three.webgpu.js 1.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655
  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, 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, warnOnce, 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. * @method
  444. * @param {string} str - The string to be hashed.
  445. * @return {number} The hash.
  446. */
  447. const hashString = ( str ) => cyrb53( str );
  448. /**
  449. * Computes a hash for the given array.
  450. *
  451. * @method
  452. * @param {Array<number>} array - The array to be hashed.
  453. * @return {number} The hash.
  454. */
  455. const hashArray = ( array ) => cyrb53( array );
  456. /**
  457. * Computes a hash for the given list of parameters.
  458. *
  459. * @method
  460. * @param {...number} params - A list of parameters.
  461. * @return {number} The hash.
  462. */
  463. const hash$1 = ( ...params ) => cyrb53( params );
  464. /**
  465. * Computes a cache key for the given node.
  466. *
  467. * @method
  468. * @param {Object|Node} object - The object to be hashed.
  469. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  470. * @return {number} The hash.
  471. */
  472. function getCacheKey$1( object, force = false ) {
  473. const values = [];
  474. if ( object.isNode === true ) {
  475. values.push( object.id );
  476. }
  477. for ( const { property, childNode } of getNodeChildren( object ) ) {
  478. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  479. }
  480. return cyrb53( values );
  481. }
  482. /**
  483. * This generator function can be used to iterate over the node children
  484. * of the given object.
  485. *
  486. * @generator
  487. * @param {Object} node - The object to be hashed.
  488. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  489. * @yields {Object} A result node holding the property, index (if available) and the child node.
  490. */
  491. function* getNodeChildren( node, toJSON = false ) {
  492. for ( const property of Object.getOwnPropertyNames( node ) ) {
  493. // Ignore private properties.
  494. if ( property.startsWith( '_' ) === true ) continue;
  495. const object = node[ property ];
  496. if ( Array.isArray( object ) === true ) {
  497. for ( let i = 0; i < object.length; i ++ ) {
  498. const child = object[ i ];
  499. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  500. yield { property, index: i, childNode: child };
  501. }
  502. }
  503. } else if ( object && object.isNode === true ) {
  504. yield { property, childNode: object };
  505. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  506. for ( const subProperty in object ) {
  507. // Ignore private properties.
  508. if ( subProperty.startsWith( '_' ) === true ) continue;
  509. const child = object[ subProperty ];
  510. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  511. yield { property, index: subProperty, childNode: child };
  512. }
  513. }
  514. }
  515. }
  516. }
  517. const typeFromLength = /*@__PURE__*/ new Map( [
  518. [ 1, 'float' ],
  519. [ 2, 'vec2' ],
  520. [ 3, 'vec3' ],
  521. [ 4, 'vec4' ],
  522. [ 9, 'mat3' ],
  523. [ 16, 'mat4' ]
  524. ] );
  525. const dataFromObject = /*@__PURE__*/ new WeakMap();
  526. /**
  527. * Returns the data type for the given the length.
  528. *
  529. * @method
  530. * @param {number} length - The length.
  531. * @return {string} The data type.
  532. */
  533. function getTypeFromLength( length ) {
  534. return typeFromLength.get( length );
  535. }
  536. /**
  537. * Returns the typed array for the given data type.
  538. *
  539. * @method
  540. * @param {string} type - The data type.
  541. * @return {TypedArray} The typed array.
  542. */
  543. function getTypedArrayFromType( type ) {
  544. // Handle component type for vectors and matrices
  545. if ( /[iu]?vec\d/.test( type ) ) {
  546. // Handle int vectors
  547. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  548. // Handle uint vectors
  549. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  550. // Default to float vectors
  551. return Float32Array;
  552. }
  553. // Handle matrices (always float)
  554. if ( /mat\d/.test( type ) ) return Float32Array;
  555. // Basic types
  556. if ( /float/.test( type ) ) return Float32Array;
  557. if ( /uint/.test( type ) ) return Uint32Array;
  558. if ( /int/.test( type ) ) return Int32Array;
  559. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  560. }
  561. /**
  562. * Returns the length for the given data type.
  563. *
  564. * @method
  565. * @param {string} type - The data type.
  566. * @return {number} The length.
  567. */
  568. function getLengthFromType( type ) {
  569. if ( /float|int|uint/.test( type ) ) return 1;
  570. if ( /vec2/.test( type ) ) return 2;
  571. if ( /vec3/.test( type ) ) return 3;
  572. if ( /vec4/.test( type ) ) return 4;
  573. if ( /mat2/.test( type ) ) return 4;
  574. if ( /mat3/.test( type ) ) return 9;
  575. if ( /mat4/.test( type ) ) return 16;
  576. error( 'TSL: Unsupported type:', type );
  577. }
  578. /**
  579. * Returns the gpu memory length for the given data type.
  580. *
  581. * @method
  582. * @param {string} type - The data type.
  583. * @return {number} The length.
  584. */
  585. function getMemoryLengthFromType( type ) {
  586. if ( /float|int|uint/.test( type ) ) return 1;
  587. if ( /vec2/.test( type ) ) return 2;
  588. if ( /vec3/.test( type ) ) return 3;
  589. if ( /vec4/.test( type ) ) return 4;
  590. if ( /mat2/.test( type ) ) return 4;
  591. if ( /mat3/.test( type ) ) return 12;
  592. if ( /mat4/.test( type ) ) return 16;
  593. error( 'TSL: Unsupported type:', type );
  594. }
  595. /**
  596. * Returns the byte boundary for the given data type.
  597. *
  598. * @method
  599. * @param {string} type - The data type.
  600. * @return {number} The byte boundary.
  601. */
  602. function getByteBoundaryFromType( type ) {
  603. if ( /float|int|uint/.test( type ) ) return 4;
  604. if ( /vec2/.test( type ) ) return 8;
  605. if ( /vec3/.test( type ) ) return 16;
  606. if ( /vec4/.test( type ) ) return 16;
  607. if ( /mat2/.test( type ) ) return 8;
  608. if ( /mat3/.test( type ) ) return 48;
  609. if ( /mat4/.test( type ) ) return 64;
  610. error( 'TSL: Unsupported type:', type );
  611. }
  612. /**
  613. * Returns the data type for the given value.
  614. *
  615. * @method
  616. * @param {any} value - The value.
  617. * @return {?string} The data type.
  618. */
  619. function getValueType( value ) {
  620. if ( value === undefined || value === null ) return null;
  621. const typeOf = typeof value;
  622. if ( value.isNode === true ) {
  623. return 'node';
  624. } else if ( typeOf === 'number' ) {
  625. return 'float';
  626. } else if ( typeOf === 'boolean' ) {
  627. return 'bool';
  628. } else if ( typeOf === 'string' ) {
  629. return 'string';
  630. } else if ( typeOf === 'function' ) {
  631. return 'shader';
  632. } else if ( value.isVector2 === true ) {
  633. return 'vec2';
  634. } else if ( value.isVector3 === true ) {
  635. return 'vec3';
  636. } else if ( value.isVector4 === true ) {
  637. return 'vec4';
  638. } else if ( value.isMatrix2 === true ) {
  639. return 'mat2';
  640. } else if ( value.isMatrix3 === true ) {
  641. return 'mat3';
  642. } else if ( value.isMatrix4 === true ) {
  643. return 'mat4';
  644. } else if ( value.isColor === true ) {
  645. return 'color';
  646. } else if ( value instanceof ArrayBuffer ) {
  647. return 'ArrayBuffer';
  648. }
  649. return null;
  650. }
  651. /**
  652. * Returns the value/object for the given data type and parameters.
  653. *
  654. * @method
  655. * @param {string} type - The given type.
  656. * @param {...any} params - A parameter list.
  657. * @return {any} The value/object.
  658. */
  659. function getValueFromType( type, ...params ) {
  660. const last4 = type ? type.slice( -4 ) : undefined;
  661. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  662. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  663. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  664. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  665. }
  666. if ( type === 'color' ) {
  667. return new Color( ...params );
  668. } else if ( last4 === 'vec2' ) {
  669. return new Vector2( ...params );
  670. } else if ( last4 === 'vec3' ) {
  671. return new Vector3( ...params );
  672. } else if ( last4 === 'vec4' ) {
  673. return new Vector4( ...params );
  674. } else if ( last4 === 'mat2' ) {
  675. return new Matrix2( ...params );
  676. } else if ( last4 === 'mat3' ) {
  677. return new Matrix3( ...params );
  678. } else if ( last4 === 'mat4' ) {
  679. return new Matrix4( ...params );
  680. } else if ( type === 'bool' ) {
  681. return params[ 0 ] || false;
  682. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  683. return params[ 0 ] || 0;
  684. } else if ( type === 'string' ) {
  685. return params[ 0 ] || '';
  686. } else if ( type === 'ArrayBuffer' ) {
  687. return base64ToArrayBuffer( params[ 0 ] );
  688. }
  689. return null;
  690. }
  691. /**
  692. * Gets the object data that can be shared between different rendering steps.
  693. *
  694. * @param {Object} object - The object to get the data for.
  695. * @return {Object} The object data.
  696. */
  697. function getDataFromObject( object ) {
  698. let data = dataFromObject.get( object );
  699. if ( data === undefined ) {
  700. data = {};
  701. dataFromObject.set( object, data );
  702. }
  703. return data;
  704. }
  705. /**
  706. * Converts the given array buffer to a Base64 string.
  707. *
  708. * @method
  709. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  710. * @return {string} The Base64 string.
  711. */
  712. function arrayBufferToBase64( arrayBuffer ) {
  713. let chars = '';
  714. const array = new Uint8Array( arrayBuffer );
  715. for ( let i = 0; i < array.length; i ++ ) {
  716. chars += String.fromCharCode( array[ i ] );
  717. }
  718. return btoa( chars );
  719. }
  720. /**
  721. * Converts the given Base64 string to an array buffer.
  722. *
  723. * @method
  724. * @param {string} base64 - The Base64 string.
  725. * @return {ArrayBuffer} The array buffer.
  726. */
  727. function base64ToArrayBuffer( base64 ) {
  728. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  729. }
  730. var NodeUtils = /*#__PURE__*/Object.freeze({
  731. __proto__: null,
  732. arrayBufferToBase64: arrayBufferToBase64,
  733. base64ToArrayBuffer: base64ToArrayBuffer,
  734. getByteBoundaryFromType: getByteBoundaryFromType,
  735. getCacheKey: getCacheKey$1,
  736. getDataFromObject: getDataFromObject,
  737. getLengthFromType: getLengthFromType,
  738. getMemoryLengthFromType: getMemoryLengthFromType,
  739. getNodeChildren: getNodeChildren,
  740. getTypeFromLength: getTypeFromLength,
  741. getTypedArrayFromType: getTypedArrayFromType,
  742. getValueFromType: getValueFromType,
  743. getValueType: getValueType,
  744. hash: hash$1,
  745. hashArray: hashArray,
  746. hashString: hashString
  747. });
  748. /**
  749. * Possible shader stages.
  750. *
  751. * @property {string} VERTEX The vertex shader stage.
  752. * @property {string} FRAGMENT The fragment shader stage.
  753. */
  754. const NodeShaderStage = {
  755. VERTEX: 'vertex',
  756. FRAGMENT: 'fragment'
  757. };
  758. /**
  759. * Update types of a node.
  760. *
  761. * @property {string} NONE The update method is not executed.
  762. * @property {string} FRAME The update method is executed per frame.
  763. * @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.
  764. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  765. */
  766. const NodeUpdateType = {
  767. NONE: 'none',
  768. FRAME: 'frame',
  769. RENDER: 'render',
  770. OBJECT: 'object'
  771. };
  772. /**
  773. * Data types of a node.
  774. *
  775. * @property {string} BOOLEAN Boolean type.
  776. * @property {string} INTEGER Integer type.
  777. * @property {string} FLOAT Float type.
  778. * @property {string} VECTOR2 Two-dimensional vector type.
  779. * @property {string} VECTOR3 Three-dimensional vector type.
  780. * @property {string} VECTOR4 Four-dimensional vector type.
  781. * @property {string} MATRIX2 2x2 matrix type.
  782. * @property {string} MATRIX3 3x3 matrix type.
  783. * @property {string} MATRIX4 4x4 matrix type.
  784. */
  785. const NodeType = {
  786. BOOLEAN: 'bool',
  787. INTEGER: 'int',
  788. FLOAT: 'float',
  789. VECTOR2: 'vec2',
  790. VECTOR3: 'vec3',
  791. VECTOR4: 'vec4',
  792. MATRIX2: 'mat2',
  793. MATRIX3: 'mat3',
  794. MATRIX4: 'mat4'
  795. };
  796. /**
  797. * Access types of a node. These are relevant for compute and storage usage.
  798. *
  799. * @property {string} READ_ONLY Read-only access
  800. * @property {string} WRITE_ONLY Write-only access.
  801. * @property {string} READ_WRITE Read and write access.
  802. */
  803. const NodeAccess = {
  804. READ_ONLY: 'readOnly',
  805. WRITE_ONLY: 'writeOnly',
  806. READ_WRITE: 'readWrite',
  807. };
  808. const defaultShaderStages = [ 'fragment', 'vertex' ];
  809. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  810. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  811. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  812. const _parentBuildStage = {
  813. analyze: 'setup',
  814. generate: 'analyze'
  815. };
  816. let _nodeId = 0;
  817. /**
  818. * Base class for all nodes.
  819. *
  820. * @augments EventDispatcher
  821. */
  822. class Node extends EventDispatcher {
  823. static get type() {
  824. return 'Node';
  825. }
  826. /**
  827. * Constructs a new node.
  828. *
  829. * @param {?string} nodeType - The node type.
  830. */
  831. constructor( nodeType = null ) {
  832. super();
  833. /**
  834. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  835. *
  836. * @type {?string}
  837. * @default null
  838. */
  839. this.nodeType = nodeType;
  840. /**
  841. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  842. *
  843. * @type {string}
  844. * @default 'none'
  845. */
  846. this.updateType = NodeUpdateType.NONE;
  847. /**
  848. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  849. *
  850. * @type {string}
  851. * @default 'none'
  852. */
  853. this.updateBeforeType = NodeUpdateType.NONE;
  854. /**
  855. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  856. *
  857. * @type {string}
  858. * @default 'none'
  859. */
  860. this.updateAfterType = NodeUpdateType.NONE;
  861. /**
  862. * The UUID of the node.
  863. *
  864. * @type {string}
  865. * @readonly
  866. */
  867. this.uuid = MathUtils.generateUUID();
  868. /**
  869. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  870. *
  871. * @type {number}
  872. * @readonly
  873. * @default 0
  874. */
  875. this.version = 0;
  876. /**
  877. * The name of the node.
  878. *
  879. * @type {string}
  880. * @default ''
  881. */
  882. this.name = '';
  883. /**
  884. * Whether this node is global or not. This property is relevant for the internal
  885. * node caching system. All nodes which should be declared just once should
  886. * set this flag to `true` (a typical example is {@link AttributeNode}).
  887. *
  888. * @type {boolean}
  889. * @default false
  890. */
  891. this.global = false;
  892. /**
  893. * Create a list of parents for this node during the build process.
  894. *
  895. * @type {boolean}
  896. * @default false
  897. */
  898. this.parents = false;
  899. /**
  900. * This flag can be used for type testing.
  901. *
  902. * @type {boolean}
  903. * @readonly
  904. * @default true
  905. */
  906. this.isNode = true;
  907. // private
  908. this._beforeNodes = null;
  909. /**
  910. * The cache key of this node.
  911. *
  912. * @private
  913. * @type {?number}
  914. * @default null
  915. */
  916. this._cacheKey = null;
  917. /**
  918. * The cache key 's version.
  919. *
  920. * @private
  921. * @type {number}
  922. * @default 0
  923. */
  924. this._cacheKeyVersion = 0;
  925. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  926. }
  927. /**
  928. * Set this property to `true` when the node should be regenerated.
  929. *
  930. * @type {boolean}
  931. * @default false
  932. * @param {boolean} value
  933. */
  934. set needsUpdate( value ) {
  935. if ( value === true ) {
  936. this.version ++;
  937. }
  938. }
  939. /**
  940. * The type of the class. The value is usually the constructor name.
  941. *
  942. * @type {string}
  943. * @readonly
  944. */
  945. get type() {
  946. return this.constructor.type;
  947. }
  948. /**
  949. * Convenient method for defining {@link Node#update}.
  950. *
  951. * @param {Function} callback - The update method.
  952. * @param {string} updateType - The update type.
  953. * @return {Node} A reference to this node.
  954. */
  955. onUpdate( callback, updateType ) {
  956. this.updateType = updateType;
  957. this.update = callback.bind( this );
  958. return this;
  959. }
  960. /**
  961. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  962. * this method automatically sets the update type to `FRAME`.
  963. *
  964. * @param {Function} callback - The update method.
  965. * @return {Node} A reference to this node.
  966. */
  967. onFrameUpdate( callback ) {
  968. return this.onUpdate( callback, NodeUpdateType.FRAME );
  969. }
  970. /**
  971. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  972. * this method automatically sets the update type to `RENDER`.
  973. *
  974. * @param {Function} callback - The update method.
  975. * @return {Node} A reference to this node.
  976. */
  977. onRenderUpdate( callback ) {
  978. return this.onUpdate( callback, NodeUpdateType.RENDER );
  979. }
  980. /**
  981. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  982. * this method automatically sets the update type to `OBJECT`.
  983. *
  984. * @param {Function} callback - The update method.
  985. * @return {Node} A reference to this node.
  986. */
  987. onObjectUpdate( callback ) {
  988. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  989. }
  990. /**
  991. * Convenient method for defining {@link Node#updateReference}.
  992. *
  993. * @param {Function} callback - The update method.
  994. * @return {Node} A reference to this node.
  995. */
  996. onReference( callback ) {
  997. this.updateReference = callback.bind( this );
  998. return this;
  999. }
  1000. /**
  1001. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1002. * to such objects based on a given state (e.g. the current node frame or builder).
  1003. *
  1004. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1005. * @return {any} The updated reference.
  1006. */
  1007. updateReference( /*state*/ ) {
  1008. return this;
  1009. }
  1010. /**
  1011. * By default this method returns the value of the {@link Node#global} flag. This method
  1012. * can be overwritten in derived classes if an analytical way is required to determine the
  1013. * global cache referring to the current shader-stage.
  1014. *
  1015. * @param {NodeBuilder} builder - The current node builder.
  1016. * @return {boolean} Whether this node is global or not.
  1017. */
  1018. isGlobal( /*builder*/ ) {
  1019. return this.global;
  1020. }
  1021. /**
  1022. * Generator function that can be used to iterate over the child nodes.
  1023. *
  1024. * @generator
  1025. * @yields {Node} A child node.
  1026. */
  1027. * getChildren() {
  1028. for ( const { childNode } of getNodeChildren( this ) ) {
  1029. yield childNode;
  1030. }
  1031. }
  1032. /**
  1033. * Calling this method dispatches the `dispose` event. This event can be used
  1034. * to register event listeners for clean up tasks.
  1035. */
  1036. dispose() {
  1037. this.dispatchEvent( { type: 'dispose' } );
  1038. }
  1039. /**
  1040. * Callback for {@link Node#traverse}.
  1041. *
  1042. * @callback traverseCallback
  1043. * @param {Node} node - The current node.
  1044. */
  1045. /**
  1046. * Can be used to traverse through the node's hierarchy.
  1047. *
  1048. * @param {traverseCallback} callback - A callback that is executed per node.
  1049. */
  1050. traverse( callback ) {
  1051. callback( this );
  1052. for ( const childNode of this.getChildren() ) {
  1053. childNode.traverse( callback );
  1054. }
  1055. }
  1056. /**
  1057. * Returns the cache key for this node.
  1058. *
  1059. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1060. * @return {number} The cache key of the node.
  1061. */
  1062. getCacheKey( force = false ) {
  1063. force = force || this.version !== this._cacheKeyVersion;
  1064. if ( force === true || this._cacheKey === null ) {
  1065. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1066. this._cacheKeyVersion = this.version;
  1067. }
  1068. return this._cacheKey;
  1069. }
  1070. /**
  1071. * Generate a custom cache key for this node.
  1072. *
  1073. * @return {number} The cache key of the node.
  1074. */
  1075. customCacheKey() {
  1076. return 0;
  1077. }
  1078. /**
  1079. * Returns the references to this node which is by default `this`.
  1080. *
  1081. * @return {Node} A reference to this node.
  1082. */
  1083. getScope() {
  1084. return this;
  1085. }
  1086. /**
  1087. * Returns the hash of the node which is used to identify the node. By default it's
  1088. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1089. * depending on their implementation.
  1090. *
  1091. * @param {NodeBuilder} builder - The current node builder.
  1092. * @return {string} The hash.
  1093. */
  1094. getHash( /*builder*/ ) {
  1095. return this.uuid;
  1096. }
  1097. /**
  1098. * Returns the update type of {@link Node#update}.
  1099. *
  1100. * @return {NodeUpdateType} The update type.
  1101. */
  1102. getUpdateType() {
  1103. return this.updateType;
  1104. }
  1105. /**
  1106. * Returns the update type of {@link Node#updateBefore}.
  1107. *
  1108. * @return {NodeUpdateType} The update type.
  1109. */
  1110. getUpdateBeforeType() {
  1111. return this.updateBeforeType;
  1112. }
  1113. /**
  1114. * Returns the update type of {@link Node#updateAfter}.
  1115. *
  1116. * @return {NodeUpdateType} The update type.
  1117. */
  1118. getUpdateAfterType() {
  1119. return this.updateAfterType;
  1120. }
  1121. /**
  1122. * Certain types are composed of multiple elements. For example a `vec3`
  1123. * is composed of three `float` values. This method returns the type of
  1124. * these elements.
  1125. *
  1126. * @param {NodeBuilder} builder - The current node builder.
  1127. * @return {string} The type of the node.
  1128. */
  1129. getElementType( builder ) {
  1130. const type = this.getNodeType( builder );
  1131. const elementType = builder.getElementType( type );
  1132. return elementType;
  1133. }
  1134. /**
  1135. * Returns the node member type for the given name.
  1136. *
  1137. * @param {NodeBuilder} builder - The current node builder.
  1138. * @param {string} name - The name of the member.
  1139. * @return {string} The type of the node.
  1140. */
  1141. getMemberType( /*builder, name*/ ) {
  1142. return 'void';
  1143. }
  1144. /**
  1145. * Returns the node's type.
  1146. *
  1147. * @param {NodeBuilder} builder - The current node builder.
  1148. * @return {string} The type of the node.
  1149. */
  1150. getNodeType( builder ) {
  1151. const nodeProperties = builder.getNodeProperties( this );
  1152. if ( nodeProperties.outputNode ) {
  1153. return nodeProperties.outputNode.getNodeType( builder );
  1154. }
  1155. return this.nodeType;
  1156. }
  1157. /**
  1158. * This method is used during the build process of a node and ensures
  1159. * equal nodes are not built multiple times but just once. For example if
  1160. * `attribute( 'uv' )` is used multiple times by the user, the build
  1161. * process makes sure to process just the first node.
  1162. *
  1163. * @param {NodeBuilder} builder - The current node builder.
  1164. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1165. */
  1166. getShared( builder ) {
  1167. const hash = this.getHash( builder );
  1168. const nodeFromHash = builder.getNodeFromHash( hash );
  1169. return nodeFromHash || this;
  1170. }
  1171. /**
  1172. * Returns the number of elements in the node array.
  1173. *
  1174. * @param {NodeBuilder} builder - The current node builder.
  1175. * @return {?number} The number of elements in the node array.
  1176. */
  1177. getArrayCount( /*builder*/ ) {
  1178. return null;
  1179. }
  1180. /**
  1181. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1182. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1183. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1184. *
  1185. * @param {NodeBuilder} builder - The current node builder.
  1186. * @return {?Node} The output node.
  1187. */
  1188. setup( builder ) {
  1189. const nodeProperties = builder.getNodeProperties( this );
  1190. let index = 0;
  1191. for ( const childNode of this.getChildren() ) {
  1192. nodeProperties[ 'node' + index ++ ] = childNode;
  1193. }
  1194. // return a outputNode if exists or null
  1195. return nodeProperties.outputNode || null;
  1196. }
  1197. /**
  1198. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1199. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1200. *
  1201. * @param {NodeBuilder} builder - The current node builder.
  1202. * @param {?Node} output - The target output node.
  1203. */
  1204. analyze( builder, output = null ) {
  1205. const usageCount = builder.increaseUsage( this );
  1206. if ( this.parents === true ) {
  1207. const nodeData = builder.getDataFromNode( this, 'any' );
  1208. nodeData.stages = nodeData.stages || {};
  1209. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1210. nodeData.stages[ builder.shaderStage ].push( output );
  1211. }
  1212. if ( usageCount === 1 ) {
  1213. // node flow children
  1214. const nodeProperties = builder.getNodeProperties( this );
  1215. for ( const childNode of Object.values( nodeProperties ) ) {
  1216. if ( childNode && childNode.isNode === true ) {
  1217. childNode.build( builder, this );
  1218. }
  1219. }
  1220. }
  1221. }
  1222. /**
  1223. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1224. * This state builds the output node and returns the resulting shader string.
  1225. *
  1226. * @param {NodeBuilder} builder - The current node builder.
  1227. * @param {?string} [output] - Can be used to define the output type.
  1228. * @return {?string} The generated shader string.
  1229. */
  1230. generate( builder, output ) {
  1231. const { outputNode } = builder.getNodeProperties( this );
  1232. if ( outputNode && outputNode.isNode === true ) {
  1233. return outputNode.build( builder, output );
  1234. }
  1235. }
  1236. /**
  1237. * The method can be implemented to update the node's internal state before it is used to render an object.
  1238. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1239. *
  1240. * @abstract
  1241. * @param {NodeFrame} frame - A reference to the current node frame.
  1242. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1243. */
  1244. updateBefore( /*frame*/ ) {
  1245. warn( 'Abstract function.' );
  1246. }
  1247. /**
  1248. * The method can be implemented to update the node's internal state after it was used to render an object.
  1249. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1250. *
  1251. * @abstract
  1252. * @param {NodeFrame} frame - A reference to the current node frame.
  1253. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1254. */
  1255. updateAfter( /*frame*/ ) {
  1256. warn( 'Abstract function.' );
  1257. }
  1258. /**
  1259. * The method can be implemented to update the node's internal state when it is used to render an object.
  1260. * The {@link Node#updateType} property defines how often the update is executed.
  1261. *
  1262. * @abstract
  1263. * @param {NodeFrame} frame - A reference to the current node frame.
  1264. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1265. */
  1266. update( /*frame*/ ) {
  1267. warn( 'Abstract function.' );
  1268. }
  1269. before( node ) {
  1270. if ( this._beforeNodes === null ) this._beforeNodes = [];
  1271. this._beforeNodes.push( node );
  1272. return this;
  1273. }
  1274. /**
  1275. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1276. * - **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.
  1277. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1278. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1279. *
  1280. * @param {NodeBuilder} builder - The current node builder.
  1281. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1282. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1283. */
  1284. build( builder, output = null ) {
  1285. const refNode = this.getShared( builder );
  1286. if ( this !== refNode ) {
  1287. return refNode.build( builder, output );
  1288. }
  1289. //
  1290. if ( this._beforeNodes !== null ) {
  1291. const currentBeforeNodes = this._beforeNodes;
  1292. this._beforeNodes = null;
  1293. for ( const beforeNode of currentBeforeNodes ) {
  1294. beforeNode.build( builder, output );
  1295. }
  1296. this._beforeNodes = currentBeforeNodes;
  1297. }
  1298. //
  1299. const nodeData = builder.getDataFromNode( this );
  1300. nodeData.buildStages = nodeData.buildStages || {};
  1301. nodeData.buildStages[ builder.buildStage ] = true;
  1302. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1303. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1304. // force parent build stage (setup or analyze)
  1305. const previousBuildStage = builder.getBuildStage();
  1306. builder.setBuildStage( parentBuildStage );
  1307. this.build( builder );
  1308. builder.setBuildStage( previousBuildStage );
  1309. }
  1310. //
  1311. builder.addNode( this );
  1312. builder.addChain( this );
  1313. /* Build stages expected results:
  1314. - "setup" -> Node
  1315. - "analyze" -> null
  1316. - "generate" -> String
  1317. */
  1318. let result = null;
  1319. const buildStage = builder.getBuildStage();
  1320. if ( buildStage === 'setup' ) {
  1321. this.updateReference( builder );
  1322. const properties = builder.getNodeProperties( this );
  1323. if ( properties.initialized !== true ) {
  1324. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1325. properties.initialized = true;
  1326. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1327. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1328. // !! no outputNode !!
  1329. //outputNode = builder.stack;
  1330. }*/
  1331. for ( const childNode of Object.values( properties ) ) {
  1332. if ( childNode && childNode.isNode === true ) {
  1333. if ( childNode.parents === true ) {
  1334. const childProperties = builder.getNodeProperties( childNode );
  1335. childProperties.parents = childProperties.parents || [];
  1336. childProperties.parents.push( this );
  1337. }
  1338. childNode.build( builder );
  1339. }
  1340. }
  1341. }
  1342. result = properties.outputNode;
  1343. } else if ( buildStage === 'analyze' ) {
  1344. this.analyze( builder, output );
  1345. } else if ( buildStage === 'generate' ) {
  1346. const isGenerateOnce = this.generate.length === 1;
  1347. if ( isGenerateOnce ) {
  1348. const type = this.getNodeType( builder );
  1349. const nodeData = builder.getDataFromNode( this );
  1350. result = nodeData.snippet;
  1351. if ( result === undefined ) {
  1352. if ( nodeData.generated === undefined ) {
  1353. nodeData.generated = true;
  1354. result = this.generate( builder ) || '';
  1355. nodeData.snippet = result;
  1356. } else {
  1357. warn( 'Node: Recursion detected.', this );
  1358. result = '/* Recursion detected. */';
  1359. }
  1360. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1361. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1362. }
  1363. result = builder.format( result, type, output );
  1364. } else {
  1365. result = this.generate( builder, output ) || '';
  1366. }
  1367. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1368. // if no snippet is generated, return a default value
  1369. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1370. result = builder.generateConst( output );
  1371. }
  1372. }
  1373. builder.removeChain( this );
  1374. builder.addSequentialNode( this );
  1375. return result;
  1376. }
  1377. /**
  1378. * Returns the child nodes as a JSON object.
  1379. *
  1380. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1381. */
  1382. getSerializeChildren() {
  1383. return getNodeChildren( this );
  1384. }
  1385. /**
  1386. * Serializes the node to JSON.
  1387. *
  1388. * @param {Object} json - The output JSON object.
  1389. */
  1390. serialize( json ) {
  1391. const nodeChildren = this.getSerializeChildren();
  1392. const inputNodes = {};
  1393. for ( const { property, index, childNode } of nodeChildren ) {
  1394. if ( index !== undefined ) {
  1395. if ( inputNodes[ property ] === undefined ) {
  1396. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1397. }
  1398. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1399. } else {
  1400. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1401. }
  1402. }
  1403. if ( Object.keys( inputNodes ).length > 0 ) {
  1404. json.inputNodes = inputNodes;
  1405. }
  1406. }
  1407. /**
  1408. * Deserializes the node from the given JSON.
  1409. *
  1410. * @param {Object} json - The JSON object.
  1411. */
  1412. deserialize( json ) {
  1413. if ( json.inputNodes !== undefined ) {
  1414. const nodes = json.meta.nodes;
  1415. for ( const property in json.inputNodes ) {
  1416. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1417. const inputArray = [];
  1418. for ( const uuid of json.inputNodes[ property ] ) {
  1419. inputArray.push( nodes[ uuid ] );
  1420. }
  1421. this[ property ] = inputArray;
  1422. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1423. const inputObject = {};
  1424. for ( const subProperty in json.inputNodes[ property ] ) {
  1425. const uuid = json.inputNodes[ property ][ subProperty ];
  1426. inputObject[ subProperty ] = nodes[ uuid ];
  1427. }
  1428. this[ property ] = inputObject;
  1429. } else {
  1430. const uuid = json.inputNodes[ property ];
  1431. this[ property ] = nodes[ uuid ];
  1432. }
  1433. }
  1434. }
  1435. }
  1436. /**
  1437. * Serializes the node into the three.js JSON Object/Scene format.
  1438. *
  1439. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1440. * @return {Object} The serialized node.
  1441. */
  1442. toJSON( meta ) {
  1443. const { uuid, type } = this;
  1444. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1445. if ( isRoot ) {
  1446. meta = {
  1447. textures: {},
  1448. images: {},
  1449. nodes: {}
  1450. };
  1451. }
  1452. // serialize
  1453. let data = meta.nodes[ uuid ];
  1454. if ( data === undefined ) {
  1455. data = {
  1456. uuid,
  1457. type,
  1458. meta,
  1459. metadata: {
  1460. version: 4.7,
  1461. type: 'Node',
  1462. generator: 'Node.toJSON'
  1463. }
  1464. };
  1465. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1466. this.serialize( data );
  1467. delete data.meta;
  1468. }
  1469. // TODO: Copied from Object3D.toJSON
  1470. function extractFromCache( cache ) {
  1471. const values = [];
  1472. for ( const key in cache ) {
  1473. const data = cache[ key ];
  1474. delete data.metadata;
  1475. values.push( data );
  1476. }
  1477. return values;
  1478. }
  1479. if ( isRoot ) {
  1480. const textures = extractFromCache( meta.textures );
  1481. const images = extractFromCache( meta.images );
  1482. const nodes = extractFromCache( meta.nodes );
  1483. if ( textures.length > 0 ) data.textures = textures;
  1484. if ( images.length > 0 ) data.images = images;
  1485. if ( nodes.length > 0 ) data.nodes = nodes;
  1486. }
  1487. return data;
  1488. }
  1489. }
  1490. /**
  1491. * Base class for representing element access on an array-like
  1492. * node data structures.
  1493. *
  1494. * @augments Node
  1495. */
  1496. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1497. static get type() {
  1498. return 'ArrayElementNode';
  1499. }
  1500. /**
  1501. * Constructs an array element node.
  1502. *
  1503. * @param {Node} node - The array-like node.
  1504. * @param {Node} indexNode - The index node that defines the element access.
  1505. */
  1506. constructor( node, indexNode ) {
  1507. super();
  1508. /**
  1509. * The array-like node.
  1510. *
  1511. * @type {Node}
  1512. */
  1513. this.node = node;
  1514. /**
  1515. * The index node that defines the element access.
  1516. *
  1517. * @type {Node}
  1518. */
  1519. this.indexNode = indexNode;
  1520. /**
  1521. * This flag can be used for type testing.
  1522. *
  1523. * @type {boolean}
  1524. * @readonly
  1525. * @default true
  1526. */
  1527. this.isArrayElementNode = true;
  1528. }
  1529. /**
  1530. * This method is overwritten since the node type is inferred from the array-like node.
  1531. *
  1532. * @param {NodeBuilder} builder - The current node builder.
  1533. * @return {string} The node type.
  1534. */
  1535. getNodeType( builder ) {
  1536. return this.node.getElementType( builder );
  1537. }
  1538. generate( builder ) {
  1539. const indexType = this.indexNode.getNodeType( builder );
  1540. const nodeSnippet = this.node.build( builder );
  1541. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1542. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1543. }
  1544. }
  1545. /**
  1546. * This module is part of the TSL core and usually not used in app level code.
  1547. * It represents a convert operation during the shader generation process
  1548. * meaning it converts the data type of a node to a target data type.
  1549. *
  1550. * @augments Node
  1551. */
  1552. class ConvertNode extends Node {
  1553. static get type() {
  1554. return 'ConvertNode';
  1555. }
  1556. /**
  1557. * Constructs a new convert node.
  1558. *
  1559. * @param {Node} node - The node which type should be converted.
  1560. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1561. */
  1562. constructor( node, convertTo ) {
  1563. super();
  1564. /**
  1565. * The node which type should be converted.
  1566. *
  1567. * @type {Node}
  1568. */
  1569. this.node = node;
  1570. /**
  1571. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1572. *
  1573. * @type {string}
  1574. */
  1575. this.convertTo = convertTo;
  1576. }
  1577. /**
  1578. * This method is overwritten since the implementation tries to infer the best
  1579. * matching type from the {@link ConvertNode#convertTo} property.
  1580. *
  1581. * @param {NodeBuilder} builder - The current node builder.
  1582. * @return {string} The node type.
  1583. */
  1584. getNodeType( builder ) {
  1585. const requestType = this.node.getNodeType( builder );
  1586. let convertTo = null;
  1587. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1588. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1589. convertTo = overloadingType;
  1590. }
  1591. }
  1592. return convertTo;
  1593. }
  1594. serialize( data ) {
  1595. super.serialize( data );
  1596. data.convertTo = this.convertTo;
  1597. }
  1598. deserialize( data ) {
  1599. super.deserialize( data );
  1600. this.convertTo = data.convertTo;
  1601. }
  1602. generate( builder, output ) {
  1603. const node = this.node;
  1604. const type = this.getNodeType( builder );
  1605. const snippet = node.build( builder, type );
  1606. return builder.format( snippet, type, output );
  1607. }
  1608. }
  1609. /**
  1610. * This module uses cache management to create temporary variables
  1611. * if the node is used more than once to prevent duplicate calculations.
  1612. *
  1613. * The class acts as a base class for many other nodes types.
  1614. *
  1615. * @augments Node
  1616. */
  1617. class TempNode extends Node {
  1618. static get type() {
  1619. return 'TempNode';
  1620. }
  1621. /**
  1622. * Constructs a temp node.
  1623. *
  1624. * @param {?string} nodeType - The node type.
  1625. */
  1626. constructor( nodeType = null ) {
  1627. super( nodeType );
  1628. /**
  1629. * This flag can be used for type testing.
  1630. *
  1631. * @type {boolean}
  1632. * @readonly
  1633. * @default true
  1634. */
  1635. this.isTempNode = true;
  1636. }
  1637. /**
  1638. * Whether this node is used more than once in context of other nodes.
  1639. *
  1640. * @param {NodeBuilder} builder - The node builder.
  1641. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1642. */
  1643. hasDependencies( builder ) {
  1644. return builder.getDataFromNode( this ).usageCount > 1;
  1645. }
  1646. build( builder, output ) {
  1647. const buildStage = builder.getBuildStage();
  1648. if ( buildStage === 'generate' ) {
  1649. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1650. const nodeData = builder.getDataFromNode( this );
  1651. if ( nodeData.propertyName !== undefined ) {
  1652. return builder.format( nodeData.propertyName, type, output );
  1653. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1654. const snippet = super.build( builder, type );
  1655. const nodeVar = builder.getVarFromNode( this, null, type );
  1656. const propertyName = builder.getPropertyName( nodeVar );
  1657. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1658. nodeData.snippet = snippet;
  1659. nodeData.propertyName = propertyName;
  1660. return builder.format( nodeData.propertyName, type, output );
  1661. }
  1662. }
  1663. return super.build( builder, output );
  1664. }
  1665. }
  1666. /**
  1667. * This module is part of the TSL core and usually not used in app level code.
  1668. * It represents a join operation during the shader generation process.
  1669. * For example in can compose/join two single floats into a `vec2` type.
  1670. *
  1671. * @augments TempNode
  1672. */
  1673. class JoinNode extends TempNode {
  1674. static get type() {
  1675. return 'JoinNode';
  1676. }
  1677. /**
  1678. * Constructs a new join node.
  1679. *
  1680. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1681. * @param {?string} [nodeType=null] - The node type.
  1682. */
  1683. constructor( nodes = [], nodeType = null ) {
  1684. super( nodeType );
  1685. /**
  1686. * An array of nodes that should be joined.
  1687. *
  1688. * @type {Array<Node>}
  1689. */
  1690. this.nodes = nodes;
  1691. }
  1692. /**
  1693. * This method is overwritten since the node type must be inferred from the
  1694. * joined data length if not explicitly defined.
  1695. *
  1696. * @param {NodeBuilder} builder - The current node builder.
  1697. * @return {string} The node type.
  1698. */
  1699. getNodeType( builder ) {
  1700. if ( this.nodeType !== null ) {
  1701. return builder.getVectorType( this.nodeType );
  1702. }
  1703. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1704. }
  1705. generate( builder, output ) {
  1706. const type = this.getNodeType( builder );
  1707. const maxLength = builder.getTypeLength( type );
  1708. const nodes = this.nodes;
  1709. const primitiveType = builder.getComponentType( type );
  1710. const snippetValues = [];
  1711. let length = 0;
  1712. for ( const input of nodes ) {
  1713. if ( length >= maxLength ) {
  1714. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1715. break;
  1716. }
  1717. let inputType = input.getNodeType( builder );
  1718. let inputTypeLength = builder.getTypeLength( inputType );
  1719. let inputSnippet;
  1720. if ( length + inputTypeLength > maxLength ) {
  1721. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1722. inputTypeLength = maxLength - length;
  1723. inputType = builder.getTypeFromLength( inputTypeLength );
  1724. }
  1725. length += inputTypeLength;
  1726. inputSnippet = input.build( builder, inputType );
  1727. const inputPrimitiveType = builder.getComponentType( inputType );
  1728. if ( inputPrimitiveType !== primitiveType ) {
  1729. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1730. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1731. }
  1732. snippetValues.push( inputSnippet );
  1733. }
  1734. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1735. return builder.format( snippet, type, output );
  1736. }
  1737. }
  1738. const _stringVectorComponents = vectorComponents.join( '' );
  1739. /**
  1740. * This module is part of the TSL core and usually not used in app level code.
  1741. * `SplitNode` represents a property access operation which means it is
  1742. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1743. * For example:
  1744. * ```js
  1745. * const redValue = color.r;
  1746. * ```
  1747. *
  1748. * @augments Node
  1749. */
  1750. class SplitNode extends Node {
  1751. static get type() {
  1752. return 'SplitNode';
  1753. }
  1754. /**
  1755. * Constructs a new split node.
  1756. *
  1757. * @param {Node} node - The node that should be accessed.
  1758. * @param {string} [components='x'] - The components that should be accessed.
  1759. */
  1760. constructor( node, components = 'x' ) {
  1761. super();
  1762. /**
  1763. * The node that should be accessed.
  1764. *
  1765. * @type {Node}
  1766. */
  1767. this.node = node;
  1768. /**
  1769. * The components that should be accessed.
  1770. *
  1771. * @type {string}
  1772. */
  1773. this.components = components;
  1774. /**
  1775. * This flag can be used for type testing.
  1776. *
  1777. * @type {boolean}
  1778. * @readonly
  1779. * @default true
  1780. */
  1781. this.isSplitNode = true;
  1782. }
  1783. /**
  1784. * Returns the vector length which is computed based on the requested components.
  1785. *
  1786. * @return {number} The vector length.
  1787. */
  1788. getVectorLength() {
  1789. let vectorLength = this.components.length;
  1790. for ( const c of this.components ) {
  1791. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1792. }
  1793. return vectorLength;
  1794. }
  1795. /**
  1796. * Returns the component type of the node's type.
  1797. *
  1798. * @param {NodeBuilder} builder - The current node builder.
  1799. * @return {string} The component type.
  1800. */
  1801. getComponentType( builder ) {
  1802. return builder.getComponentType( this.node.getNodeType( builder ) );
  1803. }
  1804. /**
  1805. * This method is overwritten since the node type is inferred from requested components.
  1806. *
  1807. * @param {NodeBuilder} builder - The current node builder.
  1808. * @return {string} The node type.
  1809. */
  1810. getNodeType( builder ) {
  1811. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1812. }
  1813. /**
  1814. * Returns the scope of the node.
  1815. *
  1816. * @return {Node} The scope of the node.
  1817. */
  1818. getScope() {
  1819. return this.node.getScope();
  1820. }
  1821. generate( builder, output ) {
  1822. const node = this.node;
  1823. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1824. let snippet = null;
  1825. if ( nodeTypeLength > 1 ) {
  1826. let type = null;
  1827. const componentsLength = this.getVectorLength();
  1828. if ( componentsLength >= nodeTypeLength ) {
  1829. // needed expand the input node
  1830. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1831. }
  1832. const nodeSnippet = node.build( builder, type );
  1833. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1834. // unnecessary swizzle
  1835. snippet = builder.format( nodeSnippet, type, output );
  1836. } else {
  1837. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1838. }
  1839. } else {
  1840. // ignore .components if .node returns float/integer
  1841. snippet = node.build( builder, output );
  1842. }
  1843. return snippet;
  1844. }
  1845. serialize( data ) {
  1846. super.serialize( data );
  1847. data.components = this.components;
  1848. }
  1849. deserialize( data ) {
  1850. super.deserialize( data );
  1851. this.components = data.components;
  1852. }
  1853. }
  1854. /**
  1855. * This module is part of the TSL core and usually not used in app level code.
  1856. * `SetNode` represents a set operation which means it is used to implement any
  1857. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1858. * For example:
  1859. * ```js
  1860. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1861. * ```
  1862. *
  1863. * @augments TempNode
  1864. */
  1865. class SetNode extends TempNode {
  1866. static get type() {
  1867. return 'SetNode';
  1868. }
  1869. /**
  1870. * Constructs a new set node.
  1871. *
  1872. * @param {Node} sourceNode - The node that should be updated.
  1873. * @param {string} components - The components that should be updated.
  1874. * @param {Node} targetNode - The value node.
  1875. */
  1876. constructor( sourceNode, components, targetNode ) {
  1877. super();
  1878. /**
  1879. * The node that should be updated.
  1880. *
  1881. * @type {Node}
  1882. */
  1883. this.sourceNode = sourceNode;
  1884. /**
  1885. * The components that should be updated.
  1886. *
  1887. * @type {string}
  1888. */
  1889. this.components = components;
  1890. /**
  1891. * The value node.
  1892. *
  1893. * @type {Node}
  1894. */
  1895. this.targetNode = targetNode;
  1896. }
  1897. /**
  1898. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1899. *
  1900. * @param {NodeBuilder} builder - The current node builder.
  1901. * @return {string} The node type.
  1902. */
  1903. getNodeType( builder ) {
  1904. return this.sourceNode.getNodeType( builder );
  1905. }
  1906. generate( builder ) {
  1907. const { sourceNode, components, targetNode } = this;
  1908. const sourceType = this.getNodeType( builder );
  1909. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1910. const targetType = builder.getTypeFromLength( components.length, componentType );
  1911. const targetSnippet = targetNode.build( builder, targetType );
  1912. const sourceSnippet = sourceNode.build( builder, sourceType );
  1913. const length = builder.getTypeLength( sourceType );
  1914. const snippetValues = [];
  1915. for ( let i = 0; i < length; i ++ ) {
  1916. const component = vectorComponents[ i ];
  1917. if ( component === components[ 0 ] ) {
  1918. snippetValues.push( targetSnippet );
  1919. i += components.length - 1;
  1920. } else {
  1921. snippetValues.push( sourceSnippet + '.' + component );
  1922. }
  1923. }
  1924. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1925. }
  1926. }
  1927. /**
  1928. * This module is part of the TSL core and usually not used in app level code.
  1929. * It represents a flip operation during the shader generation process
  1930. * meaning it flips normalized values with the following formula:
  1931. * ```
  1932. * x = 1 - x;
  1933. * ```
  1934. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1935. * `flipSTPQ()` method invocations on node objects. For example:
  1936. * ```js
  1937. * uvNode = uvNode.flipY();
  1938. * ```
  1939. *
  1940. * @augments TempNode
  1941. */
  1942. class FlipNode extends TempNode {
  1943. static get type() {
  1944. return 'FlipNode';
  1945. }
  1946. /**
  1947. * Constructs a new flip node.
  1948. *
  1949. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1950. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1951. */
  1952. constructor( sourceNode, components ) {
  1953. super();
  1954. /**
  1955. * The node which component(s) should be flipped.
  1956. *
  1957. * @type {Node}
  1958. */
  1959. this.sourceNode = sourceNode;
  1960. /**
  1961. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1962. *
  1963. * @type {string}
  1964. */
  1965. this.components = components;
  1966. }
  1967. /**
  1968. * This method is overwritten since the node type is inferred from the source node.
  1969. *
  1970. * @param {NodeBuilder} builder - The current node builder.
  1971. * @return {string} The node type.
  1972. */
  1973. getNodeType( builder ) {
  1974. return this.sourceNode.getNodeType( builder );
  1975. }
  1976. generate( builder ) {
  1977. const { components, sourceNode } = this;
  1978. const sourceType = this.getNodeType( builder );
  1979. const sourceSnippet = sourceNode.build( builder );
  1980. const sourceCache = builder.getVarFromNode( this );
  1981. const sourceProperty = builder.getPropertyName( sourceCache );
  1982. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1983. const length = builder.getTypeLength( sourceType );
  1984. const snippetValues = [];
  1985. let componentIndex = 0;
  1986. for ( let i = 0; i < length; i ++ ) {
  1987. const component = vectorComponents[ i ];
  1988. if ( component === components[ componentIndex ] ) {
  1989. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1990. componentIndex ++;
  1991. } else {
  1992. snippetValues.push( sourceProperty + '.' + component );
  1993. }
  1994. }
  1995. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1996. }
  1997. }
  1998. /**
  1999. * Base class for representing data input nodes.
  2000. *
  2001. * @augments Node
  2002. */
  2003. class InputNode extends Node {
  2004. static get type() {
  2005. return 'InputNode';
  2006. }
  2007. /**
  2008. * Constructs a new input node.
  2009. *
  2010. * @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).
  2011. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2012. */
  2013. constructor( value, nodeType = null ) {
  2014. super( nodeType );
  2015. /**
  2016. * This flag can be used for type testing.
  2017. *
  2018. * @type {boolean}
  2019. * @readonly
  2020. * @default true
  2021. */
  2022. this.isInputNode = true;
  2023. /**
  2024. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2025. *
  2026. * @type {any}
  2027. */
  2028. this.value = value;
  2029. /**
  2030. * The precision of the value in the shader.
  2031. *
  2032. * @type {?('low'|'medium'|'high')}
  2033. * @default null
  2034. */
  2035. this.precision = null;
  2036. }
  2037. getNodeType( /*builder*/ ) {
  2038. if ( this.nodeType === null ) {
  2039. return getValueType( this.value );
  2040. }
  2041. return this.nodeType;
  2042. }
  2043. /**
  2044. * Returns the input type of the node which is by default the node type. Derived modules
  2045. * might overwrite this method and use a fixed type or compute one analytically.
  2046. *
  2047. * A typical example for different input and node types are textures. The input type of a
  2048. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2049. *
  2050. * @param {NodeBuilder} builder - The current node builder.
  2051. * @return {string} The input type.
  2052. */
  2053. getInputType( builder ) {
  2054. return this.getNodeType( builder );
  2055. }
  2056. /**
  2057. * Sets the precision to the given value. The method can be
  2058. * overwritten in derived classes if the final precision must be computed
  2059. * analytically.
  2060. *
  2061. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2062. * @return {InputNode} A reference to this node.
  2063. */
  2064. setPrecision( precision ) {
  2065. this.precision = precision;
  2066. return this;
  2067. }
  2068. serialize( data ) {
  2069. super.serialize( data );
  2070. data.value = this.value;
  2071. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2072. data.valueType = getValueType( this.value );
  2073. data.nodeType = this.nodeType;
  2074. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2075. data.precision = this.precision;
  2076. }
  2077. deserialize( data ) {
  2078. super.deserialize( data );
  2079. this.nodeType = data.nodeType;
  2080. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2081. this.precision = data.precision || null;
  2082. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2083. }
  2084. generate( /*builder, output*/ ) {
  2085. warn( 'Abstract function.' );
  2086. }
  2087. }
  2088. const _regNum = /float|u?int/;
  2089. /**
  2090. * Class for representing a constant value in the shader.
  2091. *
  2092. * @augments InputNode
  2093. */
  2094. class ConstNode extends InputNode {
  2095. static get type() {
  2096. return 'ConstNode';
  2097. }
  2098. /**
  2099. * Constructs a new input node.
  2100. *
  2101. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2102. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2103. */
  2104. constructor( value, nodeType = null ) {
  2105. super( value, nodeType );
  2106. /**
  2107. * This flag can be used for type testing.
  2108. *
  2109. * @type {boolean}
  2110. * @readonly
  2111. * @default true
  2112. */
  2113. this.isConstNode = true;
  2114. }
  2115. /**
  2116. * Generates the shader string of the value with the current node builder.
  2117. *
  2118. * @param {NodeBuilder} builder - The current node builder.
  2119. * @return {string} The generated value as a shader string.
  2120. */
  2121. generateConst( builder ) {
  2122. return builder.generateConst( this.getNodeType( builder ), this.value );
  2123. }
  2124. generate( builder, output ) {
  2125. const type = this.getNodeType( builder );
  2126. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2127. return builder.generateConst( output, this.value );
  2128. }
  2129. return builder.format( this.generateConst( builder ), type, output );
  2130. }
  2131. }
  2132. /**
  2133. * Base class for representing member access on an object-like
  2134. * node data structures.
  2135. *
  2136. * @augments Node
  2137. */
  2138. class MemberNode extends Node {
  2139. static get type() {
  2140. return 'MemberNode';
  2141. }
  2142. /**
  2143. * Constructs a member node.
  2144. *
  2145. * @param {Node} structNode - The struct node.
  2146. * @param {string} property - The property name.
  2147. */
  2148. constructor( structNode, property ) {
  2149. super();
  2150. /**
  2151. * The struct node.
  2152. *
  2153. * @type {Node}
  2154. */
  2155. this.structNode = structNode;
  2156. /**
  2157. * The property name.
  2158. *
  2159. * @type {Node}
  2160. */
  2161. this.property = property;
  2162. /**
  2163. * This flag can be used for type testing.
  2164. *
  2165. * @type {boolean}
  2166. * @readonly
  2167. * @default true
  2168. */
  2169. this.isMemberNode = true;
  2170. }
  2171. hasMember( builder ) {
  2172. if ( this.structNode.isMemberNode ) {
  2173. if ( this.structNode.hasMember( builder ) === false ) {
  2174. return false;
  2175. }
  2176. }
  2177. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2178. }
  2179. getNodeType( builder ) {
  2180. if ( this.hasMember( builder ) === false ) {
  2181. // default type if member does not exist
  2182. return 'float';
  2183. }
  2184. return this.structNode.getMemberType( builder, this.property );
  2185. }
  2186. getMemberType( builder, name ) {
  2187. if ( this.hasMember( builder ) === false ) {
  2188. // default type if member does not exist
  2189. return 'float';
  2190. }
  2191. const type = this.getNodeType( builder );
  2192. const struct = builder.getStructTypeNode( type );
  2193. return struct.getMemberType( builder, name );
  2194. }
  2195. generate( builder ) {
  2196. if ( this.hasMember( builder ) === false ) {
  2197. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2198. const type = this.getNodeType( builder );
  2199. return builder.generateConst( type );
  2200. }
  2201. const propertyName = this.structNode.build( builder );
  2202. return propertyName + '.' + this.property;
  2203. }
  2204. }
  2205. let currentStack = null;
  2206. const NodeElements = new Map();
  2207. // Extend Node Class for TSL using prototype
  2208. function addMethodChaining( name, nodeElement ) {
  2209. if ( NodeElements.has( name ) ) {
  2210. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2211. return;
  2212. }
  2213. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2214. NodeElements.set( name, nodeElement );
  2215. if ( name !== 'assign' ) {
  2216. // Changing Node prototype to add method chaining
  2217. Node.prototype[ name ] = function ( ...params ) {
  2218. //if ( name === 'toVarIntent' ) return this;
  2219. return this.isStackNode ? this.add( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2220. };
  2221. // Adding assign method chaining
  2222. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2223. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2224. };
  2225. }
  2226. }
  2227. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2228. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2229. Node.prototype.assign = function ( ...params ) {
  2230. if ( this.isStackNode !== true ) {
  2231. if ( currentStack !== null ) {
  2232. currentStack.assign( this, ...params );
  2233. } else {
  2234. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2235. }
  2236. return this;
  2237. } else {
  2238. const nodeElement = NodeElements.get( 'assign' );
  2239. return this.add( nodeElement( ...params ) );
  2240. }
  2241. };
  2242. Node.prototype.toVarIntent = function () {
  2243. return this;
  2244. };
  2245. Node.prototype.get = function ( value ) {
  2246. return new MemberNode( this, value );
  2247. };
  2248. // Cache prototype for TSL
  2249. const proto = {};
  2250. // Set swizzle properties for xyzw, rgba, and stpq.
  2251. function setProtoSwizzle( property, altA, altB ) {
  2252. // swizzle properties
  2253. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2254. get() {
  2255. this._cache = this._cache || {};
  2256. //
  2257. let split = this._cache[ property ];
  2258. if ( split === undefined ) {
  2259. split = new SplitNode( this, property );
  2260. this._cache[ property ] = split;
  2261. }
  2262. return split;
  2263. },
  2264. set( value ) {
  2265. this[ property ].assign( nodeObject( value ) );
  2266. }
  2267. };
  2268. // set properties ( swizzle ) and sort to xyzw sequence
  2269. const propUpper = property.toUpperCase();
  2270. const altAUpper = altA.toUpperCase();
  2271. const altBUpper = altB.toUpperCase();
  2272. // Set methods for swizzle properties
  2273. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2274. const swizzle = parseSwizzleAndSort( property );
  2275. return new SetNode( this, swizzle, nodeObject( value ) );
  2276. };
  2277. // Set methods for flip properties
  2278. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2279. const swizzle = parseSwizzleAndSort( property );
  2280. return new FlipNode( this, swizzle );
  2281. };
  2282. }
  2283. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2284. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2285. const swizzleC = [ 's', 't', 'p', 'q' ];
  2286. for ( let a = 0; a < 4; a ++ ) {
  2287. let prop = swizzleA[ a ];
  2288. let altA = swizzleB[ a ];
  2289. let altB = swizzleC[ a ];
  2290. setProtoSwizzle( prop, altA, altB );
  2291. for ( let b = 0; b < 4; b ++ ) {
  2292. prop = swizzleA[ a ] + swizzleA[ b ];
  2293. altA = swizzleB[ a ] + swizzleB[ b ];
  2294. altB = swizzleC[ a ] + swizzleC[ b ];
  2295. setProtoSwizzle( prop, altA, altB );
  2296. for ( let c = 0; c < 4; c ++ ) {
  2297. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2298. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2299. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2300. setProtoSwizzle( prop, altA, altB );
  2301. for ( let d = 0; d < 4; d ++ ) {
  2302. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2303. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2304. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2305. setProtoSwizzle( prop, altA, altB );
  2306. }
  2307. }
  2308. }
  2309. }
  2310. // Set/get static properties for array elements (0-31).
  2311. for ( let i = 0; i < 32; i ++ ) {
  2312. proto[ i ] = {
  2313. get() {
  2314. this._cache = this._cache || {};
  2315. //
  2316. let element = this._cache[ i ];
  2317. if ( element === undefined ) {
  2318. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2319. this._cache[ i ] = element;
  2320. }
  2321. return element;
  2322. },
  2323. set( value ) {
  2324. this[ i ].assign( nodeObject( value ) );
  2325. }
  2326. };
  2327. }
  2328. /*
  2329. // Set properties for width, height, and depth.
  2330. function setProtoProperty( property, target ) {
  2331. proto[ property ] = {
  2332. get() {
  2333. this._cache = this._cache || {};
  2334. //
  2335. let split = this._cache[ target ];
  2336. if ( split === undefined ) {
  2337. split = new SplitNode( this, target );
  2338. this._cache[ target ] = split;
  2339. }
  2340. return split;
  2341. },
  2342. set( value ) {
  2343. this[ target ].assign( nodeObject( value ) );
  2344. }
  2345. };
  2346. }
  2347. setProtoProperty( 'width', 'x' );
  2348. setProtoProperty( 'height', 'y' );
  2349. setProtoProperty( 'depth', 'z' );
  2350. */
  2351. Object.defineProperties( Node.prototype, proto );
  2352. // --- FINISH ---
  2353. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2354. const ShaderNodeObject = function ( obj, altType = null ) {
  2355. const type = getValueType( obj );
  2356. if ( type === 'node' ) {
  2357. return obj;
  2358. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2359. return nodeObject( getConstNode( obj, altType ) );
  2360. } else if ( type === 'shader' ) {
  2361. return obj.isFn ? obj : Fn( obj );
  2362. }
  2363. return obj;
  2364. };
  2365. const ShaderNodeObjects = function ( objects, altType = null ) {
  2366. for ( const name in objects ) {
  2367. objects[ name ] = nodeObject( objects[ name ], altType );
  2368. }
  2369. return objects;
  2370. };
  2371. const ShaderNodeArray = function ( array, altType = null ) {
  2372. const len = array.length;
  2373. for ( let i = 0; i < len; i ++ ) {
  2374. array[ i ] = nodeObject( array[ i ], altType );
  2375. }
  2376. return array;
  2377. };
  2378. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2379. function assignNode( node ) {
  2380. if ( settings !== null ) {
  2381. node = nodeObject( Object.assign( node, settings ) );
  2382. if ( settings.intent === true ) {
  2383. node = node.toVarIntent();
  2384. }
  2385. } else {
  2386. node = nodeObject( node );
  2387. }
  2388. return node;
  2389. }
  2390. let fn, name = scope, minParams, maxParams;
  2391. function verifyParamsLimit( params ) {
  2392. let tslName;
  2393. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2394. else tslName = NodeClass.type;
  2395. if ( minParams !== undefined && params.length < minParams ) {
  2396. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2397. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2398. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2399. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2400. return params.slice( 0, maxParams );
  2401. }
  2402. return params;
  2403. }
  2404. if ( scope === null ) {
  2405. fn = ( ...params ) => {
  2406. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2407. };
  2408. } else if ( factor !== null ) {
  2409. factor = nodeObject( factor );
  2410. fn = ( ...params ) => {
  2411. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2412. };
  2413. } else {
  2414. fn = ( ...params ) => {
  2415. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2416. };
  2417. }
  2418. fn.setParameterLength = ( ...params ) => {
  2419. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2420. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2421. return fn;
  2422. };
  2423. fn.setName = ( value ) => {
  2424. name = value;
  2425. return fn;
  2426. };
  2427. return fn;
  2428. };
  2429. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2430. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2431. };
  2432. class ShaderCallNodeInternal extends Node {
  2433. constructor( shaderNode, rawInputs ) {
  2434. super();
  2435. this.shaderNode = shaderNode;
  2436. this.rawInputs = rawInputs;
  2437. this.isShaderCallNodeInternal = true;
  2438. }
  2439. getNodeType( builder ) {
  2440. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2441. }
  2442. getMemberType( builder, name ) {
  2443. return this.getOutputNode( builder ).getMemberType( builder, name );
  2444. }
  2445. call( builder ) {
  2446. const { shaderNode, rawInputs } = this;
  2447. const properties = builder.getNodeProperties( shaderNode );
  2448. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2449. const subBuildProperty = subBuild || 'default';
  2450. if ( properties[ subBuildProperty ] ) {
  2451. return properties[ subBuildProperty ];
  2452. }
  2453. //
  2454. const previousSubBuildFn = builder.subBuildFn;
  2455. builder.subBuildFn = subBuild;
  2456. let result = null;
  2457. if ( shaderNode.layout ) {
  2458. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2459. if ( functionNodesCacheMap === undefined ) {
  2460. functionNodesCacheMap = new WeakMap();
  2461. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2462. }
  2463. let functionNode = functionNodesCacheMap.get( shaderNode );
  2464. if ( functionNode === undefined ) {
  2465. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2466. functionNodesCacheMap.set( shaderNode, functionNode );
  2467. }
  2468. builder.addInclude( functionNode );
  2469. //
  2470. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2471. result = nodeObject( functionNode.call( inputs ) );
  2472. } else {
  2473. const secureNodeBuilder = new Proxy( builder, {
  2474. get: ( target, property, receiver ) => {
  2475. let value;
  2476. if ( Symbol.iterator === property ) {
  2477. value = function* () {
  2478. yield undefined;
  2479. };
  2480. } else {
  2481. value = Reflect.get( target, property, receiver );
  2482. }
  2483. return value;
  2484. }
  2485. } );
  2486. //
  2487. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2488. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2489. const jsFunc = shaderNode.jsFunc;
  2490. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2491. result = nodeObject( outputNode );
  2492. }
  2493. builder.subBuildFn = previousSubBuildFn;
  2494. if ( shaderNode.once ) {
  2495. properties[ subBuildProperty ] = result;
  2496. }
  2497. return result;
  2498. }
  2499. setupOutput( builder ) {
  2500. builder.addStack();
  2501. builder.stack.outputNode = this.call( builder );
  2502. return builder.removeStack();
  2503. }
  2504. getOutputNode( builder ) {
  2505. const properties = builder.getNodeProperties( this );
  2506. const subBuildOutput = builder.getSubBuildOutput( this );
  2507. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2508. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2509. return properties[ subBuildOutput ];
  2510. }
  2511. build( builder, output = null ) {
  2512. let result = null;
  2513. const buildStage = builder.getBuildStage();
  2514. const properties = builder.getNodeProperties( this );
  2515. const subBuildOutput = builder.getSubBuildOutput( this );
  2516. const outputNode = this.getOutputNode( builder );
  2517. if ( buildStage === 'setup' ) {
  2518. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2519. if ( properties[ subBuildInitialized ] !== true ) {
  2520. properties[ subBuildInitialized ] = true;
  2521. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2522. properties[ subBuildOutput ].build( builder );
  2523. // If the shaderNode has subBuilds, add them to the chaining nodes
  2524. // so they can be built later in the build process.
  2525. if ( this.shaderNode.subBuilds ) {
  2526. for ( const node of builder.chaining ) {
  2527. const nodeData = builder.getDataFromNode( node, 'any' );
  2528. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2529. for ( const subBuild of this.shaderNode.subBuilds ) {
  2530. nodeData.subBuilds.add( subBuild );
  2531. }
  2532. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2533. }
  2534. }
  2535. }
  2536. result = properties[ subBuildOutput ];
  2537. } else if ( buildStage === 'analyze' ) {
  2538. outputNode.build( builder, output );
  2539. } else if ( buildStage === 'generate' ) {
  2540. result = outputNode.build( builder, output ) || '';
  2541. }
  2542. return result;
  2543. }
  2544. }
  2545. function getLayoutParameters( params ) {
  2546. let output;
  2547. nodeObjects( params );
  2548. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2549. if ( isArrayAsParameter ) {
  2550. output = [ ...params ];
  2551. } else {
  2552. output = params[ 0 ];
  2553. }
  2554. return output;
  2555. }
  2556. function getProxyParameters( params ) {
  2557. let index = 0;
  2558. nodeObjects( params );
  2559. return new Proxy( params, {
  2560. get: ( target, property, receiver ) => {
  2561. let value;
  2562. if ( property === 'length' ) {
  2563. value = params.length;
  2564. return value;
  2565. }
  2566. if ( Symbol.iterator === property ) {
  2567. value = function* () {
  2568. for ( const inputNode of params ) {
  2569. yield nodeObject( inputNode );
  2570. }
  2571. };
  2572. } else {
  2573. if ( params.length > 0 ) {
  2574. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2575. const objectTarget = params[ 0 ];
  2576. if ( objectTarget[ property ] === undefined ) {
  2577. value = objectTarget[ index ++ ];
  2578. } else {
  2579. value = Reflect.get( objectTarget, property, receiver );
  2580. }
  2581. } else if ( params[ 0 ] instanceof Node ) {
  2582. if ( params[ property ] === undefined ) {
  2583. value = params[ index ++ ];
  2584. } else {
  2585. value = Reflect.get( params, property, receiver );
  2586. }
  2587. }
  2588. } else {
  2589. value = Reflect.get( target, property, receiver );
  2590. }
  2591. value = nodeObject( value );
  2592. }
  2593. return value;
  2594. }
  2595. } );
  2596. }
  2597. class ShaderNodeInternal extends Node {
  2598. constructor( jsFunc, nodeType ) {
  2599. super( nodeType );
  2600. this.jsFunc = jsFunc;
  2601. this.layout = null;
  2602. this.global = true;
  2603. this.once = false;
  2604. }
  2605. setLayout( layout ) {
  2606. this.layout = layout;
  2607. return this;
  2608. }
  2609. call( rawInputs = null ) {
  2610. return nodeObject( new ShaderCallNodeInternal( this, rawInputs ) );
  2611. }
  2612. setup() {
  2613. return this.call();
  2614. }
  2615. }
  2616. const bools = [ false, true ];
  2617. const uints = [ 0, 1, 2, 3 ];
  2618. const ints = [ -1, -2 ];
  2619. 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 ];
  2620. const boolsCacheMap = new Map();
  2621. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2622. const uintsCacheMap = new Map();
  2623. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2624. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2625. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2626. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2627. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2628. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2629. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2630. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2631. const getConstNode = ( value, type ) => {
  2632. if ( constNodesCacheMap.has( value ) ) {
  2633. return constNodesCacheMap.get( value );
  2634. } else if ( value.isNode === true ) {
  2635. return value;
  2636. } else {
  2637. return new ConstNode( value, type );
  2638. }
  2639. };
  2640. const ConvertType = function ( type, cacheMap = null ) {
  2641. return ( ...params ) => {
  2642. for ( const param of params ) {
  2643. if ( param === undefined ) {
  2644. error( `TSL: Invalid parameter for the type "${ type }".` );
  2645. return nodeObject( new ConstNode( 0, type ) );
  2646. }
  2647. }
  2648. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2649. const paramType = typeof param;
  2650. return paramType !== 'object' && paramType !== 'function';
  2651. } ) ) ) {
  2652. params = [ getValueFromType( type, ...params ) ];
  2653. }
  2654. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2655. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2656. }
  2657. if ( params.length === 1 ) {
  2658. const node = getConstNode( params[ 0 ], type );
  2659. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2660. return nodeObjectIntent( new ConvertNode( node, type ) );
  2661. }
  2662. const nodes = params.map( param => getConstNode( param ) );
  2663. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2664. };
  2665. };
  2666. // exports
  2667. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2668. // utils
  2669. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2670. // shader node base
  2671. function ShaderNode( jsFunc, nodeType ) {
  2672. return new ShaderNodeInternal( jsFunc, nodeType );
  2673. }
  2674. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2675. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2676. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2677. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2678. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2679. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2680. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2681. let fnId = 0;
  2682. class FnNode extends Node {
  2683. constructor( jsFunc, layout = null ) {
  2684. super();
  2685. let nodeType = null;
  2686. if ( layout !== null ) {
  2687. if ( typeof layout === 'object' ) {
  2688. nodeType = layout.return;
  2689. } else {
  2690. if ( typeof layout === 'string' ) {
  2691. nodeType = layout;
  2692. } else {
  2693. error( 'TSL: Invalid layout type.' );
  2694. }
  2695. layout = null;
  2696. }
  2697. }
  2698. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2699. if ( layout !== null ) {
  2700. this.setLayout( layout );
  2701. }
  2702. this.isFn = true;
  2703. }
  2704. setLayout( layout ) {
  2705. const nodeType = this.shaderNode.nodeType;
  2706. if ( typeof layout.inputs !== 'object' ) {
  2707. const fullLayout = {
  2708. name: 'fn' + fnId ++,
  2709. type: nodeType,
  2710. inputs: []
  2711. };
  2712. for ( const name in layout ) {
  2713. if ( name === 'return' ) continue;
  2714. fullLayout.inputs.push( {
  2715. name: name,
  2716. type: layout[ name ]
  2717. } );
  2718. }
  2719. layout = fullLayout;
  2720. }
  2721. this.shaderNode.setLayout( layout );
  2722. return this;
  2723. }
  2724. getNodeType( builder ) {
  2725. return this.shaderNode.getNodeType( builder ) || 'float';
  2726. }
  2727. call( ...params ) {
  2728. const fnCall = this.shaderNode.call( params );
  2729. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2730. return fnCall.toVarIntent();
  2731. }
  2732. once( subBuilds = null ) {
  2733. this.shaderNode.once = true;
  2734. this.shaderNode.subBuilds = subBuilds;
  2735. return this;
  2736. }
  2737. generate( builder ) {
  2738. const type = this.getNodeType( builder );
  2739. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2740. return builder.generateConst( type );
  2741. }
  2742. }
  2743. function Fn( jsFunc, layout = null ) {
  2744. const instance = new FnNode( jsFunc, layout );
  2745. return new Proxy( () => {}, {
  2746. apply( target, thisArg, params ) {
  2747. return instance.call( ...params );
  2748. },
  2749. get( target, prop, receiver ) {
  2750. return Reflect.get( instance, prop, receiver );
  2751. },
  2752. set( target, prop, value, receiver ) {
  2753. return Reflect.set( instance, prop, value, receiver );
  2754. }
  2755. } );
  2756. }
  2757. //
  2758. const setCurrentStack = ( stack ) => {
  2759. currentStack = stack;
  2760. };
  2761. const getCurrentStack = () => currentStack;
  2762. /**
  2763. * Represent a conditional node using if/else statements.
  2764. *
  2765. * ```js
  2766. * If( condition, function )
  2767. * .ElseIf( condition, function )
  2768. * .Else( function )
  2769. * ```
  2770. * @tsl
  2771. * @function
  2772. * @param {...any} params - The parameters for the conditional node.
  2773. * @returns {StackNode} The conditional node.
  2774. */
  2775. const If = ( ...params ) => currentStack.If( ...params );
  2776. /**
  2777. * Represent a conditional node using switch/case statements.
  2778. *
  2779. * ```js
  2780. * Switch( value )
  2781. * .Case( 1, function )
  2782. * .Case( 2, 3, 4, function )
  2783. * .Default( function )
  2784. * ```
  2785. * @tsl
  2786. * @function
  2787. * @param {...any} params - The parameters for the conditional node.
  2788. * @returns {StackNode} The conditional node.
  2789. */
  2790. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2791. /**
  2792. * Add the given node to the current stack.
  2793. *
  2794. * @param {Node} node - The node to add.
  2795. * @returns {Node} The node that was added to the stack.
  2796. */
  2797. function Stack( node ) {
  2798. if ( currentStack ) currentStack.add( node );
  2799. return node;
  2800. }
  2801. addMethodChaining( 'toStack', Stack );
  2802. // types
  2803. const color = new ConvertType( 'color' );
  2804. const float = new ConvertType( 'float', cacheMaps.float );
  2805. const int = new ConvertType( 'int', cacheMaps.ints );
  2806. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2807. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2808. const vec2 = new ConvertType( 'vec2' );
  2809. const ivec2 = new ConvertType( 'ivec2' );
  2810. const uvec2 = new ConvertType( 'uvec2' );
  2811. const bvec2 = new ConvertType( 'bvec2' );
  2812. const vec3 = new ConvertType( 'vec3' );
  2813. const ivec3 = new ConvertType( 'ivec3' );
  2814. const uvec3 = new ConvertType( 'uvec3' );
  2815. const bvec3 = new ConvertType( 'bvec3' );
  2816. const vec4 = new ConvertType( 'vec4' );
  2817. const ivec4 = new ConvertType( 'ivec4' );
  2818. const uvec4 = new ConvertType( 'uvec4' );
  2819. const bvec4 = new ConvertType( 'bvec4' );
  2820. const mat2 = new ConvertType( 'mat2' );
  2821. const mat3 = new ConvertType( 'mat3' );
  2822. const mat4 = new ConvertType( 'mat4' );
  2823. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2824. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2825. addMethodChaining( 'toColor', color );
  2826. addMethodChaining( 'toFloat', float );
  2827. addMethodChaining( 'toInt', int );
  2828. addMethodChaining( 'toUint', uint );
  2829. addMethodChaining( 'toBool', bool );
  2830. addMethodChaining( 'toVec2', vec2 );
  2831. addMethodChaining( 'toIVec2', ivec2 );
  2832. addMethodChaining( 'toUVec2', uvec2 );
  2833. addMethodChaining( 'toBVec2', bvec2 );
  2834. addMethodChaining( 'toVec3', vec3 );
  2835. addMethodChaining( 'toIVec3', ivec3 );
  2836. addMethodChaining( 'toUVec3', uvec3 );
  2837. addMethodChaining( 'toBVec3', bvec3 );
  2838. addMethodChaining( 'toVec4', vec4 );
  2839. addMethodChaining( 'toIVec4', ivec4 );
  2840. addMethodChaining( 'toUVec4', uvec4 );
  2841. addMethodChaining( 'toBVec4', bvec4 );
  2842. addMethodChaining( 'toMat2', mat2 );
  2843. addMethodChaining( 'toMat3', mat3 );
  2844. addMethodChaining( 'toMat4', mat4 );
  2845. // basic nodes
  2846. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2847. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2848. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2849. addMethodChaining( 'element', element );
  2850. addMethodChaining( 'convert', convert );
  2851. // deprecated
  2852. /**
  2853. * @tsl
  2854. * @function
  2855. * @deprecated since r176. Use {@link Stack} instead.
  2856. *
  2857. * @param {Node} node - The node to add.
  2858. * @returns {Function}
  2859. */
  2860. const append = ( node ) => { // @deprecated, r176
  2861. warn( 'TSL: append() has been renamed to Stack().' );
  2862. return Stack( node );
  2863. };
  2864. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2865. warn( 'TSL: .append() has been renamed to .toStack().' );
  2866. return Stack( node );
  2867. } );
  2868. /**
  2869. * This class represents a shader property. It can be used
  2870. * to explicitly define a property and assign a value to it.
  2871. *
  2872. * ```js
  2873. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2874. *```
  2875. * `PropertyNode` is used by the engine to predefined common material properties
  2876. * for TSL code.
  2877. *
  2878. * @augments Node
  2879. */
  2880. class PropertyNode extends Node {
  2881. static get type() {
  2882. return 'PropertyNode';
  2883. }
  2884. /**
  2885. * Constructs a new property node.
  2886. *
  2887. * @param {string} nodeType - The type of the node.
  2888. * @param {?string} [name=null] - The name of the property in the shader.
  2889. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2890. */
  2891. constructor( nodeType, name = null, varying = false ) {
  2892. super( nodeType );
  2893. /**
  2894. * The name of the property in the shader. If no name is defined,
  2895. * the node system auto-generates one.
  2896. *
  2897. * @type {?string}
  2898. * @default null
  2899. */
  2900. this.name = name;
  2901. /**
  2902. * Whether this property is a varying or not.
  2903. *
  2904. * @type {boolean}
  2905. * @default false
  2906. */
  2907. this.varying = varying;
  2908. /**
  2909. * This flag can be used for type testing.
  2910. *
  2911. * @type {boolean}
  2912. * @readonly
  2913. * @default true
  2914. */
  2915. this.isPropertyNode = true;
  2916. /**
  2917. * This flag is used for global cache.
  2918. *
  2919. * @type {boolean}
  2920. * @default true
  2921. */
  2922. this.global = true;
  2923. }
  2924. getHash( builder ) {
  2925. return this.name || super.getHash( builder );
  2926. }
  2927. generate( builder ) {
  2928. let nodeVar;
  2929. if ( this.varying === true ) {
  2930. nodeVar = builder.getVaryingFromNode( this, this.name );
  2931. nodeVar.needsInterpolation = true;
  2932. } else {
  2933. nodeVar = builder.getVarFromNode( this, this.name );
  2934. }
  2935. return builder.getPropertyName( nodeVar );
  2936. }
  2937. }
  2938. /**
  2939. * TSL function for creating a property node.
  2940. *
  2941. * @tsl
  2942. * @function
  2943. * @param {string} type - The type of the node.
  2944. * @param {?string} [name=null] - The name of the property in the shader.
  2945. * @returns {PropertyNode}
  2946. */
  2947. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2948. /**
  2949. * TSL function for creating a varying property node.
  2950. *
  2951. * @tsl
  2952. * @function
  2953. * @param {string} type - The type of the node.
  2954. * @param {?string} [name=null] - The name of the varying in the shader.
  2955. * @returns {PropertyNode}
  2956. */
  2957. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2958. /**
  2959. * TSL object that represents the shader variable `DiffuseColor`.
  2960. *
  2961. * @tsl
  2962. * @type {PropertyNode<vec4>}
  2963. */
  2964. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2965. /**
  2966. * TSL object that represents the shader variable `EmissiveColor`.
  2967. *
  2968. * @tsl
  2969. * @type {PropertyNode<vec3>}
  2970. */
  2971. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2972. /**
  2973. * TSL object that represents the shader variable `Roughness`.
  2974. *
  2975. * @tsl
  2976. * @type {PropertyNode<float>}
  2977. */
  2978. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2979. /**
  2980. * TSL object that represents the shader variable `Metalness`.
  2981. *
  2982. * @tsl
  2983. * @type {PropertyNode<float>}
  2984. */
  2985. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2986. /**
  2987. * TSL object that represents the shader variable `Clearcoat`.
  2988. *
  2989. * @tsl
  2990. * @type {PropertyNode<float>}
  2991. */
  2992. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2993. /**
  2994. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2995. *
  2996. * @tsl
  2997. * @type {PropertyNode<float>}
  2998. */
  2999. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  3000. /**
  3001. * TSL object that represents the shader variable `Sheen`.
  3002. *
  3003. * @tsl
  3004. * @type {PropertyNode<vec3>}
  3005. */
  3006. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  3007. /**
  3008. * TSL object that represents the shader variable `SheenRoughness`.
  3009. *
  3010. * @tsl
  3011. * @type {PropertyNode<float>}
  3012. */
  3013. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  3014. /**
  3015. * TSL object that represents the shader variable `Iridescence`.
  3016. *
  3017. * @tsl
  3018. * @type {PropertyNode<float>}
  3019. */
  3020. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  3021. /**
  3022. * TSL object that represents the shader variable `IridescenceIOR`.
  3023. *
  3024. * @tsl
  3025. * @type {PropertyNode<float>}
  3026. */
  3027. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3028. /**
  3029. * TSL object that represents the shader variable `IridescenceThickness`.
  3030. *
  3031. * @tsl
  3032. * @type {PropertyNode<float>}
  3033. */
  3034. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3035. /**
  3036. * TSL object that represents the shader variable `AlphaT`.
  3037. *
  3038. * @tsl
  3039. * @type {PropertyNode<float>}
  3040. */
  3041. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3042. /**
  3043. * TSL object that represents the shader variable `Anisotropy`.
  3044. *
  3045. * @tsl
  3046. * @type {PropertyNode<float>}
  3047. */
  3048. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3049. /**
  3050. * TSL object that represents the shader variable `AnisotropyT`.
  3051. *
  3052. * @tsl
  3053. * @type {PropertyNode<vec3>}
  3054. */
  3055. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3056. /**
  3057. * TSL object that represents the shader variable `AnisotropyB`.
  3058. *
  3059. * @tsl
  3060. * @type {PropertyNode<vec3>}
  3061. */
  3062. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3063. /**
  3064. * TSL object that represents the shader variable `SpecularColor`.
  3065. *
  3066. * @tsl
  3067. * @type {PropertyNode<color>}
  3068. */
  3069. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3070. /**
  3071. * TSL object that represents the shader variable `SpecularF90`.
  3072. *
  3073. * @tsl
  3074. * @type {PropertyNode<float>}
  3075. */
  3076. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3077. /**
  3078. * TSL object that represents the shader variable `Shininess`.
  3079. *
  3080. * @tsl
  3081. * @type {PropertyNode<float>}
  3082. */
  3083. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3084. /**
  3085. * TSL object that represents the shader variable `Output`.
  3086. *
  3087. * @tsl
  3088. * @type {PropertyNode<vec4>}
  3089. */
  3090. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3091. /**
  3092. * TSL object that represents the shader variable `dashSize`.
  3093. *
  3094. * @tsl
  3095. * @type {PropertyNode<float>}
  3096. */
  3097. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3098. /**
  3099. * TSL object that represents the shader variable `gapSize`.
  3100. *
  3101. * @tsl
  3102. * @type {PropertyNode<float>}
  3103. */
  3104. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3105. /**
  3106. * TSL object that represents the shader variable `pointWidth`.
  3107. *
  3108. * @tsl
  3109. * @type {PropertyNode<float>}
  3110. */
  3111. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3112. /**
  3113. * TSL object that represents the shader variable `IOR`.
  3114. *
  3115. * @tsl
  3116. * @type {PropertyNode<float>}
  3117. */
  3118. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3119. /**
  3120. * TSL object that represents the shader variable `Transmission`.
  3121. *
  3122. * @tsl
  3123. * @type {PropertyNode<float>}
  3124. */
  3125. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3126. /**
  3127. * TSL object that represents the shader variable `Thickness`.
  3128. *
  3129. * @tsl
  3130. * @type {PropertyNode<float>}
  3131. */
  3132. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3133. /**
  3134. * TSL object that represents the shader variable `AttenuationDistance`.
  3135. *
  3136. * @tsl
  3137. * @type {PropertyNode<float>}
  3138. */
  3139. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3140. /**
  3141. * TSL object that represents the shader variable `AttenuationColor`.
  3142. *
  3143. * @tsl
  3144. * @type {PropertyNode<color>}
  3145. */
  3146. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3147. /**
  3148. * TSL object that represents the shader variable `Dispersion`.
  3149. *
  3150. * @tsl
  3151. * @type {PropertyNode<float>}
  3152. */
  3153. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3154. /**
  3155. * This node can be used to group single instances of {@link UniformNode}
  3156. * and manage them as a uniform buffer.
  3157. *
  3158. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3159. * will be used when defining the {@link UniformNode#groupNode} property.
  3160. *
  3161. * - `objectGroup`: Uniform buffer per object.
  3162. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3163. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3164. *
  3165. * @augments Node
  3166. */
  3167. class UniformGroupNode extends Node {
  3168. static get type() {
  3169. return 'UniformGroupNode';
  3170. }
  3171. /**
  3172. * Constructs a new uniform group node.
  3173. *
  3174. * @param {string} name - The name of the uniform group node.
  3175. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3176. * @param {number} [order=1] - Influences the internal sorting.
  3177. */
  3178. constructor( name, shared = false, order = 1 ) {
  3179. super( 'string' );
  3180. /**
  3181. * The name of the uniform group node.
  3182. *
  3183. * @type {string}
  3184. */
  3185. this.name = name;
  3186. /**
  3187. * Whether this uniform group node is shared or not.
  3188. *
  3189. * @type {boolean}
  3190. * @default false
  3191. */
  3192. this.shared = shared;
  3193. /**
  3194. * Influences the internal sorting.
  3195. * TODO: Add details when this property should be changed.
  3196. *
  3197. * @type {number}
  3198. * @default 1
  3199. */
  3200. this.order = order;
  3201. /**
  3202. * This flag can be used for type testing.
  3203. *
  3204. * @type {boolean}
  3205. * @readonly
  3206. * @default true
  3207. */
  3208. this.isUniformGroup = true;
  3209. }
  3210. serialize( data ) {
  3211. super.serialize( data );
  3212. data.name = this.name;
  3213. data.version = this.version;
  3214. data.shared = this.shared;
  3215. }
  3216. deserialize( data ) {
  3217. super.deserialize( data );
  3218. this.name = data.name;
  3219. this.version = data.version;
  3220. this.shared = data.shared;
  3221. }
  3222. }
  3223. /**
  3224. * TSL function for creating a uniform group node with the given name.
  3225. *
  3226. * @tsl
  3227. * @function
  3228. * @param {string} name - The name of the uniform group node.
  3229. * @returns {UniformGroupNode}
  3230. */
  3231. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3232. /**
  3233. * TSL function for creating a shared uniform group node with the given name and order.
  3234. *
  3235. * @tsl
  3236. * @function
  3237. * @param {string} name - The name of the uniform group node.
  3238. * @param {number} [order=0] - Influences the internal sorting.
  3239. * @returns {UniformGroupNode}
  3240. */
  3241. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3242. /**
  3243. * TSL object that represents a shared uniform group node which is updated once per frame.
  3244. *
  3245. * @tsl
  3246. * @type {UniformGroupNode}
  3247. */
  3248. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3249. /**
  3250. * TSL object that represents a shared uniform group node which is updated once per render.
  3251. *
  3252. * @tsl
  3253. * @type {UniformGroupNode}
  3254. */
  3255. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3256. /**
  3257. * TSL object that represents a uniform group node which is updated once per object.
  3258. *
  3259. * @tsl
  3260. * @type {UniformGroupNode}
  3261. */
  3262. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3263. /**
  3264. * Class for representing a uniform.
  3265. *
  3266. * @augments InputNode
  3267. */
  3268. class UniformNode extends InputNode {
  3269. static get type() {
  3270. return 'UniformNode';
  3271. }
  3272. /**
  3273. * Constructs a new uniform node.
  3274. *
  3275. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3276. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3277. */
  3278. constructor( value, nodeType = null ) {
  3279. super( value, nodeType );
  3280. /**
  3281. * This flag can be used for type testing.
  3282. *
  3283. * @type {boolean}
  3284. * @readonly
  3285. * @default true
  3286. */
  3287. this.isUniformNode = true;
  3288. /**
  3289. * The name or label of the uniform.
  3290. *
  3291. * @type {string}
  3292. * @default ''
  3293. */
  3294. this.name = '';
  3295. /**
  3296. * The uniform group of this uniform. By default, uniforms are
  3297. * managed per object but they might belong to a shared group
  3298. * which is updated per frame or render call.
  3299. *
  3300. * @type {UniformGroupNode}
  3301. */
  3302. this.groupNode = objectGroup;
  3303. }
  3304. /**
  3305. * Sets the {@link UniformNode#name} property.
  3306. *
  3307. * @param {string} name - The name of the uniform.
  3308. * @return {UniformNode} A reference to this node.
  3309. */
  3310. setName( name ) {
  3311. this.name = name;
  3312. return this;
  3313. }
  3314. /**
  3315. * Sets the {@link UniformNode#name} property.
  3316. *
  3317. * @deprecated
  3318. * @param {string} name - The name of the uniform.
  3319. * @return {UniformNode} A reference to this node.
  3320. */
  3321. label( name ) {
  3322. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3323. return this.setName( name );
  3324. }
  3325. /**
  3326. * Sets the {@link UniformNode#groupNode} property.
  3327. *
  3328. * @param {UniformGroupNode} group - The uniform group.
  3329. * @return {UniformNode} A reference to this node.
  3330. */
  3331. setGroup( group ) {
  3332. this.groupNode = group;
  3333. return this;
  3334. }
  3335. /**
  3336. * Returns the {@link UniformNode#groupNode}.
  3337. *
  3338. * @return {UniformGroupNode} The uniform group.
  3339. */
  3340. getGroup() {
  3341. return this.groupNode;
  3342. }
  3343. /**
  3344. * By default, this method returns the result of {@link Node#getHash} but derived
  3345. * classes might overwrite this method with a different implementation.
  3346. *
  3347. * @param {NodeBuilder} builder - The current node builder.
  3348. * @return {string} The uniform hash.
  3349. */
  3350. getUniformHash( builder ) {
  3351. return this.getHash( builder );
  3352. }
  3353. onUpdate( callback, updateType ) {
  3354. callback = callback.bind( this );
  3355. return super.onUpdate( ( frame ) => {
  3356. const value = callback( frame, this );
  3357. if ( value !== undefined ) {
  3358. this.value = value;
  3359. }
  3360. }, updateType );
  3361. }
  3362. getInputType( builder ) {
  3363. let type = super.getInputType( builder );
  3364. if ( type === 'bool' ) {
  3365. type = 'uint';
  3366. }
  3367. return type;
  3368. }
  3369. generate( builder, output ) {
  3370. const type = this.getNodeType( builder );
  3371. const hash = this.getUniformHash( builder );
  3372. let sharedNode = builder.getNodeFromHash( hash );
  3373. if ( sharedNode === undefined ) {
  3374. builder.setHashNode( this, hash );
  3375. sharedNode = this;
  3376. }
  3377. const sharedNodeType = sharedNode.getInputType( builder );
  3378. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3379. const uniformName = builder.getPropertyName( nodeUniform );
  3380. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3381. //
  3382. let snippet = uniformName;
  3383. if ( type === 'bool' ) {
  3384. // cache to variable
  3385. const nodeData = builder.getDataFromNode( this );
  3386. let propertyName = nodeData.propertyName;
  3387. if ( propertyName === undefined ) {
  3388. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3389. propertyName = builder.getPropertyName( nodeVar );
  3390. nodeData.propertyName = propertyName;
  3391. snippet = builder.format( uniformName, sharedNodeType, type );
  3392. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3393. }
  3394. snippet = propertyName;
  3395. }
  3396. return builder.format( snippet, type, output );
  3397. }
  3398. }
  3399. /**
  3400. * TSL function for creating a uniform node.
  3401. *
  3402. * @tsl
  3403. * @function
  3404. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3405. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3406. * @returns {UniformNode}
  3407. */
  3408. const uniform = ( value, type ) => {
  3409. const nodeType = getConstNodeType( type || value );
  3410. if ( nodeType === value ) {
  3411. // if the value is a type but no having a value
  3412. value = getValueFromType( nodeType );
  3413. }
  3414. // @TODO: get ConstNode from .traverse() in the future
  3415. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3416. return nodeObject( new UniformNode( value, nodeType ) );
  3417. };
  3418. /**
  3419. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3420. * ```js
  3421. * const colors = array( [
  3422. * vec3( 1, 0, 0 ),
  3423. * vec3( 0, 1, 0 ),
  3424. * vec3( 0, 0, 1 )
  3425. * ] );
  3426. *
  3427. * const redColor = tintColors.element( 0 );
  3428. *
  3429. * @augments TempNode
  3430. */
  3431. class ArrayNode extends TempNode {
  3432. static get type() {
  3433. return 'ArrayNode';
  3434. }
  3435. /**
  3436. * Constructs a new array node.
  3437. *
  3438. * @param {?string} nodeType - The data type of the elements.
  3439. * @param {number} count - Size of the array.
  3440. * @param {?Array<Node>} [values=null] - Array default values.
  3441. */
  3442. constructor( nodeType, count, values = null ) {
  3443. super( nodeType );
  3444. /**
  3445. * Array size.
  3446. *
  3447. * @type {number}
  3448. */
  3449. this.count = count;
  3450. /**
  3451. * Array default values.
  3452. *
  3453. * @type {?Array<Node>}
  3454. */
  3455. this.values = values;
  3456. /**
  3457. * This flag can be used for type testing.
  3458. *
  3459. * @type {boolean}
  3460. * @readonly
  3461. * @default true
  3462. */
  3463. this.isArrayNode = true;
  3464. }
  3465. /**
  3466. * Returns the number of elements in the node array.
  3467. *
  3468. * @param {NodeBuilder} builder - The current node builder.
  3469. * @return {number} The number of elements in the node array.
  3470. */
  3471. getArrayCount( /*builder*/ ) {
  3472. return this.count;
  3473. }
  3474. /**
  3475. * Returns the node's type.
  3476. *
  3477. * @param {NodeBuilder} builder - The current node builder.
  3478. * @return {string} The type of the node.
  3479. */
  3480. getNodeType( builder ) {
  3481. if ( this.nodeType === null ) {
  3482. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3483. }
  3484. return this.nodeType;
  3485. }
  3486. /**
  3487. * Returns the node's type.
  3488. *
  3489. * @param {NodeBuilder} builder - The current node builder.
  3490. * @return {string} The type of the node.
  3491. */
  3492. getElementType( builder ) {
  3493. return this.getNodeType( builder );
  3494. }
  3495. /**
  3496. * This method builds the output node and returns the resulting array as a shader string.
  3497. *
  3498. * @param {NodeBuilder} builder - The current node builder.
  3499. * @return {string} The generated shader string.
  3500. */
  3501. generate( builder ) {
  3502. const type = this.getNodeType( builder );
  3503. return builder.generateArray( type, this.count, this.values );
  3504. }
  3505. }
  3506. /**
  3507. * TSL function for creating an array node.
  3508. *
  3509. * @tsl
  3510. * @function
  3511. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3512. * or an array containing the default values (e.g., [ vec3() ]).
  3513. * @param {?number} [count] - Size of the array.
  3514. * @returns {ArrayNode}
  3515. */
  3516. const array = ( ...params ) => {
  3517. let node;
  3518. if ( params.length === 1 ) {
  3519. const values = params[ 0 ];
  3520. node = new ArrayNode( null, values.length, values );
  3521. } else {
  3522. const nodeType = params[ 0 ];
  3523. const count = params[ 1 ];
  3524. node = new ArrayNode( nodeType, count );
  3525. }
  3526. return nodeObject( node );
  3527. };
  3528. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3529. /**
  3530. * These node represents an assign operation. Meaning a node is assigned
  3531. * to another node.
  3532. *
  3533. * @augments TempNode
  3534. */
  3535. class AssignNode extends TempNode {
  3536. static get type() {
  3537. return 'AssignNode';
  3538. }
  3539. /**
  3540. * Constructs a new assign node.
  3541. *
  3542. * @param {Node} targetNode - The target node.
  3543. * @param {Node} sourceNode - The source type.
  3544. */
  3545. constructor( targetNode, sourceNode ) {
  3546. super();
  3547. /**
  3548. * The target node.
  3549. *
  3550. * @type {Node}
  3551. */
  3552. this.targetNode = targetNode;
  3553. /**
  3554. * The source node.
  3555. *
  3556. * @type {Node}
  3557. */
  3558. this.sourceNode = sourceNode;
  3559. /**
  3560. * This flag can be used for type testing.
  3561. *
  3562. * @type {boolean}
  3563. * @readonly
  3564. * @default true
  3565. */
  3566. this.isAssignNode = true;
  3567. }
  3568. /**
  3569. * Whether this node is used more than once in context of other nodes. This method
  3570. * is overwritten since it always returns `false` (assigns are unique).
  3571. *
  3572. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3573. */
  3574. hasDependencies() {
  3575. return false;
  3576. }
  3577. getNodeType( builder, output ) {
  3578. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3579. }
  3580. /**
  3581. * Whether a split is required when assigning source to target. This can happen when the component length of
  3582. * target and source data type does not match.
  3583. *
  3584. * @param {NodeBuilder} builder - The current node builder.
  3585. * @return {boolean} Whether a split is required when assigning source to target.
  3586. */
  3587. needsSplitAssign( builder ) {
  3588. const { targetNode } = this;
  3589. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3590. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3591. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3592. return assignDifferentVector;
  3593. }
  3594. return false;
  3595. }
  3596. setup( builder ) {
  3597. const { targetNode, sourceNode } = this;
  3598. const scope = targetNode.getScope();
  3599. const targetProperties = builder.getNodeProperties( scope );
  3600. targetProperties.assign = true;
  3601. const properties = builder.getNodeProperties( this );
  3602. properties.sourceNode = sourceNode;
  3603. properties.targetNode = targetNode.context( { assign: true } );
  3604. }
  3605. generate( builder, output ) {
  3606. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3607. const needsSplitAssign = this.needsSplitAssign( builder );
  3608. const target = targetNode.build( builder );
  3609. const targetType = targetNode.getNodeType( builder );
  3610. const source = sourceNode.build( builder, targetType );
  3611. const sourceType = sourceNode.getNodeType( builder );
  3612. const nodeData = builder.getDataFromNode( this );
  3613. //
  3614. let snippet;
  3615. if ( nodeData.initialized === true ) {
  3616. if ( output !== 'void' ) {
  3617. snippet = target;
  3618. }
  3619. } else if ( needsSplitAssign ) {
  3620. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3621. const sourceProperty = builder.getPropertyName( sourceVar );
  3622. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3623. const splitNode = targetNode.node;
  3624. const splitTargetNode = splitNode.node.context( { assign: true } );
  3625. const targetRoot = splitTargetNode.build( builder );
  3626. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3627. const component = splitNode.components[ i ];
  3628. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3629. }
  3630. if ( output !== 'void' ) {
  3631. snippet = target;
  3632. }
  3633. } else {
  3634. snippet = `${ target } = ${ source }`;
  3635. if ( output === 'void' || sourceType === 'void' ) {
  3636. builder.addLineFlowCode( snippet, this );
  3637. if ( output !== 'void' ) {
  3638. snippet = target;
  3639. }
  3640. }
  3641. }
  3642. nodeData.initialized = true;
  3643. return builder.format( snippet, targetType, output );
  3644. }
  3645. }
  3646. /**
  3647. * TSL function for creating an assign node.
  3648. *
  3649. * @tsl
  3650. * @function
  3651. * @param {Node} targetNode - The target node.
  3652. * @param {Node} sourceNode - The source type.
  3653. * @returns {AssignNode}
  3654. */
  3655. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3656. addMethodChaining( 'assign', assign );
  3657. /**
  3658. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3659. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3660. * this logic.
  3661. *
  3662. * @augments TempNode
  3663. */
  3664. class FunctionCallNode extends TempNode {
  3665. static get type() {
  3666. return 'FunctionCallNode';
  3667. }
  3668. /**
  3669. * Constructs a new function call node.
  3670. *
  3671. * @param {?FunctionNode} functionNode - The function node.
  3672. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3673. */
  3674. constructor( functionNode = null, parameters = {} ) {
  3675. super();
  3676. /**
  3677. * The function node.
  3678. *
  3679. * @type {?FunctionNode}
  3680. * @default null
  3681. */
  3682. this.functionNode = functionNode;
  3683. /**
  3684. * The parameters of the function call.
  3685. *
  3686. * @type {Object<string, Node>}
  3687. * @default {}
  3688. */
  3689. this.parameters = parameters;
  3690. }
  3691. /**
  3692. * Sets the parameters of the function call node.
  3693. *
  3694. * @param {Object<string, Node>} parameters - The parameters to set.
  3695. * @return {FunctionCallNode} A reference to this node.
  3696. */
  3697. setParameters( parameters ) {
  3698. this.parameters = parameters;
  3699. return this;
  3700. }
  3701. /**
  3702. * Returns the parameters of the function call node.
  3703. *
  3704. * @return {Object<string, Node>} The parameters of this node.
  3705. */
  3706. getParameters() {
  3707. return this.parameters;
  3708. }
  3709. /**
  3710. * Returns the type of this function call node.
  3711. *
  3712. * @param {NodeBuilder} builder - The current node builder.
  3713. * @returns {string} The type of this node.
  3714. */
  3715. getNodeType( builder ) {
  3716. return this.functionNode.getNodeType( builder );
  3717. }
  3718. /**
  3719. * Returns the function node of this function call node.
  3720. *
  3721. * @param {NodeBuilder} builder - The current node builder.
  3722. * @param {string} [name] - The name of the member.
  3723. * @returns {string} The type of the member.
  3724. */
  3725. getMemberType( builder, name ) {
  3726. return this.functionNode.getMemberType( builder, name );
  3727. }
  3728. generate( builder ) {
  3729. const params = [];
  3730. const functionNode = this.functionNode;
  3731. const inputs = functionNode.getInputs( builder );
  3732. const parameters = this.parameters;
  3733. const generateInput = ( node, inputNode ) => {
  3734. const type = inputNode.type;
  3735. const pointer = type === 'pointer';
  3736. let output;
  3737. if ( pointer ) output = '&' + node.build( builder );
  3738. else output = node.build( builder, type );
  3739. return output;
  3740. };
  3741. if ( Array.isArray( parameters ) ) {
  3742. if ( parameters.length > inputs.length ) {
  3743. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3744. parameters.length = inputs.length;
  3745. } else if ( parameters.length < inputs.length ) {
  3746. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3747. while ( parameters.length < inputs.length ) {
  3748. parameters.push( float( 0 ) );
  3749. }
  3750. }
  3751. for ( let i = 0; i < parameters.length; i ++ ) {
  3752. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3753. }
  3754. } else {
  3755. for ( const inputNode of inputs ) {
  3756. const node = parameters[ inputNode.name ];
  3757. if ( node !== undefined ) {
  3758. params.push( generateInput( node, inputNode ) );
  3759. } else {
  3760. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3761. params.push( generateInput( float( 0 ), inputNode ) );
  3762. }
  3763. }
  3764. }
  3765. const functionName = functionNode.build( builder, 'property' );
  3766. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3767. }
  3768. }
  3769. const call = ( func, ...params ) => {
  3770. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3771. return new FunctionCallNode( nodeObject( func ), params );
  3772. };
  3773. addMethodChaining( 'call', call );
  3774. const _vectorOperators = {
  3775. '==': 'equal',
  3776. '!=': 'notEqual',
  3777. '<': 'lessThan',
  3778. '>': 'greaterThan',
  3779. '<=': 'lessThanEqual',
  3780. '>=': 'greaterThanEqual',
  3781. '%': 'mod'
  3782. };
  3783. /**
  3784. * This node represents basic mathematical and logical operations like addition,
  3785. * subtraction or comparisons (e.g. `equal()`).
  3786. *
  3787. * @augments TempNode
  3788. */
  3789. class OperatorNode extends TempNode {
  3790. static get type() {
  3791. return 'OperatorNode';
  3792. }
  3793. /**
  3794. * Constructs a new operator node.
  3795. *
  3796. * @param {string} op - The operator.
  3797. * @param {Node} aNode - The first input.
  3798. * @param {Node} bNode - The second input.
  3799. * @param {...Node} params - Additional input parameters.
  3800. */
  3801. constructor( op, aNode, bNode, ...params ) {
  3802. super();
  3803. if ( params.length > 0 ) {
  3804. let finalOp = new OperatorNode( op, aNode, bNode );
  3805. for ( let i = 0; i < params.length - 1; i ++ ) {
  3806. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3807. }
  3808. aNode = finalOp;
  3809. bNode = params[ params.length - 1 ];
  3810. }
  3811. /**
  3812. * The operator.
  3813. *
  3814. * @type {string}
  3815. */
  3816. this.op = op;
  3817. /**
  3818. * The first input.
  3819. *
  3820. * @type {Node}
  3821. */
  3822. this.aNode = aNode;
  3823. /**
  3824. * The second input.
  3825. *
  3826. * @type {Node}
  3827. */
  3828. this.bNode = bNode;
  3829. /**
  3830. * This flag can be used for type testing.
  3831. *
  3832. * @type {boolean}
  3833. * @readonly
  3834. * @default true
  3835. */
  3836. this.isOperatorNode = true;
  3837. }
  3838. /**
  3839. * Returns the operator method name.
  3840. *
  3841. * @param {NodeBuilder} builder - The current node builder.
  3842. * @param {string} output - The output type.
  3843. * @returns {string} The operator method name.
  3844. */
  3845. getOperatorMethod( builder, output ) {
  3846. return builder.getMethod( _vectorOperators[ this.op ], output );
  3847. }
  3848. /**
  3849. * This method is overwritten since the node type is inferred from the operator
  3850. * and the input node types.
  3851. *
  3852. * @param {NodeBuilder} builder - The current node builder.
  3853. * @param {?string} [output=null] - The output type.
  3854. * @return {string} The node type.
  3855. */
  3856. getNodeType( builder, output = null ) {
  3857. const op = this.op;
  3858. const aNode = this.aNode;
  3859. const bNode = this.bNode;
  3860. const typeA = aNode.getNodeType( builder );
  3861. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3862. if ( typeA === 'void' || typeB === 'void' ) {
  3863. return output || 'void';
  3864. } else if ( op === '%' ) {
  3865. return typeA;
  3866. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3867. return builder.getIntegerType( typeA );
  3868. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3869. return 'bool';
  3870. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3871. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3872. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3873. } else {
  3874. // Handle matrix operations
  3875. if ( builder.isMatrix( typeA ) ) {
  3876. if ( typeB === 'float' ) {
  3877. return typeA; // matrix * scalar = matrix
  3878. } else if ( builder.isVector( typeB ) ) {
  3879. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3880. } else if ( builder.isMatrix( typeB ) ) {
  3881. return typeA; // matrix * matrix
  3882. }
  3883. } else if ( builder.isMatrix( typeB ) ) {
  3884. if ( typeA === 'float' ) {
  3885. return typeB; // scalar * matrix = matrix
  3886. } else if ( builder.isVector( typeA ) ) {
  3887. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3888. }
  3889. }
  3890. // Handle non-matrix cases
  3891. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3892. // anytype x anytype: use the greater length vector
  3893. return typeB;
  3894. }
  3895. return typeA;
  3896. }
  3897. }
  3898. generate( builder, output ) {
  3899. const op = this.op;
  3900. const { aNode, bNode } = this;
  3901. const type = this.getNodeType( builder, output );
  3902. let typeA = null;
  3903. let typeB = null;
  3904. if ( type !== 'void' ) {
  3905. typeA = aNode.getNodeType( builder );
  3906. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3907. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3908. if ( builder.isVector( typeA ) ) {
  3909. typeB = typeA;
  3910. } else if ( builder.isVector( typeB ) ) {
  3911. typeA = typeB;
  3912. } else if ( typeA !== typeB ) {
  3913. typeA = typeB = 'float';
  3914. }
  3915. } else if ( op === '>>' || op === '<<' ) {
  3916. typeA = type;
  3917. typeB = builder.changeComponentType( typeB, 'uint' );
  3918. } else if ( op === '%' ) {
  3919. typeA = type;
  3920. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3921. } else if ( builder.isMatrix( typeA ) ) {
  3922. if ( typeB === 'float' ) {
  3923. // Keep matrix type for typeA, but ensure typeB stays float
  3924. typeB = 'float';
  3925. } else if ( builder.isVector( typeB ) ) {
  3926. // matrix x vector
  3927. typeB = builder.getVectorFromMatrix( typeA );
  3928. } else if ( builder.isMatrix( typeB ) ) ; else {
  3929. typeA = typeB = type;
  3930. }
  3931. } else if ( builder.isMatrix( typeB ) ) {
  3932. if ( typeA === 'float' ) {
  3933. // Keep matrix type for typeB, but ensure typeA stays float
  3934. typeA = 'float';
  3935. } else if ( builder.isVector( typeA ) ) {
  3936. // vector x matrix
  3937. typeA = builder.getVectorFromMatrix( typeB );
  3938. } else {
  3939. typeA = typeB = type;
  3940. }
  3941. } else {
  3942. // anytype x anytype
  3943. typeA = typeB = type;
  3944. }
  3945. } else {
  3946. typeA = typeB = type;
  3947. }
  3948. const a = aNode.build( builder, typeA );
  3949. const b = bNode ? bNode.build( builder, typeB ) : null;
  3950. const fnOpSnippet = builder.getFunctionOperator( op );
  3951. if ( output !== 'void' ) {
  3952. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3953. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3954. if ( isGLSL ) {
  3955. if ( builder.isVector( typeA ) ) {
  3956. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3957. } else {
  3958. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3959. }
  3960. } else {
  3961. // WGSL
  3962. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3963. }
  3964. } else if ( op === '%' ) {
  3965. if ( builder.isInteger( typeB ) ) {
  3966. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3967. } else {
  3968. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3969. }
  3970. } else if ( op === '!' || op === '~' ) {
  3971. return builder.format( `(${op}${a})`, typeA, output );
  3972. } else if ( fnOpSnippet ) {
  3973. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3974. } else {
  3975. // Handle matrix operations
  3976. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3977. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3978. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3979. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3980. } else {
  3981. let snippet = `( ${ a } ${ op } ${ b } )`;
  3982. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3983. snippet = `all${ snippet }`;
  3984. }
  3985. return builder.format( snippet, type, output );
  3986. }
  3987. }
  3988. } else if ( typeA !== 'void' ) {
  3989. if ( fnOpSnippet ) {
  3990. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3991. } else {
  3992. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3993. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3994. } else {
  3995. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3996. }
  3997. }
  3998. }
  3999. }
  4000. serialize( data ) {
  4001. super.serialize( data );
  4002. data.op = this.op;
  4003. }
  4004. deserialize( data ) {
  4005. super.deserialize( data );
  4006. this.op = data.op;
  4007. }
  4008. }
  4009. /**
  4010. * Returns the addition of two or more value.
  4011. *
  4012. * @tsl
  4013. * @function
  4014. * @param {Node} a - The first input.
  4015. * @param {Node} b - The second input.
  4016. * @param {...Node} params - Additional input parameters.
  4017. * @returns {OperatorNode}
  4018. */
  4019. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  4020. /**
  4021. * Returns the subtraction of two or more value.
  4022. *
  4023. * @tsl
  4024. * @function
  4025. * @param {Node} a - The first input.
  4026. * @param {Node} b - The second input.
  4027. * @param {...Node} params - Additional input parameters.
  4028. * @returns {OperatorNode}
  4029. */
  4030. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4031. /**
  4032. * Returns the multiplication of two or more value.
  4033. *
  4034. * @tsl
  4035. * @function
  4036. * @param {Node} a - The first input.
  4037. * @param {Node} b - The second input.
  4038. * @param {...Node} params - Additional input parameters.
  4039. * @returns {OperatorNode}
  4040. */
  4041. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4042. /**
  4043. * Returns the division of two or more value.
  4044. *
  4045. * @tsl
  4046. * @function
  4047. * @param {Node} a - The first input.
  4048. * @param {Node} b - The second input.
  4049. * @param {...Node} params - Additional input parameters.
  4050. * @returns {OperatorNode}
  4051. */
  4052. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4053. /**
  4054. * Computes the remainder of dividing the first node by the second one.
  4055. *
  4056. * @tsl
  4057. * @function
  4058. * @param {Node} a - The first input.
  4059. * @param {Node} b - The second input.
  4060. * @returns {OperatorNode}
  4061. */
  4062. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4063. /**
  4064. * Checks if two nodes are equal.
  4065. *
  4066. * @tsl
  4067. * @function
  4068. * @param {Node} a - The first input.
  4069. * @param {Node} b - The second input.
  4070. * @returns {OperatorNode}
  4071. */
  4072. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4073. /**
  4074. * Checks if two nodes are not equal.
  4075. *
  4076. * @tsl
  4077. * @function
  4078. * @param {Node} a - The first input.
  4079. * @param {Node} b - The second input.
  4080. * @returns {OperatorNode}
  4081. */
  4082. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4083. /**
  4084. * Checks if the first node is less than the second.
  4085. *
  4086. * @tsl
  4087. * @function
  4088. * @param {Node} a - The first input.
  4089. * @param {Node} b - The second input.
  4090. * @returns {OperatorNode}
  4091. */
  4092. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4093. /**
  4094. * Checks if the first node is greater than the second.
  4095. *
  4096. * @tsl
  4097. * @function
  4098. * @param {Node} a - The first input.
  4099. * @param {Node} b - The second input.
  4100. * @returns {OperatorNode}
  4101. */
  4102. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4103. /**
  4104. * Checks if the first node is less than or equal to the second.
  4105. *
  4106. * @tsl
  4107. * @function
  4108. * @param {Node} a - The first input.
  4109. * @param {Node} b - The second input.
  4110. * @returns {OperatorNode}
  4111. */
  4112. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4113. /**
  4114. * Checks if the first node is greater than or equal to the second.
  4115. *
  4116. * @tsl
  4117. * @function
  4118. * @param {Node} a - The first input.
  4119. * @param {Node} b - The second input.
  4120. * @returns {OperatorNode}
  4121. */
  4122. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4123. /**
  4124. * Performs a logical AND operation on multiple nodes.
  4125. *
  4126. * @tsl
  4127. * @function
  4128. * @param {...Node} nodes - The input nodes to be combined using AND.
  4129. * @returns {OperatorNode}
  4130. */
  4131. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4132. /**
  4133. * Performs a logical OR operation on multiple nodes.
  4134. *
  4135. * @tsl
  4136. * @function
  4137. * @param {...Node} nodes - The input nodes to be combined using OR.
  4138. * @returns {OperatorNode}
  4139. */
  4140. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4141. /**
  4142. * Performs logical NOT on a node.
  4143. *
  4144. * @tsl
  4145. * @function
  4146. * @param {Node} value - The value.
  4147. * @returns {OperatorNode}
  4148. */
  4149. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4150. /**
  4151. * Performs logical XOR on two nodes.
  4152. *
  4153. * @tsl
  4154. * @function
  4155. * @param {Node} a - The first input.
  4156. * @param {Node} b - The second input.
  4157. * @returns {OperatorNode}
  4158. */
  4159. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4160. /**
  4161. * Performs bitwise AND on two nodes.
  4162. *
  4163. * @tsl
  4164. * @function
  4165. * @param {Node} a - The first input.
  4166. * @param {Node} b - The second input.
  4167. * @returns {OperatorNode}
  4168. */
  4169. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4170. /**
  4171. * Performs bitwise NOT on a node.
  4172. *
  4173. * @tsl
  4174. * @function
  4175. * @param {Node} a - The first input.
  4176. * @param {Node} b - The second input.
  4177. * @returns {OperatorNode}
  4178. */
  4179. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4180. /**
  4181. * Performs bitwise OR on two nodes.
  4182. *
  4183. * @tsl
  4184. * @function
  4185. * @param {Node} a - The first input.
  4186. * @param {Node} b - The second input.
  4187. * @returns {OperatorNode}
  4188. */
  4189. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4190. /**
  4191. * Performs bitwise XOR on two nodes.
  4192. *
  4193. * @tsl
  4194. * @function
  4195. * @param {Node} a - The first input.
  4196. * @param {Node} b - The second input.
  4197. * @returns {OperatorNode}
  4198. */
  4199. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4200. /**
  4201. * Shifts a node to the left.
  4202. *
  4203. * @tsl
  4204. * @function
  4205. * @param {Node} a - The node to shift.
  4206. * @param {Node} b - The value to shift.
  4207. * @returns {OperatorNode}
  4208. */
  4209. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4210. /**
  4211. * Shifts a node to the right.
  4212. *
  4213. * @tsl
  4214. * @function
  4215. * @param {Node} a - The node to shift.
  4216. * @param {Node} b - The value to shift.
  4217. * @returns {OperatorNode}
  4218. */
  4219. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4220. /**
  4221. * Increments a node by 1.
  4222. *
  4223. * @tsl
  4224. * @function
  4225. * @param {Node} a - The node to increment.
  4226. * @returns {OperatorNode}
  4227. */
  4228. const incrementBefore = Fn( ( [ a ] ) => {
  4229. a.addAssign( 1 );
  4230. return a;
  4231. } );
  4232. /**
  4233. * Decrements a node by 1.
  4234. *
  4235. * @tsl
  4236. * @function
  4237. * @param {Node} a - The node to decrement.
  4238. * @returns {OperatorNode}
  4239. */
  4240. const decrementBefore = Fn( ( [ a ] ) => {
  4241. a.subAssign( 1 );
  4242. return a;
  4243. } );
  4244. /**
  4245. * Increments a node by 1 and returns the previous value.
  4246. *
  4247. * @tsl
  4248. * @function
  4249. * @param {Node} a - The node to increment.
  4250. * @returns {OperatorNode}
  4251. */
  4252. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4253. const temp = int( a ).toConst();
  4254. a.addAssign( 1 );
  4255. return temp;
  4256. } );
  4257. /**
  4258. * Decrements a node by 1 and returns the previous value.
  4259. *
  4260. * @tsl
  4261. * @function
  4262. * @param {Node} a - The node to decrement.
  4263. * @returns {OperatorNode}
  4264. */
  4265. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4266. const temp = int( a ).toConst();
  4267. a.subAssign( 1 );
  4268. return temp;
  4269. } );
  4270. addMethodChaining( 'add', add );
  4271. addMethodChaining( 'sub', sub );
  4272. addMethodChaining( 'mul', mul );
  4273. addMethodChaining( 'div', div );
  4274. addMethodChaining( 'mod', mod );
  4275. addMethodChaining( 'equal', equal );
  4276. addMethodChaining( 'notEqual', notEqual );
  4277. addMethodChaining( 'lessThan', lessThan );
  4278. addMethodChaining( 'greaterThan', greaterThan );
  4279. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4280. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4281. addMethodChaining( 'and', and );
  4282. addMethodChaining( 'or', or );
  4283. addMethodChaining( 'not', not );
  4284. addMethodChaining( 'xor', xor );
  4285. addMethodChaining( 'bitAnd', bitAnd );
  4286. addMethodChaining( 'bitNot', bitNot );
  4287. addMethodChaining( 'bitOr', bitOr );
  4288. addMethodChaining( 'bitXor', bitXor );
  4289. addMethodChaining( 'shiftLeft', shiftLeft );
  4290. addMethodChaining( 'shiftRight', shiftRight );
  4291. addMethodChaining( 'incrementBefore', incrementBefore );
  4292. addMethodChaining( 'decrementBefore', decrementBefore );
  4293. addMethodChaining( 'increment', increment );
  4294. addMethodChaining( 'decrement', decrement );
  4295. /**
  4296. * @tsl
  4297. * @function
  4298. * @deprecated since r175. Use {@link mod} instead.
  4299. *
  4300. * @param {Node} a - The first input.
  4301. * @param {Node} b - The second input.
  4302. * @returns {OperatorNode}
  4303. */
  4304. const modInt = ( a, b ) => { // @deprecated, r175
  4305. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4306. return mod( int( a ), int( b ) );
  4307. };
  4308. addMethodChaining( 'modInt', modInt );
  4309. /**
  4310. * This node represents a variety of mathematical methods available in shaders.
  4311. * They are divided into three categories:
  4312. *
  4313. * - Methods with one input like `sin`, `cos` or `normalize`.
  4314. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4315. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4316. *
  4317. * @augments TempNode
  4318. */
  4319. class MathNode extends TempNode {
  4320. static get type() {
  4321. return 'MathNode';
  4322. }
  4323. /**
  4324. * Constructs a new math node.
  4325. *
  4326. * @param {string} method - The method name.
  4327. * @param {Node} aNode - The first input.
  4328. * @param {?Node} [bNode=null] - The second input.
  4329. * @param {?Node} [cNode=null] - The third input.
  4330. */
  4331. constructor( method, aNode, bNode = null, cNode = null ) {
  4332. super();
  4333. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4334. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4335. let finalOp = new MathNode( method, aNode, bNode );
  4336. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4337. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4338. }
  4339. aNode = finalOp;
  4340. bNode = arguments[ arguments.length - 1 ];
  4341. cNode = null;
  4342. }
  4343. /**
  4344. * The method name.
  4345. *
  4346. * @type {string}
  4347. */
  4348. this.method = method;
  4349. /**
  4350. * The first input.
  4351. *
  4352. * @type {Node}
  4353. */
  4354. this.aNode = aNode;
  4355. /**
  4356. * The second input.
  4357. *
  4358. * @type {?Node}
  4359. * @default null
  4360. */
  4361. this.bNode = bNode;
  4362. /**
  4363. * The third input.
  4364. *
  4365. * @type {?Node}
  4366. * @default null
  4367. */
  4368. this.cNode = cNode;
  4369. /**
  4370. * This flag can be used for type testing.
  4371. *
  4372. * @type {boolean}
  4373. * @readonly
  4374. * @default true
  4375. */
  4376. this.isMathNode = true;
  4377. }
  4378. /**
  4379. * The input type is inferred from the node types of the input nodes.
  4380. *
  4381. * @param {NodeBuilder} builder - The current node builder.
  4382. * @return {string} The input type.
  4383. */
  4384. getInputType( builder ) {
  4385. const aType = this.aNode.getNodeType( builder );
  4386. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4387. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4388. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4389. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4390. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4391. if ( aLen > bLen && aLen > cLen ) {
  4392. return aType;
  4393. } else if ( bLen > cLen ) {
  4394. return bType;
  4395. } else if ( cLen > aLen ) {
  4396. return cType;
  4397. }
  4398. return aType;
  4399. }
  4400. /**
  4401. * The selected method as well as the input type determine the node type of this node.
  4402. *
  4403. * @param {NodeBuilder} builder - The current node builder.
  4404. * @return {string} The node type.
  4405. */
  4406. getNodeType( builder ) {
  4407. const method = this.method;
  4408. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4409. return 'float';
  4410. } else if ( method === MathNode.CROSS ) {
  4411. return 'vec3';
  4412. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4413. return 'bool';
  4414. } else if ( method === MathNode.EQUALS ) {
  4415. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4416. } else {
  4417. return this.getInputType( builder );
  4418. }
  4419. }
  4420. setup( builder ) {
  4421. const { aNode, bNode, method } = this;
  4422. let outputNode = null;
  4423. if ( method === MathNode.ONE_MINUS ) {
  4424. outputNode = sub( 1.0, aNode );
  4425. } else if ( method === MathNode.RECIPROCAL ) {
  4426. outputNode = div( 1.0, aNode );
  4427. } else if ( method === MathNode.DIFFERENCE ) {
  4428. outputNode = abs( sub( aNode, bNode ) );
  4429. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4430. // dir can be either a direction vector or a normal vector
  4431. // upper-left 3x3 of matrix is assumed to be orthogonal
  4432. let tA = aNode;
  4433. let tB = bNode;
  4434. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4435. tB = vec4( vec3( tB ), 0.0 );
  4436. } else {
  4437. tA = vec4( vec3( tA ), 0.0 );
  4438. }
  4439. const mulNode = mul( tA, tB ).xyz;
  4440. outputNode = normalize( mulNode );
  4441. }
  4442. if ( outputNode !== null ) {
  4443. return outputNode;
  4444. } else {
  4445. return super.setup( builder );
  4446. }
  4447. }
  4448. generate( builder, output ) {
  4449. const properties = builder.getNodeProperties( this );
  4450. if ( properties.outputNode ) {
  4451. return super.generate( builder, output );
  4452. }
  4453. let method = this.method;
  4454. const type = this.getNodeType( builder );
  4455. const inputType = this.getInputType( builder );
  4456. const a = this.aNode;
  4457. const b = this.bNode;
  4458. const c = this.cNode;
  4459. const coordinateSystem = builder.renderer.coordinateSystem;
  4460. if ( method === MathNode.NEGATE ) {
  4461. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4462. } else {
  4463. const params = [];
  4464. if ( method === MathNode.CROSS ) {
  4465. params.push(
  4466. a.build( builder, type ),
  4467. b.build( builder, type )
  4468. );
  4469. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4470. params.push(
  4471. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4472. b.build( builder, inputType )
  4473. );
  4474. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4475. params.push(
  4476. a.build( builder, inputType ),
  4477. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4478. );
  4479. } else if ( method === MathNode.REFRACT ) {
  4480. params.push(
  4481. a.build( builder, inputType ),
  4482. b.build( builder, inputType ),
  4483. c.build( builder, 'float' )
  4484. );
  4485. } else if ( method === MathNode.MIX ) {
  4486. params.push(
  4487. a.build( builder, inputType ),
  4488. b.build( builder, inputType ),
  4489. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4490. );
  4491. } else {
  4492. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4493. method = 'atan2';
  4494. }
  4495. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4496. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4497. method = '/*' + method + '*/';
  4498. }
  4499. params.push( a.build( builder, inputType ) );
  4500. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4501. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4502. }
  4503. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4504. }
  4505. }
  4506. serialize( data ) {
  4507. super.serialize( data );
  4508. data.method = this.method;
  4509. }
  4510. deserialize( data ) {
  4511. super.deserialize( data );
  4512. this.method = data.method;
  4513. }
  4514. }
  4515. // 1 input
  4516. MathNode.ALL = 'all';
  4517. MathNode.ANY = 'any';
  4518. MathNode.RADIANS = 'radians';
  4519. MathNode.DEGREES = 'degrees';
  4520. MathNode.EXP = 'exp';
  4521. MathNode.EXP2 = 'exp2';
  4522. MathNode.LOG = 'log';
  4523. MathNode.LOG2 = 'log2';
  4524. MathNode.SQRT = 'sqrt';
  4525. MathNode.INVERSE_SQRT = 'inversesqrt';
  4526. MathNode.FLOOR = 'floor';
  4527. MathNode.CEIL = 'ceil';
  4528. MathNode.NORMALIZE = 'normalize';
  4529. MathNode.FRACT = 'fract';
  4530. MathNode.SIN = 'sin';
  4531. MathNode.COS = 'cos';
  4532. MathNode.TAN = 'tan';
  4533. MathNode.ASIN = 'asin';
  4534. MathNode.ACOS = 'acos';
  4535. MathNode.ATAN = 'atan';
  4536. MathNode.ABS = 'abs';
  4537. MathNode.SIGN = 'sign';
  4538. MathNode.LENGTH = 'length';
  4539. MathNode.NEGATE = 'negate';
  4540. MathNode.ONE_MINUS = 'oneMinus';
  4541. MathNode.DFDX = 'dFdx';
  4542. MathNode.DFDY = 'dFdy';
  4543. MathNode.ROUND = 'round';
  4544. MathNode.RECIPROCAL = 'reciprocal';
  4545. MathNode.TRUNC = 'trunc';
  4546. MathNode.FWIDTH = 'fwidth';
  4547. MathNode.TRANSPOSE = 'transpose';
  4548. MathNode.DETERMINANT = 'determinant';
  4549. MathNode.INVERSE = 'inverse';
  4550. // 2 inputs
  4551. MathNode.EQUALS = 'equals';
  4552. MathNode.MIN = 'min';
  4553. MathNode.MAX = 'max';
  4554. MathNode.STEP = 'step';
  4555. MathNode.REFLECT = 'reflect';
  4556. MathNode.DISTANCE = 'distance';
  4557. MathNode.DIFFERENCE = 'difference';
  4558. MathNode.DOT = 'dot';
  4559. MathNode.CROSS = 'cross';
  4560. MathNode.POW = 'pow';
  4561. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4562. // 3 inputs
  4563. MathNode.MIX = 'mix';
  4564. MathNode.CLAMP = 'clamp';
  4565. MathNode.REFRACT = 'refract';
  4566. MathNode.SMOOTHSTEP = 'smoothstep';
  4567. MathNode.FACEFORWARD = 'faceforward';
  4568. // 1 inputs
  4569. /**
  4570. * A small value used to handle floating-point precision errors.
  4571. *
  4572. * @tsl
  4573. * @type {Node<float>}
  4574. */
  4575. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4576. /**
  4577. * Represents infinity.
  4578. *
  4579. * @tsl
  4580. * @type {Node<float>}
  4581. */
  4582. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4583. /**
  4584. * Represents PI.
  4585. *
  4586. * @tsl
  4587. * @type {Node<float>}
  4588. */
  4589. const PI = /*@__PURE__*/ float( Math.PI );
  4590. /**
  4591. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4592. *
  4593. * @tsl
  4594. * @deprecated
  4595. * @type {Node<float>}
  4596. */
  4597. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4598. /**
  4599. * Represents PI * 2.
  4600. *
  4601. * @tsl
  4602. * @type {Node<float>}
  4603. */
  4604. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4605. /**
  4606. * Represents PI / 2.
  4607. *
  4608. * @tsl
  4609. * @type {Node<float>}
  4610. */
  4611. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4612. /**
  4613. * Returns `true` if all components of `x` are `true`.
  4614. *
  4615. * @tsl
  4616. * @function
  4617. * @param {Node | number} x - The parameter.
  4618. * @returns {Node<bool>}
  4619. */
  4620. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4621. /**
  4622. * Returns `true` if any components of `x` are `true`.
  4623. *
  4624. * @tsl
  4625. * @function
  4626. * @param {Node | number} x - The parameter.
  4627. * @returns {Node<bool>}
  4628. */
  4629. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4630. /**
  4631. * Converts a quantity in degrees to radians.
  4632. *
  4633. * @tsl
  4634. * @function
  4635. * @param {Node | number} x - The input in degrees.
  4636. * @returns {Node}
  4637. */
  4638. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4639. /**
  4640. * Convert a quantity in radians to degrees.
  4641. *
  4642. * @tsl
  4643. * @function
  4644. * @param {Node | number} x - The input in radians.
  4645. * @returns {Node}
  4646. */
  4647. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4648. /**
  4649. * Returns the natural exponentiation of the parameter.
  4650. *
  4651. * @tsl
  4652. * @function
  4653. * @param {Node | number} x - The parameter.
  4654. * @returns {Node}
  4655. */
  4656. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4657. /**
  4658. * Returns 2 raised to the power of the parameter.
  4659. *
  4660. * @tsl
  4661. * @function
  4662. * @param {Node | number} x - The parameter.
  4663. * @returns {Node}
  4664. */
  4665. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4666. /**
  4667. * Returns the natural logarithm of the parameter.
  4668. *
  4669. * @tsl
  4670. * @function
  4671. * @param {Node | number} x - The parameter.
  4672. * @returns {Node}
  4673. */
  4674. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4675. /**
  4676. * Returns the base 2 logarithm of the parameter.
  4677. *
  4678. * @tsl
  4679. * @function
  4680. * @param {Node | number} x - The parameter.
  4681. * @returns {Node}
  4682. */
  4683. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4684. /**
  4685. * Returns the square root of the parameter.
  4686. *
  4687. * @tsl
  4688. * @function
  4689. * @param {Node | number} x - The parameter.
  4690. * @returns {Node}
  4691. */
  4692. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4693. /**
  4694. * Returns the inverse of the square root of the parameter.
  4695. *
  4696. * @tsl
  4697. * @function
  4698. * @param {Node | number} x - The parameter.
  4699. * @returns {Node}
  4700. */
  4701. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4702. /**
  4703. * Finds the nearest integer less than or equal to the parameter.
  4704. *
  4705. * @tsl
  4706. * @function
  4707. * @param {Node | number} x - The parameter.
  4708. * @returns {Node}
  4709. */
  4710. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4711. /**
  4712. * Finds the nearest integer that is greater than or equal to the parameter.
  4713. *
  4714. * @tsl
  4715. * @function
  4716. * @param {Node | number} x - The parameter.
  4717. * @returns {Node}
  4718. */
  4719. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4720. /**
  4721. * Calculates the unit vector in the same direction as the original vector.
  4722. *
  4723. * @tsl
  4724. * @function
  4725. * @param {Node} x - The input vector.
  4726. * @returns {Node}
  4727. */
  4728. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4729. /**
  4730. * Computes the fractional part of the parameter.
  4731. *
  4732. * @tsl
  4733. * @function
  4734. * @param {Node | number} x - The parameter.
  4735. * @returns {Node}
  4736. */
  4737. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4738. /**
  4739. * Returns the sine of the parameter.
  4740. *
  4741. * @tsl
  4742. * @function
  4743. * @param {Node | number} x - The parameter.
  4744. * @returns {Node}
  4745. */
  4746. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4747. /**
  4748. * Returns the cosine of the parameter.
  4749. *
  4750. * @tsl
  4751. * @function
  4752. * @param {Node | number} x - The parameter.
  4753. * @returns {Node}
  4754. */
  4755. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4756. /**
  4757. * Returns the tangent of the parameter.
  4758. *
  4759. * @tsl
  4760. * @function
  4761. * @param {Node | number} x - The parameter.
  4762. * @returns {Node}
  4763. */
  4764. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4765. /**
  4766. * Returns the arcsine of the parameter.
  4767. *
  4768. * @tsl
  4769. * @function
  4770. * @param {Node | number} x - The parameter.
  4771. * @returns {Node}
  4772. */
  4773. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4774. /**
  4775. * Returns the arccosine of the parameter.
  4776. *
  4777. * @tsl
  4778. * @function
  4779. * @param {Node | number} x - The parameter.
  4780. * @returns {Node}
  4781. */
  4782. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4783. /**
  4784. * Returns the arc-tangent of the parameter.
  4785. * If two parameters are provided, the result is `atan2(y/x)`.
  4786. *
  4787. * @tsl
  4788. * @function
  4789. * @param {Node | number} y - The y parameter.
  4790. * @param {?(Node | number)} x - The x parameter.
  4791. * @returns {Node}
  4792. */
  4793. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4794. /**
  4795. * Returns the absolute value of the parameter.
  4796. *
  4797. * @tsl
  4798. * @function
  4799. * @param {Node | number} x - The parameter.
  4800. * @returns {Node}
  4801. */
  4802. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4803. /**
  4804. * Extracts the sign of the parameter.
  4805. *
  4806. * @tsl
  4807. * @function
  4808. * @param {Node | number} x - The parameter.
  4809. * @returns {Node}
  4810. */
  4811. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4812. /**
  4813. * Calculates the length of a vector.
  4814. *
  4815. * @tsl
  4816. * @function
  4817. * @param {Node} x - The parameter.
  4818. * @returns {Node<float>}
  4819. */
  4820. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4821. /**
  4822. * Negates the value of the parameter (-x).
  4823. *
  4824. * @tsl
  4825. * @function
  4826. * @param {Node | number} x - The parameter.
  4827. * @returns {Node}
  4828. */
  4829. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4830. /**
  4831. * Return `1` minus the parameter.
  4832. *
  4833. * @tsl
  4834. * @function
  4835. * @param {Node | number} x - The parameter.
  4836. * @returns {Node}
  4837. */
  4838. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4839. /**
  4840. * Returns the partial derivative of the parameter with respect to x.
  4841. *
  4842. * @tsl
  4843. * @function
  4844. * @param {Node | number} x - The parameter.
  4845. * @returns {Node}
  4846. */
  4847. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4848. /**
  4849. * Returns the partial derivative of the parameter with respect to y.
  4850. *
  4851. * @tsl
  4852. * @function
  4853. * @param {Node | number} x - The parameter.
  4854. * @returns {Node}
  4855. */
  4856. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4857. /**
  4858. * Rounds the parameter to the nearest integer.
  4859. *
  4860. * @tsl
  4861. * @function
  4862. * @param {Node | number} x - The parameter.
  4863. * @returns {Node}
  4864. */
  4865. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4866. /**
  4867. * Returns the reciprocal of the parameter `(1/x)`.
  4868. *
  4869. * @tsl
  4870. * @function
  4871. * @param {Node | number} x - The parameter.
  4872. * @returns {Node}
  4873. */
  4874. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4875. /**
  4876. * Truncates the parameter, removing the fractional part.
  4877. *
  4878. * @tsl
  4879. * @function
  4880. * @param {Node | number} x - The parameter.
  4881. * @returns {Node}
  4882. */
  4883. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4884. /**
  4885. * Returns the sum of the absolute derivatives in x and y.
  4886. *
  4887. * @tsl
  4888. * @function
  4889. * @param {Node | number} x - The parameter.
  4890. * @returns {Node}
  4891. */
  4892. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4893. /**
  4894. * Returns the transpose of a matrix.
  4895. *
  4896. * @tsl
  4897. * @function
  4898. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4899. * @returns {Node}
  4900. */
  4901. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4902. /**
  4903. * Returns the determinant of a matrix.
  4904. *
  4905. * @tsl
  4906. * @function
  4907. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4908. * @returns {Node<float>}
  4909. */
  4910. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4911. /**
  4912. * Returns the inverse of a matrix.
  4913. *
  4914. * @tsl
  4915. * @function
  4916. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4917. * @returns {Node<mat2|mat3|mat4>}
  4918. */
  4919. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4920. // 2 inputs
  4921. /**
  4922. * Returns `true` if `x` equals `y`.
  4923. *
  4924. * @tsl
  4925. * @function
  4926. * @param {Node | number} x - The first parameter.
  4927. * @param {Node | number} y - The second parameter.
  4928. * @deprecated since r175. Use {@link equal} instead.
  4929. * @returns {Node<bool>}
  4930. */
  4931. const equals = ( x, y ) => { // @deprecated, r172
  4932. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4933. return equal( x, y );
  4934. };
  4935. /**
  4936. * Returns the least of the given values.
  4937. *
  4938. * @tsl
  4939. * @function
  4940. * @param {...(Node | number)} values - The values to compare.
  4941. * @returns {Node}
  4942. */
  4943. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4944. /**
  4945. * Returns the greatest of the given values.
  4946. *
  4947. * @tsl
  4948. * @function
  4949. * @param {...(Node | number)} values - The values to compare.
  4950. * @returns {Node}
  4951. */
  4952. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4953. /**
  4954. * Generate a step function by comparing two values.
  4955. *
  4956. * @tsl
  4957. * @function
  4958. * @param {Node | number} x - The y parameter.
  4959. * @param {Node | number} y - The x parameter.
  4960. * @returns {Node}
  4961. */
  4962. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4963. /**
  4964. * Calculates the reflection direction for an incident vector.
  4965. *
  4966. * @tsl
  4967. * @function
  4968. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4969. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4970. * @returns {Node<vec2|vec3|vec4>}
  4971. */
  4972. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4973. /**
  4974. * Calculates the distance between two points.
  4975. *
  4976. * @tsl
  4977. * @function
  4978. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4979. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4980. * @returns {Node<float>}
  4981. */
  4982. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4983. /**
  4984. * Calculates the absolute difference between two values.
  4985. *
  4986. * @tsl
  4987. * @function
  4988. * @param {Node | number} x - The first parameter.
  4989. * @param {Node | number} y - The second parameter.
  4990. * @returns {Node}
  4991. */
  4992. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4993. /**
  4994. * Calculates the dot product of two vectors.
  4995. *
  4996. * @tsl
  4997. * @function
  4998. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4999. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  5000. * @returns {Node<float>}
  5001. */
  5002. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  5003. /**
  5004. * Calculates the cross product of two vectors.
  5005. *
  5006. * @tsl
  5007. * @function
  5008. * @param {Node<vec2|vec3>} x - The first vector.
  5009. * @param {Node<vec2|vec3>} y - The second vector.
  5010. * @returns {Node<float|vec3>}
  5011. */
  5012. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  5013. /**
  5014. * Return the value of the first parameter raised to the power of the second one.
  5015. *
  5016. * @tsl
  5017. * @function
  5018. * @param {Node | number} x - The first parameter.
  5019. * @param {Node | number} y - The second parameter.
  5020. * @returns {Node}
  5021. */
  5022. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5023. /**
  5024. * Returns the square of the parameter.
  5025. *
  5026. * @tsl
  5027. * @function
  5028. * @param {Node | number} x - The first parameter.
  5029. * @returns {Node}
  5030. */
  5031. const pow2 = ( x ) => mul( x, x );
  5032. /**
  5033. * Returns the cube of the parameter.
  5034. *
  5035. * @tsl
  5036. * @function
  5037. * @param {Node | number} x - The first parameter.
  5038. * @returns {Node}
  5039. */
  5040. const pow3 = ( x ) => mul( x, x, x );
  5041. /**
  5042. * Returns the fourth power of the parameter.
  5043. *
  5044. * @tsl
  5045. * @function
  5046. * @param {Node | number} x - The first parameter.
  5047. * @returns {Node}
  5048. */
  5049. const pow4 = ( x ) => mul( x, x, x, x );
  5050. /**
  5051. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5052. *
  5053. * @tsl
  5054. * @function
  5055. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5056. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5057. * @returns {Node}
  5058. */
  5059. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5060. /**
  5061. * Returns the cube root of a number.
  5062. *
  5063. * @tsl
  5064. * @function
  5065. * @param {Node | number} a - The first parameter.
  5066. * @returns {Node}
  5067. */
  5068. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5069. /**
  5070. * Calculate the squared length of a vector.
  5071. *
  5072. * @tsl
  5073. * @function
  5074. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5075. * @returns {Node<float>}
  5076. */
  5077. const lengthSq = ( a ) => dot( a, a );
  5078. /**
  5079. * Linearly interpolates between two values.
  5080. *
  5081. * @tsl
  5082. * @function
  5083. * @param {Node | number} a - The first parameter.
  5084. * @param {Node | number} b - The second parameter.
  5085. * @param {Node | number} t - The interpolation value.
  5086. * @returns {Node}
  5087. */
  5088. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5089. /**
  5090. * Constrains a value to lie between two further values.
  5091. *
  5092. * @tsl
  5093. * @function
  5094. * @param {Node | number} value - The value to constrain.
  5095. * @param {Node | number} [low=0] - The lower bound.
  5096. * @param {Node | number} [high=1] - The upper bound.
  5097. * @returns {Node}
  5098. */
  5099. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5100. /**
  5101. * Constrains a value between `0` and `1`.
  5102. *
  5103. * @tsl
  5104. * @function
  5105. * @param {Node | number} value - The value to constrain.
  5106. * @returns {Node}
  5107. */
  5108. const saturate = ( value ) => clamp( value );
  5109. /**
  5110. * Calculates the refraction direction for an incident vector.
  5111. *
  5112. * @tsl
  5113. * @function
  5114. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5115. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5116. * @param {Node<float>} eta - The ratio of indices of refraction.
  5117. * @returns {Node<vec2|vec3|vec4>}
  5118. */
  5119. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5120. /**
  5121. * Performs a Hermite interpolation between two values.
  5122. *
  5123. * @tsl
  5124. * @function
  5125. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5126. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5127. * @param {Node | number} x - The source value for interpolation.
  5128. * @returns {Node}
  5129. */
  5130. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5131. /**
  5132. * Returns a vector pointing in the same direction as another.
  5133. *
  5134. * @tsl
  5135. * @function
  5136. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5137. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5138. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5139. * @returns {Node<vec2|vec3|vec4>}
  5140. */
  5141. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5142. /**
  5143. * Returns a random value for the given uv.
  5144. *
  5145. * @tsl
  5146. * @function
  5147. * @param {Node<vec2>} uv - The uv node.
  5148. * @returns {Node<float>}
  5149. */
  5150. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5151. const a = 12.9898, b = 78.233, c = 43758.5453;
  5152. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5153. return fract( sin( sn ).mul( c ) );
  5154. } );
  5155. /**
  5156. * Alias for `mix()` with a different parameter order.
  5157. *
  5158. * @tsl
  5159. * @function
  5160. * @param {Node | number} t - The interpolation value.
  5161. * @param {Node | number} e1 - The first parameter.
  5162. * @param {Node | number} e2 - The second parameter.
  5163. * @returns {Node}
  5164. */
  5165. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5166. /**
  5167. * Alias for `smoothstep()` with a different parameter order.
  5168. *
  5169. * @tsl
  5170. * @function
  5171. * @param {Node | number} x - The source value for interpolation.
  5172. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5173. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5174. * @returns {Node}
  5175. */
  5176. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5177. /**
  5178. * Alias for `step()` with a different parameter order.
  5179. *
  5180. * @tsl
  5181. * @function
  5182. * @param {Node | number} x - The source value for interpolation.
  5183. * @param {Node | number} edge - The edge value.
  5184. * @returns {Node}
  5185. */
  5186. const stepElement = ( x, edge ) => step( edge, x );
  5187. /**
  5188. * Returns the arc-tangent of the quotient of its parameters.
  5189. *
  5190. * @tsl
  5191. * @function
  5192. * @deprecated since r172. Use {@link atan} instead.
  5193. *
  5194. * @param {Node | number} y - The y parameter.
  5195. * @param {Node | number} x - The x parameter.
  5196. * @returns {Node}
  5197. */
  5198. const atan2 = ( y, x ) => { // @deprecated, r172
  5199. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5200. return atan( y, x );
  5201. };
  5202. // GLSL alias function
  5203. const faceforward = faceForward;
  5204. const inversesqrt = inverseSqrt;
  5205. // Method chaining
  5206. addMethodChaining( 'all', all );
  5207. addMethodChaining( 'any', any );
  5208. addMethodChaining( 'equals', equals );
  5209. addMethodChaining( 'radians', radians );
  5210. addMethodChaining( 'degrees', degrees );
  5211. addMethodChaining( 'exp', exp );
  5212. addMethodChaining( 'exp2', exp2 );
  5213. addMethodChaining( 'log', log );
  5214. addMethodChaining( 'log2', log2 );
  5215. addMethodChaining( 'sqrt', sqrt );
  5216. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5217. addMethodChaining( 'floor', floor );
  5218. addMethodChaining( 'ceil', ceil );
  5219. addMethodChaining( 'normalize', normalize );
  5220. addMethodChaining( 'fract', fract );
  5221. addMethodChaining( 'sin', sin );
  5222. addMethodChaining( 'cos', cos );
  5223. addMethodChaining( 'tan', tan );
  5224. addMethodChaining( 'asin', asin );
  5225. addMethodChaining( 'acos', acos );
  5226. addMethodChaining( 'atan', atan );
  5227. addMethodChaining( 'abs', abs );
  5228. addMethodChaining( 'sign', sign );
  5229. addMethodChaining( 'length', length );
  5230. addMethodChaining( 'lengthSq', lengthSq );
  5231. addMethodChaining( 'negate', negate );
  5232. addMethodChaining( 'oneMinus', oneMinus );
  5233. addMethodChaining( 'dFdx', dFdx );
  5234. addMethodChaining( 'dFdy', dFdy );
  5235. addMethodChaining( 'round', round );
  5236. addMethodChaining( 'reciprocal', reciprocal );
  5237. addMethodChaining( 'trunc', trunc );
  5238. addMethodChaining( 'fwidth', fwidth );
  5239. addMethodChaining( 'atan2', atan2 );
  5240. addMethodChaining( 'min', min$1 );
  5241. addMethodChaining( 'max', max$1 );
  5242. addMethodChaining( 'step', stepElement );
  5243. addMethodChaining( 'reflect', reflect );
  5244. addMethodChaining( 'distance', distance );
  5245. addMethodChaining( 'dot', dot );
  5246. addMethodChaining( 'cross', cross );
  5247. addMethodChaining( 'pow', pow );
  5248. addMethodChaining( 'pow2', pow2 );
  5249. addMethodChaining( 'pow3', pow3 );
  5250. addMethodChaining( 'pow4', pow4 );
  5251. addMethodChaining( 'transformDirection', transformDirection );
  5252. addMethodChaining( 'mix', mixElement );
  5253. addMethodChaining( 'clamp', clamp );
  5254. addMethodChaining( 'refract', refract );
  5255. addMethodChaining( 'smoothstep', smoothstepElement );
  5256. addMethodChaining( 'faceForward', faceForward );
  5257. addMethodChaining( 'difference', difference );
  5258. addMethodChaining( 'saturate', saturate );
  5259. addMethodChaining( 'cbrt', cbrt );
  5260. addMethodChaining( 'transpose', transpose );
  5261. addMethodChaining( 'determinant', determinant );
  5262. addMethodChaining( 'inverse', inverse );
  5263. addMethodChaining( 'rand', rand );
  5264. /**
  5265. * Represents a logical `if/else` statement. Can be used as an alternative
  5266. * to the `If()`/`Else()` syntax.
  5267. *
  5268. * The corresponding TSL `select()` looks like so:
  5269. * ```js
  5270. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5271. * ```
  5272. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5273. * determine the outcome of the entire statement.
  5274. *
  5275. * @augments Node
  5276. */
  5277. class ConditionalNode extends Node {
  5278. static get type() {
  5279. return 'ConditionalNode';
  5280. }
  5281. /**
  5282. * Constructs a new conditional node.
  5283. *
  5284. * @param {Node} condNode - The node that defines the condition.
  5285. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5286. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5287. */
  5288. constructor( condNode, ifNode, elseNode = null ) {
  5289. super();
  5290. /**
  5291. * The node that defines the condition.
  5292. *
  5293. * @type {Node}
  5294. */
  5295. this.condNode = condNode;
  5296. /**
  5297. * The node that is evaluate when the condition ends up `true`.
  5298. *
  5299. * @type {Node}
  5300. */
  5301. this.ifNode = ifNode;
  5302. /**
  5303. * The node that is evaluate when the condition ends up `false`.
  5304. *
  5305. * @type {?Node}
  5306. * @default null
  5307. */
  5308. this.elseNode = elseNode;
  5309. }
  5310. /**
  5311. * This method is overwritten since the node type is inferred from the if/else
  5312. * nodes.
  5313. *
  5314. * @param {NodeBuilder} builder - The current node builder.
  5315. * @return {string} The node type.
  5316. */
  5317. getNodeType( builder ) {
  5318. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5319. if ( ifNode === undefined ) {
  5320. // fallback setup
  5321. builder.flowBuildStage( this, 'setup' );
  5322. return this.getNodeType( builder );
  5323. }
  5324. const ifType = ifNode.getNodeType( builder );
  5325. if ( elseNode !== null ) {
  5326. const elseType = elseNode.getNodeType( builder );
  5327. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5328. return elseType;
  5329. }
  5330. }
  5331. return ifType;
  5332. }
  5333. setup( builder ) {
  5334. const condNode = this.condNode;
  5335. const ifNode = this.ifNode.isolate();
  5336. const elseNode = this.elseNode ? this.elseNode.isolate() : null;
  5337. //
  5338. const currentNodeBlock = builder.context.nodeBlock;
  5339. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5340. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5341. //
  5342. const isUniformFlow = builder.context.uniformFlow;
  5343. const properties = builder.getNodeProperties( this );
  5344. properties.condNode = condNode;
  5345. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5346. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5347. }
  5348. generate( builder, output ) {
  5349. const type = this.getNodeType( builder );
  5350. const nodeData = builder.getDataFromNode( this );
  5351. if ( nodeData.nodeProperty !== undefined ) {
  5352. return nodeData.nodeProperty;
  5353. }
  5354. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5355. const functionNode = builder.currentFunctionNode;
  5356. const needsOutput = output !== 'void';
  5357. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5358. nodeData.nodeProperty = nodeProperty;
  5359. const nodeSnippet = condNode.build( builder, 'bool' );
  5360. const isUniformFlow = builder.context.uniformFlow;
  5361. if ( isUniformFlow && elseNode !== null ) {
  5362. const ifSnippet = ifNode.build( builder, type );
  5363. const elseSnippet = elseNode.build( builder, type );
  5364. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5365. // TODO: If node property already exists return something else
  5366. return builder.format( mathSnippet, type, output );
  5367. }
  5368. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5369. let ifSnippet = ifNode.build( builder, type );
  5370. if ( ifSnippet ) {
  5371. if ( needsOutput ) {
  5372. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5373. } else {
  5374. ifSnippet = 'return ' + ifSnippet + ';';
  5375. if ( functionNode === null ) {
  5376. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5377. ifSnippet = '// ' + ifSnippet;
  5378. }
  5379. }
  5380. }
  5381. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5382. if ( elseNode !== null ) {
  5383. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5384. let elseSnippet = elseNode.build( builder, type );
  5385. if ( elseSnippet ) {
  5386. if ( needsOutput ) {
  5387. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5388. } else {
  5389. elseSnippet = 'return ' + elseSnippet + ';';
  5390. if ( functionNode === null ) {
  5391. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5392. elseSnippet = '// ' + elseSnippet;
  5393. }
  5394. }
  5395. }
  5396. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5397. } else {
  5398. builder.addFlowCode( '\n\n' );
  5399. }
  5400. return builder.format( nodeProperty, type, output );
  5401. }
  5402. }
  5403. /**
  5404. * TSL function for creating a conditional node.
  5405. *
  5406. * @tsl
  5407. * @function
  5408. * @param {Node} condNode - The node that defines the condition.
  5409. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5410. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5411. * @returns {ConditionalNode}
  5412. */
  5413. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5414. addMethodChaining( 'select', select );
  5415. /**
  5416. * This node can be used as a context management component for another node.
  5417. * {@link NodeBuilder} performs its node building process in a specific context and
  5418. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5419. *
  5420. * ```js
  5421. *node.context( { getUV: () => customCoord } );
  5422. *```
  5423. * @augments Node
  5424. */
  5425. class ContextNode extends Node {
  5426. static get type() {
  5427. return 'ContextNode';
  5428. }
  5429. /**
  5430. * Constructs a new context node.
  5431. *
  5432. * @param {Node} node - The node whose context should be modified.
  5433. * @param {Object} [value={}] - The modified context data.
  5434. */
  5435. constructor( node, value = {} ) {
  5436. super();
  5437. /**
  5438. * This flag can be used for type testing.
  5439. *
  5440. * @type {boolean}
  5441. * @readonly
  5442. * @default true
  5443. */
  5444. this.isContextNode = true;
  5445. /**
  5446. * The node whose context should be modified.
  5447. *
  5448. * @type {Node}
  5449. */
  5450. this.node = node;
  5451. /**
  5452. * The modified context data.
  5453. *
  5454. * @type {Object}
  5455. * @default {}
  5456. */
  5457. this.value = value;
  5458. }
  5459. /**
  5460. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5461. *
  5462. * @return {Node} A reference to {@link ContextNode#node}.
  5463. */
  5464. getScope() {
  5465. return this.node.getScope();
  5466. }
  5467. /**
  5468. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5469. *
  5470. * @param {NodeBuilder} builder - The current node builder.
  5471. * @return {string} The node type.
  5472. */
  5473. getNodeType( builder ) {
  5474. return this.node.getNodeType( builder );
  5475. }
  5476. /**
  5477. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5478. *
  5479. * @param {NodeBuilder} builder - The current node builder.
  5480. * @param {string} name - The member name.
  5481. * @returns {string} The member type.
  5482. */
  5483. getMemberType( builder, name ) {
  5484. return this.node.getMemberType( builder, name );
  5485. }
  5486. analyze( builder ) {
  5487. const previousContext = builder.getContext();
  5488. builder.setContext( { ...builder.context, ...this.value } );
  5489. this.node.build( builder );
  5490. builder.setContext( previousContext );
  5491. }
  5492. setup( builder ) {
  5493. const previousContext = builder.getContext();
  5494. builder.setContext( { ...builder.context, ...this.value } );
  5495. this.node.build( builder );
  5496. builder.setContext( previousContext );
  5497. }
  5498. generate( builder, output ) {
  5499. const previousContext = builder.getContext();
  5500. builder.setContext( { ...builder.context, ...this.value } );
  5501. const snippet = this.node.build( builder, output );
  5502. builder.setContext( previousContext );
  5503. return snippet;
  5504. }
  5505. }
  5506. /**
  5507. * TSL function for creating a context node.
  5508. *
  5509. * @tsl
  5510. * @function
  5511. * @param {Node} node - The node whose context should be modified.
  5512. * @param {Object} [value={}] - The modified context data.
  5513. * @returns {ContextNode}
  5514. */
  5515. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5516. /**
  5517. * TSL function for defining a uniformFlow context value for a given node.
  5518. *
  5519. * @tsl
  5520. * @function
  5521. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5522. * @returns {ContextNode}
  5523. */
  5524. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5525. /**
  5526. * TSL function for defining a name for the context value for a given node.
  5527. *
  5528. * @tsl
  5529. * @function
  5530. * @param {Node} node - The node whose context should be modified.
  5531. * @param {string} name - The name to set.
  5532. * @returns {ContextNode}
  5533. */
  5534. const setName = ( node, name ) => context( node, { nodeName: name } );
  5535. /**
  5536. * TSL function for defining a label context value for a given node.
  5537. *
  5538. * @tsl
  5539. * @function
  5540. * @deprecated
  5541. * @param {Node} node - The node whose context should be modified.
  5542. * @param {string} name - The name/label to set.
  5543. * @returns {ContextNode}
  5544. */
  5545. function label( node, name ) {
  5546. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5547. return setName( node, name );
  5548. }
  5549. addMethodChaining( 'context', context );
  5550. addMethodChaining( 'label', label );
  5551. addMethodChaining( 'uniformFlow', uniformFlow );
  5552. addMethodChaining( 'setName', setName );
  5553. /**
  5554. * Class for representing shader variables as nodes. Variables are created from
  5555. * existing nodes like the following:
  5556. *
  5557. * ```js
  5558. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5559. * ```
  5560. *
  5561. * @augments Node
  5562. */
  5563. class VarNode extends Node {
  5564. static get type() {
  5565. return 'VarNode';
  5566. }
  5567. /**
  5568. * Constructs a new variable node.
  5569. *
  5570. * @param {Node} node - The node for which a variable should be created.
  5571. * @param {?string} [name=null] - The name of the variable in the shader.
  5572. * @param {boolean} [readOnly=false] - The read-only flag.
  5573. */
  5574. constructor( node, name = null, readOnly = false ) {
  5575. super();
  5576. /**
  5577. * The node for which a variable should be created.
  5578. *
  5579. * @type {Node}
  5580. */
  5581. this.node = node;
  5582. /**
  5583. * The name of the variable in the shader. If no name is defined,
  5584. * the node system auto-generates one.
  5585. *
  5586. * @type {?string}
  5587. * @default null
  5588. */
  5589. this.name = name;
  5590. /**
  5591. * `VarNode` sets this property to `true` by default.
  5592. *
  5593. * @type {boolean}
  5594. * @default true
  5595. */
  5596. this.global = true;
  5597. /**
  5598. * This flag can be used for type testing.
  5599. *
  5600. * @type {boolean}
  5601. * @readonly
  5602. * @default true
  5603. */
  5604. this.isVarNode = true;
  5605. /**
  5606. *
  5607. * The read-only flag.
  5608. *
  5609. * @type {boolean}
  5610. * @default false
  5611. */
  5612. this.readOnly = readOnly;
  5613. /**
  5614. *
  5615. * Add this flag to the node system to indicate that this node require parents.
  5616. *
  5617. * @type {boolean}
  5618. * @default true
  5619. */
  5620. this.parents = true;
  5621. /**
  5622. * This flag is used to indicate that this node is used for intent.
  5623. *
  5624. * @type {boolean}
  5625. * @default false
  5626. */
  5627. this.intent = false;
  5628. }
  5629. /**
  5630. * Sets the intent flag for this node.
  5631. *
  5632. * This flag is used to indicate that this node is used for intent
  5633. * and should not be built directly. Instead, it is used to indicate that
  5634. * the node should be treated as a variable intent.
  5635. *
  5636. * It's useful for assigning variables without needing creating a new variable node.
  5637. *
  5638. * @param {boolean} value - The value to set for the intent flag.
  5639. * @returns {VarNode} This node.
  5640. */
  5641. setIntent( value ) {
  5642. this.intent = value;
  5643. return this;
  5644. }
  5645. /**
  5646. * Returns the intent flag of this node.
  5647. *
  5648. * @return {boolean} The intent flag.
  5649. */
  5650. getIntent() {
  5651. return this.intent;
  5652. }
  5653. getMemberType( builder, name ) {
  5654. return this.node.getMemberType( builder, name );
  5655. }
  5656. getElementType( builder ) {
  5657. return this.node.getElementType( builder );
  5658. }
  5659. getNodeType( builder ) {
  5660. return this.node.getNodeType( builder );
  5661. }
  5662. getArrayCount( builder ) {
  5663. return this.node.getArrayCount( builder );
  5664. }
  5665. build( ...params ) {
  5666. if ( this.intent === true ) {
  5667. const builder = params[ 0 ];
  5668. const properties = builder.getNodeProperties( this );
  5669. if ( properties.assign !== true ) {
  5670. return this.node.build( ...params );
  5671. }
  5672. }
  5673. return super.build( ...params );
  5674. }
  5675. generate( builder ) {
  5676. const { node, name, readOnly } = this;
  5677. const { renderer } = builder;
  5678. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5679. let isDeterministic = false;
  5680. let shouldTreatAsReadOnly = false;
  5681. if ( readOnly ) {
  5682. isDeterministic = builder.isDeterministic( node );
  5683. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5684. }
  5685. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5686. const snippet = node.build( builder, vectorType );
  5687. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5688. const propertyName = builder.getPropertyName( nodeVar );
  5689. let declarationPrefix = propertyName;
  5690. if ( shouldTreatAsReadOnly ) {
  5691. if ( isWebGPUBackend ) {
  5692. declarationPrefix = isDeterministic
  5693. ? `const ${ propertyName }`
  5694. : `let ${ propertyName }`;
  5695. } else {
  5696. const count = node.getArrayCount( builder );
  5697. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5698. }
  5699. }
  5700. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5701. return propertyName;
  5702. }
  5703. }
  5704. /**
  5705. * TSL function for creating a var node.
  5706. *
  5707. * @tsl
  5708. * @function
  5709. * @param {Node} node - The node for which a variable should be created.
  5710. * @param {?string} name - The name of the variable in the shader.
  5711. * @returns {VarNode}
  5712. */
  5713. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5714. /**
  5715. * TSL function for creating a var node.
  5716. *
  5717. * @tsl
  5718. * @function
  5719. * @param {Node} node - The node for which a variable should be created.
  5720. * @param {?string} name - The name of the variable in the shader.
  5721. * @returns {VarNode}
  5722. */
  5723. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5724. /**
  5725. * TSL function for creating a const node.
  5726. *
  5727. * @tsl
  5728. * @function
  5729. * @param {Node} node - The node for which a constant should be created.
  5730. * @param {?string} name - The name of the constant in the shader.
  5731. * @returns {VarNode}
  5732. */
  5733. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5734. //
  5735. //
  5736. /**
  5737. * TSL function for creating a var intent node.
  5738. *
  5739. * @tsl
  5740. * @function
  5741. * @param {Node} node - The node for which a variable should be created.
  5742. * @param {?string} name - The name of the variable in the shader.
  5743. * @returns {VarNode}
  5744. */
  5745. const VarIntent = ( node ) => {
  5746. if ( getCurrentStack() === null ) {
  5747. return node;
  5748. }
  5749. return createVar( node ).setIntent( true ).toStack();
  5750. };
  5751. // Method chaining
  5752. addMethodChaining( 'toVar', Var );
  5753. addMethodChaining( 'toConst', Const );
  5754. addMethodChaining( 'toVarIntent', VarIntent );
  5755. /**
  5756. * This node is used to build a sub-build in the node system.
  5757. *
  5758. * @augments Node
  5759. * @param {Node} node - The node to be built in the sub-build.
  5760. * @param {string} name - The name of the sub-build.
  5761. * @param {?string} [nodeType=null] - The type of the node, if known.
  5762. */
  5763. class SubBuildNode extends Node {
  5764. static get type() {
  5765. return 'SubBuild';
  5766. }
  5767. constructor( node, name, nodeType = null ) {
  5768. super( nodeType );
  5769. /**
  5770. * The node to be built in the sub-build.
  5771. *
  5772. * @type {Node}
  5773. */
  5774. this.node = node;
  5775. /**
  5776. * The name of the sub-build.
  5777. *
  5778. * @type {string}
  5779. */
  5780. this.name = name;
  5781. /**
  5782. * This flag can be used for type testing.
  5783. *
  5784. * @type {boolean}
  5785. * @readonly
  5786. * @default true
  5787. */
  5788. this.isSubBuildNode = true;
  5789. }
  5790. getNodeType( builder ) {
  5791. if ( this.nodeType !== null ) return this.nodeType;
  5792. builder.addSubBuild( this.name );
  5793. const nodeType = this.node.getNodeType( builder );
  5794. builder.removeSubBuild();
  5795. return nodeType;
  5796. }
  5797. build( builder, ...params ) {
  5798. builder.addSubBuild( this.name );
  5799. const data = this.node.build( builder, ...params );
  5800. builder.removeSubBuild();
  5801. return data;
  5802. }
  5803. }
  5804. /**
  5805. * Creates a new sub-build node.
  5806. *
  5807. * @tsl
  5808. * @function
  5809. * @param {Node} node - The node to be built in the sub-build.
  5810. * @param {string} name - The name of the sub-build.
  5811. * @param {?string} [type=null] - The type of the node, if known.
  5812. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5813. */
  5814. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5815. /**
  5816. * Class for representing shader varyings as nodes. Varyings are create from
  5817. * existing nodes like the following:
  5818. *
  5819. * ```js
  5820. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5821. * ```
  5822. *
  5823. * @augments Node
  5824. */
  5825. class VaryingNode extends Node {
  5826. static get type() {
  5827. return 'VaryingNode';
  5828. }
  5829. /**
  5830. * Constructs a new varying node.
  5831. *
  5832. * @param {Node} node - The node for which a varying should be created.
  5833. * @param {?string} name - The name of the varying in the shader.
  5834. */
  5835. constructor( node, name = null ) {
  5836. super();
  5837. /**
  5838. * The node for which a varying should be created.
  5839. *
  5840. * @type {Node}
  5841. */
  5842. this.node = node;
  5843. /**
  5844. * The name of the varying in the shader. If no name is defined,
  5845. * the node system auto-generates one.
  5846. *
  5847. * @type {?string}
  5848. * @default null
  5849. */
  5850. this.name = name;
  5851. /**
  5852. * This flag can be used for type testing.
  5853. *
  5854. * @type {boolean}
  5855. * @readonly
  5856. * @default true
  5857. */
  5858. this.isVaryingNode = true;
  5859. /**
  5860. * The interpolation type of the varying data.
  5861. *
  5862. * @type {?string}
  5863. * @default null
  5864. */
  5865. this.interpolationType = null;
  5866. /**
  5867. * The interpolation sampling type of varying data.
  5868. *
  5869. * @type {?string}
  5870. * @default null
  5871. */
  5872. this.interpolationSampling = null;
  5873. /**
  5874. * This flag is used for global cache.
  5875. *
  5876. * @type {boolean}
  5877. * @default true
  5878. */
  5879. this.global = true;
  5880. }
  5881. /**
  5882. * Defines the interpolation type of the varying.
  5883. *
  5884. * @param {string} type - The interpolation type.
  5885. * @param {?string} sampling - The interpolation sampling type
  5886. * @return {VaryingNode} A reference to this node.
  5887. */
  5888. setInterpolation( type, sampling = null ) {
  5889. this.interpolationType = type;
  5890. this.interpolationSampling = sampling;
  5891. return this;
  5892. }
  5893. getHash( builder ) {
  5894. return this.name || super.getHash( builder );
  5895. }
  5896. getNodeType( builder ) {
  5897. // VaryingNode is auto type
  5898. return this.node.getNodeType( builder );
  5899. }
  5900. /**
  5901. * This method performs the setup of a varying node with the current node builder.
  5902. *
  5903. * @param {NodeBuilder} builder - The current node builder.
  5904. * @return {NodeVarying} The node varying from the node builder.
  5905. */
  5906. setupVarying( builder ) {
  5907. const properties = builder.getNodeProperties( this );
  5908. let varying = properties.varying;
  5909. if ( varying === undefined ) {
  5910. const name = this.name;
  5911. const type = this.getNodeType( builder );
  5912. const interpolationType = this.interpolationType;
  5913. const interpolationSampling = this.interpolationSampling;
  5914. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5915. properties.node = subBuild( this.node, 'VERTEX' );
  5916. }
  5917. // this property can be used to check if the varying can be optimized for a variable
  5918. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5919. return varying;
  5920. }
  5921. setup( builder ) {
  5922. this.setupVarying( builder );
  5923. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5924. }
  5925. analyze( builder ) {
  5926. this.setupVarying( builder );
  5927. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5928. }
  5929. generate( builder ) {
  5930. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5931. const properties = builder.getNodeProperties( this );
  5932. const varying = this.setupVarying( builder );
  5933. if ( properties[ propertyKey ] === undefined ) {
  5934. const type = this.getNodeType( builder );
  5935. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5936. // force node run in vertex stage
  5937. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5938. properties[ propertyKey ] = propertyName;
  5939. }
  5940. return builder.getPropertyName( varying );
  5941. }
  5942. }
  5943. /**
  5944. * TSL function for creating a varying node.
  5945. *
  5946. * @tsl
  5947. * @function
  5948. * @param {Node} node - The node for which a varying should be created.
  5949. * @param {?string} name - The name of the varying in the shader.
  5950. * @returns {VaryingNode}
  5951. */
  5952. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5953. /**
  5954. * Computes a node in the vertex stage.
  5955. *
  5956. * @tsl
  5957. * @function
  5958. * @param {Node} node - The node which should be executed in the vertex stage.
  5959. * @returns {VaryingNode}
  5960. */
  5961. const vertexStage = ( node ) => varying( node );
  5962. addMethodChaining( 'toVarying', varying );
  5963. addMethodChaining( 'toVertexStage', vertexStage );
  5964. // Deprecated
  5965. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5966. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  5967. return varying( ...params );
  5968. } );
  5969. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5970. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5971. return varying( ...params );
  5972. } );
  5973. /**
  5974. * Converts the given color value from sRGB to linear-sRGB color space.
  5975. *
  5976. * @tsl
  5977. * @function
  5978. * @param {Node<vec3>} color - The sRGB color.
  5979. * @return {Node<vec3>} The linear-sRGB color.
  5980. */
  5981. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5982. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5983. const b = color.mul( 0.0773993808 );
  5984. const factor = color.lessThanEqual( 0.04045 );
  5985. const rgbResult = mix( a, b, factor );
  5986. return rgbResult;
  5987. } ).setLayout( {
  5988. name: 'sRGBTransferEOTF',
  5989. type: 'vec3',
  5990. inputs: [
  5991. { name: 'color', type: 'vec3' }
  5992. ]
  5993. } );
  5994. /**
  5995. * Converts the given color value from linear-sRGB to sRGB color space.
  5996. *
  5997. * @tsl
  5998. * @function
  5999. * @param {Node<vec3>} color - The linear-sRGB color.
  6000. * @return {Node<vec3>} The sRGB color.
  6001. */
  6002. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  6003. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  6004. const b = color.mul( 12.92 );
  6005. const factor = color.lessThanEqual( 0.0031308 );
  6006. const rgbResult = mix( a, b, factor );
  6007. return rgbResult;
  6008. } ).setLayout( {
  6009. name: 'sRGBTransferOETF',
  6010. type: 'vec3',
  6011. inputs: [
  6012. { name: 'color', type: 'vec3' }
  6013. ]
  6014. } );
  6015. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  6016. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  6017. /**
  6018. * This node represents a color space conversion. Meaning it converts
  6019. * a color value from a source to a target color space.
  6020. *
  6021. * @augments TempNode
  6022. */
  6023. class ColorSpaceNode extends TempNode {
  6024. static get type() {
  6025. return 'ColorSpaceNode';
  6026. }
  6027. /**
  6028. * Constructs a new color space node.
  6029. *
  6030. * @param {Node} colorNode - Represents the color to convert.
  6031. * @param {string} source - The source color space.
  6032. * @param {string} target - The target color space.
  6033. */
  6034. constructor( colorNode, source, target ) {
  6035. super( 'vec4' );
  6036. /**
  6037. * Represents the color to convert.
  6038. *
  6039. * @type {Node}
  6040. */
  6041. this.colorNode = colorNode;
  6042. /**
  6043. * The source color space.
  6044. *
  6045. * @type {string}
  6046. */
  6047. this.source = source;
  6048. /**
  6049. * The target color space.
  6050. *
  6051. * @type {string}
  6052. */
  6053. this.target = target;
  6054. }
  6055. /**
  6056. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6057. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6058. * color management and renderer.
  6059. *
  6060. * @param {NodeBuilder} builder - The current node builder.
  6061. * @param {string} colorSpace - The color space to resolve.
  6062. * @return {string} The resolved color space.
  6063. */
  6064. resolveColorSpace( builder, colorSpace ) {
  6065. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6066. return ColorManagement.workingColorSpace;
  6067. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6068. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6069. }
  6070. return colorSpace;
  6071. }
  6072. setup( builder ) {
  6073. const { colorNode } = this;
  6074. const source = this.resolveColorSpace( builder, this.source );
  6075. const target = this.resolveColorSpace( builder, this.target );
  6076. let outputNode = colorNode;
  6077. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6078. return outputNode;
  6079. }
  6080. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6081. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6082. }
  6083. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6084. outputNode = vec4(
  6085. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6086. outputNode.a
  6087. );
  6088. }
  6089. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6090. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6091. }
  6092. return outputNode;
  6093. }
  6094. }
  6095. /**
  6096. * TSL function for converting a given color node from the current working color space to the given color space.
  6097. *
  6098. * @tsl
  6099. * @function
  6100. * @param {Node} node - Represents the node to convert.
  6101. * @param {string} targetColorSpace - The target color space.
  6102. * @returns {ColorSpaceNode}
  6103. */
  6104. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6105. /**
  6106. * TSL function for converting a given color node from the given color space to the current working color space.
  6107. *
  6108. * @tsl
  6109. * @function
  6110. * @param {Node} node - Represents the node to convert.
  6111. * @param {string} sourceColorSpace - The source color space.
  6112. * @returns {ColorSpaceNode}
  6113. */
  6114. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6115. /**
  6116. * TSL function for converting a given color node from one color space to another one.
  6117. *
  6118. * @tsl
  6119. * @function
  6120. * @param {Node} node - Represents the node to convert.
  6121. * @param {string} sourceColorSpace - The source color space.
  6122. * @param {string} targetColorSpace - The target color space.
  6123. * @returns {ColorSpaceNode}
  6124. */
  6125. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6126. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6127. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6128. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6129. /**
  6130. * This class is only relevant if the referenced property is array-like.
  6131. * In this case, `ReferenceElementNode` allows to refer to a specific
  6132. * element inside the data structure via an index.
  6133. *
  6134. * @augments ArrayElementNode
  6135. */
  6136. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6137. static get type() {
  6138. return 'ReferenceElementNode';
  6139. }
  6140. /**
  6141. * Constructs a new reference element node.
  6142. *
  6143. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6144. * @param {Node} indexNode - The index node that defines the element access.
  6145. */
  6146. constructor( referenceNode, indexNode ) {
  6147. super( referenceNode, indexNode );
  6148. /**
  6149. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6150. * property references to the current node.
  6151. *
  6152. * @type {?ReferenceBaseNode}
  6153. * @default null
  6154. */
  6155. this.referenceNode = referenceNode;
  6156. /**
  6157. * This flag can be used for type testing.
  6158. *
  6159. * @type {boolean}
  6160. * @readonly
  6161. * @default true
  6162. */
  6163. this.isReferenceElementNode = true;
  6164. }
  6165. /**
  6166. * This method is overwritten since the node type is inferred from
  6167. * the uniform type of the reference node.
  6168. *
  6169. * @return {string} The node type.
  6170. */
  6171. getNodeType() {
  6172. return this.referenceNode.uniformType;
  6173. }
  6174. generate( builder ) {
  6175. const snippet = super.generate( builder );
  6176. const arrayType = this.referenceNode.getNodeType();
  6177. const elementType = this.getNodeType();
  6178. return builder.format( snippet, arrayType, elementType );
  6179. }
  6180. };
  6181. /**
  6182. * Base class for nodes which establishes a reference to a property of another object.
  6183. * In this way, the value of the node is automatically linked to the value of
  6184. * referenced object. Reference nodes internally represent the linked value
  6185. * as a uniform.
  6186. *
  6187. * @augments Node
  6188. */
  6189. class ReferenceBaseNode extends Node {
  6190. static get type() {
  6191. return 'ReferenceBaseNode';
  6192. }
  6193. /**
  6194. * Constructs a new reference base node.
  6195. *
  6196. * @param {string} property - The name of the property the node refers to.
  6197. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6198. * @param {?Object} [object=null] - The object the property belongs to.
  6199. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6200. */
  6201. constructor( property, uniformType, object = null, count = null ) {
  6202. super();
  6203. /**
  6204. * The name of the property the node refers to.
  6205. *
  6206. * @type {string}
  6207. */
  6208. this.property = property;
  6209. /**
  6210. * The uniform type that should be used to represent the property value.
  6211. *
  6212. * @type {string}
  6213. */
  6214. this.uniformType = uniformType;
  6215. /**
  6216. * The object the property belongs to.
  6217. *
  6218. * @type {?Object}
  6219. * @default null
  6220. */
  6221. this.object = object;
  6222. /**
  6223. * When the linked property is an array, this parameter defines its length.
  6224. *
  6225. * @type {?number}
  6226. * @default null
  6227. */
  6228. this.count = count;
  6229. /**
  6230. * The property name might have dots so nested properties can be referred.
  6231. * The hierarchy of the names is stored inside this array.
  6232. *
  6233. * @type {Array<string>}
  6234. */
  6235. this.properties = property.split( '.' );
  6236. /**
  6237. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6238. * since the final reference might be updated from calling code.
  6239. *
  6240. * @type {?Object}
  6241. * @default null
  6242. */
  6243. this.reference = object;
  6244. /**
  6245. * The uniform node that holds the value of the reference node.
  6246. *
  6247. * @type {UniformNode}
  6248. * @default null
  6249. */
  6250. this.node = null;
  6251. /**
  6252. * The uniform group of the internal uniform.
  6253. *
  6254. * @type {UniformGroupNode}
  6255. * @default null
  6256. */
  6257. this.group = null;
  6258. /**
  6259. * Overwritten since reference nodes are updated per object.
  6260. *
  6261. * @type {string}
  6262. * @default 'object'
  6263. */
  6264. this.updateType = NodeUpdateType.OBJECT;
  6265. }
  6266. /**
  6267. * Sets the uniform group for this reference node.
  6268. *
  6269. * @param {UniformGroupNode} group - The uniform group to set.
  6270. * @return {ReferenceBaseNode} A reference to this node.
  6271. */
  6272. setGroup( group ) {
  6273. this.group = group;
  6274. return this;
  6275. }
  6276. /**
  6277. * When the referred property is array-like, this method can be used
  6278. * to access elements via an index node.
  6279. *
  6280. * @param {IndexNode} indexNode - indexNode.
  6281. * @return {ReferenceElementNode} A reference to an element.
  6282. */
  6283. element( indexNode ) {
  6284. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6285. }
  6286. /**
  6287. * Sets the node type which automatically defines the internal
  6288. * uniform type.
  6289. *
  6290. * @param {string} uniformType - The type to set.
  6291. */
  6292. setNodeType( uniformType ) {
  6293. const node = uniform( null, uniformType );
  6294. if ( this.group !== null ) {
  6295. node.setGroup( this.group );
  6296. }
  6297. this.node = node;
  6298. }
  6299. /**
  6300. * This method is overwritten since the node type is inferred from
  6301. * the type of the reference node.
  6302. *
  6303. * @param {NodeBuilder} builder - The current node builder.
  6304. * @return {string} The node type.
  6305. */
  6306. getNodeType( builder ) {
  6307. if ( this.node === null ) {
  6308. this.updateReference( builder );
  6309. this.updateValue();
  6310. }
  6311. return this.node.getNodeType( builder );
  6312. }
  6313. /**
  6314. * Returns the property value from the given referred object.
  6315. *
  6316. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6317. * @return {any} The value.
  6318. */
  6319. getValueFromReference( object = this.reference ) {
  6320. const { properties } = this;
  6321. let value = object[ properties[ 0 ] ];
  6322. for ( let i = 1; i < properties.length; i ++ ) {
  6323. value = value[ properties[ i ] ];
  6324. }
  6325. return value;
  6326. }
  6327. /**
  6328. * Allows to update the reference based on the given state. The state is only
  6329. * evaluated {@link ReferenceBaseNode#object} is not set.
  6330. *
  6331. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6332. * @return {Object} The updated reference.
  6333. */
  6334. updateReference( state ) {
  6335. this.reference = this.object !== null ? this.object : state.object;
  6336. return this.reference;
  6337. }
  6338. /**
  6339. * The output of the reference node is the internal uniform node.
  6340. *
  6341. * @return {UniformNode} The output node.
  6342. */
  6343. setup() {
  6344. this.updateValue();
  6345. return this.node;
  6346. }
  6347. /**
  6348. * Overwritten to update the internal uniform value.
  6349. *
  6350. * @param {NodeFrame} frame - A reference to the current node frame.
  6351. */
  6352. update( /*frame*/ ) {
  6353. this.updateValue();
  6354. }
  6355. /**
  6356. * Retrieves the value from the referred object property and uses it
  6357. * to updated the internal uniform.
  6358. */
  6359. updateValue() {
  6360. if ( this.node === null ) this.setNodeType( this.uniformType );
  6361. const value = this.getValueFromReference();
  6362. if ( Array.isArray( value ) ) {
  6363. this.node.array = value;
  6364. } else {
  6365. this.node.value = value;
  6366. }
  6367. }
  6368. }
  6369. /**
  6370. * TSL function for creating a reference base node.
  6371. *
  6372. * @tsl
  6373. * @function
  6374. * @param {string} name - The name of the property the node refers to.
  6375. * @param {string} type - The uniform type that should be used to represent the property value.
  6376. * @param {Object} object - The object the property belongs to.
  6377. * @returns {ReferenceBaseNode}
  6378. */
  6379. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6380. /**
  6381. * This node is a special type of reference node which is intended
  6382. * for linking renderer properties with node values.
  6383. * ```js
  6384. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6385. * ```
  6386. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6387. * automatically be updated.
  6388. *
  6389. * @augments ReferenceBaseNode
  6390. */
  6391. class RendererReferenceNode extends ReferenceBaseNode {
  6392. static get type() {
  6393. return 'RendererReferenceNode';
  6394. }
  6395. /**
  6396. * Constructs a new renderer reference node.
  6397. *
  6398. * @param {string} property - The name of the property the node refers to.
  6399. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6400. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6401. * the node refers to the renderer of the current state.
  6402. */
  6403. constructor( property, inputType, renderer = null ) {
  6404. super( property, inputType, renderer );
  6405. /**
  6406. * The renderer the property belongs to. When no renderer is set,
  6407. * the node refers to the renderer of the current state.
  6408. *
  6409. * @type {?Renderer}
  6410. * @default null
  6411. */
  6412. this.renderer = renderer;
  6413. this.setGroup( renderGroup );
  6414. }
  6415. /**
  6416. * Updates the reference based on the given state. The state is only evaluated
  6417. * {@link RendererReferenceNode#renderer} is not set.
  6418. *
  6419. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6420. * @return {Object} The updated reference.
  6421. */
  6422. updateReference( state ) {
  6423. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6424. return this.reference;
  6425. }
  6426. }
  6427. /**
  6428. * TSL function for creating a renderer reference node.
  6429. *
  6430. * @tsl
  6431. * @function
  6432. * @param {string} name - The name of the property the node refers to.
  6433. * @param {string} type - The uniform type that should be used to represent the property value.
  6434. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6435. * the node refers to the renderer of the current state.
  6436. * @returns {RendererReferenceNode}
  6437. */
  6438. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6439. /**
  6440. * This node represents a tone mapping operation.
  6441. *
  6442. * @augments TempNode
  6443. */
  6444. class ToneMappingNode extends TempNode {
  6445. static get type() {
  6446. return 'ToneMappingNode';
  6447. }
  6448. /**
  6449. * Constructs a new tone mapping node.
  6450. *
  6451. * @param {number} toneMapping - The tone mapping type.
  6452. * @param {Node} exposureNode - The tone mapping exposure.
  6453. * @param {Node} [colorNode=null] - The color node to process.
  6454. */
  6455. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6456. super( 'vec3' );
  6457. /**
  6458. * The tone mapping type.
  6459. *
  6460. * @type {number}
  6461. */
  6462. this.toneMapping = toneMapping;
  6463. /**
  6464. * The tone mapping exposure.
  6465. *
  6466. * @type {Node}
  6467. * @default null
  6468. */
  6469. this.exposureNode = exposureNode;
  6470. /**
  6471. * Represents the color to process.
  6472. *
  6473. * @type {?Node}
  6474. * @default null
  6475. */
  6476. this.colorNode = colorNode;
  6477. }
  6478. /**
  6479. * Overwrites the default `customCacheKey()` implementation by including the tone
  6480. * mapping type into the cache key.
  6481. *
  6482. * @return {number} The hash.
  6483. */
  6484. customCacheKey() {
  6485. return hash$1( this.toneMapping );
  6486. }
  6487. setup( builder ) {
  6488. const colorNode = this.colorNode || builder.context.color;
  6489. const toneMapping = this.toneMapping;
  6490. if ( toneMapping === NoToneMapping ) return colorNode;
  6491. let outputNode = null;
  6492. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6493. if ( toneMappingFn !== null ) {
  6494. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6495. } else {
  6496. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6497. outputNode = colorNode;
  6498. }
  6499. return outputNode;
  6500. }
  6501. }
  6502. /**
  6503. * TSL function for creating a tone mapping node.
  6504. *
  6505. * @tsl
  6506. * @function
  6507. * @param {number} mapping - The tone mapping type.
  6508. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6509. * @param {Node<vec3> | Color} color - The color node to process.
  6510. * @returns {ToneMappingNode<vec3>}
  6511. */
  6512. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6513. /**
  6514. * TSL object that represents the global tone mapping exposure of the renderer.
  6515. *
  6516. * @tsl
  6517. * @type {RendererReferenceNode<vec3>}
  6518. */
  6519. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6520. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6521. /**
  6522. * In earlier `three.js` versions it was only possible to define attribute data
  6523. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6524. * on the node level.
  6525. * ```js
  6526. * const geometry = new THREE.PlaneGeometry();
  6527. * const positionAttribute = geometry.getAttribute( 'position' );
  6528. *
  6529. * const colors = [];
  6530. * for ( let i = 0; i < position.count; i ++ ) {
  6531. * colors.push( 1, 0, 0 );
  6532. * }
  6533. *
  6534. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6535. * ```
  6536. * This new approach is especially interesting when geometry data are generated via
  6537. * compute shaders. The below line converts a storage buffer into an attribute node.
  6538. * ```js
  6539. * material.positionNode = positionBuffer.toAttribute();
  6540. * ```
  6541. * @augments InputNode
  6542. */
  6543. class BufferAttributeNode extends InputNode {
  6544. static get type() {
  6545. return 'BufferAttributeNode';
  6546. }
  6547. /**
  6548. * Constructs a new buffer attribute node.
  6549. *
  6550. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6551. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6552. * @param {number} [bufferStride=0] - The buffer stride.
  6553. * @param {number} [bufferOffset=0] - The buffer offset.
  6554. */
  6555. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6556. super( value, bufferType );
  6557. /**
  6558. * This flag can be used for type testing.
  6559. *
  6560. * @type {boolean}
  6561. * @readonly
  6562. * @default true
  6563. */
  6564. this.isBufferNode = true;
  6565. /**
  6566. * The buffer type (e.g. `'vec3'`).
  6567. *
  6568. * @type {?string}
  6569. * @default null
  6570. */
  6571. this.bufferType = bufferType;
  6572. /**
  6573. * The buffer stride.
  6574. *
  6575. * @type {number}
  6576. * @default 0
  6577. */
  6578. this.bufferStride = bufferStride;
  6579. /**
  6580. * The buffer offset.
  6581. *
  6582. * @type {number}
  6583. * @default 0
  6584. */
  6585. this.bufferOffset = bufferOffset;
  6586. /**
  6587. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6588. * if you are planning to update the attribute data per frame.
  6589. *
  6590. * @type {number}
  6591. * @default StaticDrawUsage
  6592. */
  6593. this.usage = StaticDrawUsage;
  6594. /**
  6595. * Whether the attribute is instanced or not.
  6596. *
  6597. * @type {boolean}
  6598. * @default false
  6599. */
  6600. this.instanced = false;
  6601. /**
  6602. * A reference to the buffer attribute.
  6603. *
  6604. * @type {?BufferAttribute}
  6605. * @default null
  6606. */
  6607. this.attribute = null;
  6608. /**
  6609. * `BufferAttributeNode` sets this property to `true` by default.
  6610. *
  6611. * @type {boolean}
  6612. * @default true
  6613. */
  6614. this.global = true;
  6615. if ( value && value.isBufferAttribute === true ) {
  6616. this.attribute = value;
  6617. this.usage = value.usage;
  6618. this.instanced = value.isInstancedBufferAttribute;
  6619. }
  6620. }
  6621. /**
  6622. * This method is overwritten since the attribute data might be shared
  6623. * and thus the hash should be shared as well.
  6624. *
  6625. * @param {NodeBuilder} builder - The current node builder.
  6626. * @return {string} The hash.
  6627. */
  6628. getHash( builder ) {
  6629. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6630. let bufferData = builder.globalCache.getData( this.value );
  6631. if ( bufferData === undefined ) {
  6632. bufferData = {
  6633. node: this
  6634. };
  6635. builder.globalCache.setData( this.value, bufferData );
  6636. }
  6637. return bufferData.node.uuid;
  6638. }
  6639. return this.uuid;
  6640. }
  6641. /**
  6642. * This method is overwritten since the node type is inferred from
  6643. * the buffer attribute.
  6644. *
  6645. * @param {NodeBuilder} builder - The current node builder.
  6646. * @return {string} The node type.
  6647. */
  6648. getNodeType( builder ) {
  6649. if ( this.bufferType === null ) {
  6650. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6651. }
  6652. return this.bufferType;
  6653. }
  6654. /**
  6655. * Depending on which value was passed to the node, `setup()` behaves
  6656. * differently. If no instance of `BufferAttribute` was passed, the method
  6657. * creates an internal attribute and configures it respectively.
  6658. *
  6659. * @param {NodeBuilder} builder - The current node builder.
  6660. */
  6661. setup( builder ) {
  6662. if ( this.attribute !== null ) return;
  6663. const type = this.getNodeType( builder );
  6664. const array = this.value;
  6665. const itemSize = builder.getTypeLength( type );
  6666. const stride = this.bufferStride || itemSize;
  6667. const offset = this.bufferOffset;
  6668. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6669. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6670. buffer.setUsage( this.usage );
  6671. this.attribute = bufferAttribute;
  6672. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6673. }
  6674. /**
  6675. * Generates the code snippet of the buffer attribute node.
  6676. *
  6677. * @param {NodeBuilder} builder - The current node builder.
  6678. * @return {string} The generated code snippet.
  6679. */
  6680. generate( builder ) {
  6681. const nodeType = this.getNodeType( builder );
  6682. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6683. const propertyName = builder.getPropertyName( nodeAttribute );
  6684. let output = null;
  6685. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6686. this.name = propertyName;
  6687. output = propertyName;
  6688. } else {
  6689. const nodeVarying = varying( this );
  6690. output = nodeVarying.build( builder, nodeType );
  6691. }
  6692. return output;
  6693. }
  6694. /**
  6695. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6696. *
  6697. * @param {NodeBuilder} builder - The current node builder.
  6698. * @return {string} The input type.
  6699. */
  6700. getInputType( /*builder*/ ) {
  6701. return 'bufferAttribute';
  6702. }
  6703. /**
  6704. * Sets the `usage` property to the given value.
  6705. *
  6706. * @param {number} value - The usage to set.
  6707. * @return {BufferAttributeNode} A reference to this node.
  6708. */
  6709. setUsage( value ) {
  6710. this.usage = value;
  6711. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6712. this.attribute.usage = value;
  6713. }
  6714. return this;
  6715. }
  6716. /**
  6717. * Sets the `instanced` property to the given value.
  6718. *
  6719. * @param {boolean} value - The value to set.
  6720. * @return {BufferAttributeNode} A reference to this node.
  6721. */
  6722. setInstanced( value ) {
  6723. this.instanced = value;
  6724. return this;
  6725. }
  6726. }
  6727. /**
  6728. * TSL function for creating a buffer attribute node.
  6729. *
  6730. * @tsl
  6731. * @function
  6732. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6733. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6734. * @param {number} [stride=0] - The buffer stride.
  6735. * @param {number} [offset=0] - The buffer offset.
  6736. * @returns {BufferAttributeNode}
  6737. */
  6738. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6739. /**
  6740. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6741. * Use this function if attribute data are updated per frame.
  6742. *
  6743. * @tsl
  6744. * @function
  6745. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6746. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6747. * @param {number} [stride=0] - The buffer stride.
  6748. * @param {number} [offset=0] - The buffer offset.
  6749. * @returns {BufferAttributeNode}
  6750. */
  6751. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6752. /**
  6753. * TSL function for creating a buffer attribute node but with enabled instancing
  6754. *
  6755. * @tsl
  6756. * @function
  6757. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6758. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6759. * @param {number} [stride=0] - The buffer stride.
  6760. * @param {number} [offset=0] - The buffer offset.
  6761. * @returns {BufferAttributeNode}
  6762. */
  6763. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6764. /**
  6765. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6766. *
  6767. * @tsl
  6768. * @function
  6769. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6770. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6771. * @param {number} [stride=0] - The buffer stride.
  6772. * @param {number} [offset=0] - The buffer offset.
  6773. * @returns {BufferAttributeNode}
  6774. */
  6775. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6776. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6777. /**
  6778. * TODO
  6779. *
  6780. * @augments Node
  6781. */
  6782. class ComputeNode extends Node {
  6783. static get type() {
  6784. return 'ComputeNode';
  6785. }
  6786. /**
  6787. * Constructs a new compute node.
  6788. *
  6789. * @param {Node} computeNode - TODO
  6790. * @param {Array<number>} workgroupSize - TODO.
  6791. */
  6792. constructor( computeNode, workgroupSize ) {
  6793. super( 'void' );
  6794. /**
  6795. * This flag can be used for type testing.
  6796. *
  6797. * @type {boolean}
  6798. * @readonly
  6799. * @default true
  6800. */
  6801. this.isComputeNode = true;
  6802. /**
  6803. * TODO
  6804. *
  6805. * @type {Node}
  6806. */
  6807. this.computeNode = computeNode;
  6808. /**
  6809. * TODO
  6810. *
  6811. * @type {Array<number>}
  6812. * @default [ 64 ]
  6813. */
  6814. this.workgroupSize = workgroupSize;
  6815. /**
  6816. * TODO
  6817. *
  6818. * @type {number}
  6819. */
  6820. this.count = null;
  6821. /**
  6822. * TODO
  6823. *
  6824. * @type {number}
  6825. */
  6826. this.version = 1;
  6827. /**
  6828. * The name or label of the uniform.
  6829. *
  6830. * @type {string}
  6831. * @default ''
  6832. */
  6833. this.name = '';
  6834. /**
  6835. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6836. * is executed once per object by default.
  6837. *
  6838. * @type {string}
  6839. * @default 'object'
  6840. */
  6841. this.updateBeforeType = NodeUpdateType.OBJECT;
  6842. /**
  6843. * TODO
  6844. *
  6845. * @type {?Function}
  6846. */
  6847. this.onInitFunction = null;
  6848. }
  6849. setCount( count ) {
  6850. this.count = count;
  6851. return this;
  6852. }
  6853. getCount() {
  6854. return this.count;
  6855. }
  6856. /**
  6857. * Executes the `dispose` event for this node.
  6858. */
  6859. dispose() {
  6860. this.dispatchEvent( { type: 'dispose' } );
  6861. }
  6862. /**
  6863. * Sets the {@link ComputeNode#name} property.
  6864. *
  6865. * @param {string} name - The name of the uniform.
  6866. * @return {ComputeNode} A reference to this node.
  6867. */
  6868. setName( name ) {
  6869. this.name = name;
  6870. return this;
  6871. }
  6872. /**
  6873. * Sets the {@link ComputeNode#name} property.
  6874. *
  6875. * @deprecated
  6876. * @param {string} name - The name of the uniform.
  6877. * @return {ComputeNode} A reference to this node.
  6878. */
  6879. label( name ) {
  6880. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6881. return this.setName( name );
  6882. }
  6883. /**
  6884. * TODO
  6885. *
  6886. * @param {Function} callback - TODO.
  6887. * @return {ComputeNode} A reference to this node.
  6888. */
  6889. onInit( callback ) {
  6890. this.onInitFunction = callback;
  6891. return this;
  6892. }
  6893. /**
  6894. * The method execute the compute for this node.
  6895. *
  6896. * @param {NodeFrame} frame - A reference to the current node frame.
  6897. */
  6898. updateBefore( { renderer } ) {
  6899. renderer.compute( this );
  6900. }
  6901. setup( builder ) {
  6902. const result = this.computeNode.build( builder );
  6903. if ( result ) {
  6904. const properties = builder.getNodeProperties( this );
  6905. properties.outputComputeNode = result.outputNode;
  6906. result.outputNode = null;
  6907. }
  6908. return result;
  6909. }
  6910. generate( builder, output ) {
  6911. const { shaderStage } = builder;
  6912. if ( shaderStage === 'compute' ) {
  6913. const snippet = this.computeNode.build( builder, 'void' );
  6914. if ( snippet !== '' ) {
  6915. builder.addLineFlowCode( snippet, this );
  6916. }
  6917. } else {
  6918. const properties = builder.getNodeProperties( this );
  6919. const outputComputeNode = properties.outputComputeNode;
  6920. if ( outputComputeNode ) {
  6921. return outputComputeNode.build( builder, output );
  6922. }
  6923. }
  6924. }
  6925. }
  6926. /**
  6927. * TSL function for creating a compute kernel node.
  6928. *
  6929. * @tsl
  6930. * @function
  6931. * @param {Node} node - TODO
  6932. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6933. * @returns {AtomicFunctionNode}
  6934. */
  6935. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6936. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6937. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6938. }
  6939. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6940. const val = workgroupSize[ i ];
  6941. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6942. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6943. }
  6944. }
  6945. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6946. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6947. //
  6948. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6949. };
  6950. /**
  6951. * TSL function for creating a compute node.
  6952. *
  6953. * @tsl
  6954. * @function
  6955. * @param {Node} node - TODO
  6956. * @param {number} count - TODO.
  6957. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6958. * @returns {AtomicFunctionNode}
  6959. */
  6960. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  6961. addMethodChaining( 'compute', compute );
  6962. addMethodChaining( 'computeKernel', computeKernel );
  6963. /**
  6964. * This node can be used as a cache management component for another node.
  6965. * Caching is in general used by default in {@link NodeBuilder} but this node
  6966. * allows the usage of a shared parent cache during the build process.
  6967. *
  6968. * @augments Node
  6969. */
  6970. class IsolateNode extends Node {
  6971. static get type() {
  6972. return 'IsolateNode';
  6973. }
  6974. /**
  6975. * Constructs a new cache node.
  6976. *
  6977. * @param {Node} node - The node that should be cached.
  6978. * @param {Node} [scope=null] - The scope node that defines the cache context.
  6979. */
  6980. constructor( node ) {
  6981. super();
  6982. /**
  6983. * The node that should be cached.
  6984. *
  6985. * @type {Node}
  6986. */
  6987. this.node = node;
  6988. /**
  6989. * Whether this node refers to a shared parent cache or not.
  6990. *
  6991. * @type {boolean}
  6992. * @default true
  6993. */
  6994. this.parent = parent;
  6995. /**
  6996. * This flag can be used for type testing.
  6997. *
  6998. * @type {boolean}
  6999. * @readonly
  7000. * @default true
  7001. */
  7002. this.isIsolateNode = true;
  7003. }
  7004. getNodeType( builder ) {
  7005. const previousCache = builder.getCache();
  7006. const cache = builder.getCacheFromNode( this, this.parent );
  7007. builder.setCache( cache );
  7008. const nodeType = this.node.getNodeType( builder );
  7009. builder.setCache( previousCache );
  7010. return nodeType;
  7011. }
  7012. build( builder, ...params ) {
  7013. const previousCache = builder.getCache();
  7014. const cache = builder.getCacheFromNode( this, this.parent );
  7015. builder.setCache( cache );
  7016. const data = this.node.build( builder, ...params );
  7017. builder.setCache( previousCache );
  7018. return data;
  7019. }
  7020. setParent( parent ) {
  7021. this.parent = parent;
  7022. return this;
  7023. }
  7024. getParent() {
  7025. return this.parent;
  7026. }
  7027. }
  7028. /**
  7029. * TSL function for creating a cache node.
  7030. *
  7031. * @tsl
  7032. * @function
  7033. * @param {Node} node - The node that should be cached.
  7034. * @returns {IsolateNode}
  7035. */
  7036. const isolate = ( node ) => new IsolateNode( nodeObject( node ) );
  7037. /**
  7038. * TSL function for creating a cache node.
  7039. *
  7040. * @tsl
  7041. * @function
  7042. * @deprecated
  7043. * @param {Node} node - The node that should be cached.
  7044. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  7045. * @returns {IsolateNode}
  7046. */
  7047. function cache( node, parent = true ) {
  7048. warn( 'TSL: "cache()" has been deprecated. Use "isolate()" instead.' ); // @deprecated r181
  7049. return isolate( node ).setParent( parent );
  7050. }
  7051. addMethodChaining( 'cache', cache );
  7052. addMethodChaining( 'isolate', isolate );
  7053. /**
  7054. * The class generates the code of a given node but returns another node in the output.
  7055. * This can be used to call a method or node that does not return a value, i.e.
  7056. * type `void` on an input where returning a value is required. Example:
  7057. *
  7058. * ```js
  7059. * material.colorNode = myColor.bypass( runVoidFn() )
  7060. *```
  7061. *
  7062. * @augments Node
  7063. */
  7064. class BypassNode extends Node {
  7065. static get type() {
  7066. return 'BypassNode';
  7067. }
  7068. /**
  7069. * Constructs a new bypass node.
  7070. *
  7071. * @param {Node} outputNode - The output node.
  7072. * @param {Node} callNode - The call node.
  7073. */
  7074. constructor( outputNode, callNode ) {
  7075. super();
  7076. /**
  7077. * This flag can be used for type testing.
  7078. *
  7079. * @type {boolean}
  7080. * @readonly
  7081. * @default true
  7082. */
  7083. this.isBypassNode = true;
  7084. /**
  7085. * The output node.
  7086. *
  7087. * @type {Node}
  7088. */
  7089. this.outputNode = outputNode;
  7090. /**
  7091. * The call node.
  7092. *
  7093. * @type {Node}
  7094. */
  7095. this.callNode = callNode;
  7096. }
  7097. getNodeType( builder ) {
  7098. return this.outputNode.getNodeType( builder );
  7099. }
  7100. generate( builder ) {
  7101. const snippet = this.callNode.build( builder, 'void' );
  7102. if ( snippet !== '' ) {
  7103. builder.addLineFlowCode( snippet, this );
  7104. }
  7105. return this.outputNode.build( builder );
  7106. }
  7107. }
  7108. /**
  7109. * TSL function for creating a bypass node.
  7110. *
  7111. * @tsl
  7112. * @function
  7113. * @param {Node} outputNode - The output node.
  7114. * @param {Node} callNode - The call node.
  7115. * @returns {BypassNode}
  7116. */
  7117. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7118. addMethodChaining( 'bypass', bypass );
  7119. /**
  7120. * This node allows to remap a node value from one range into another. E.g a value of
  7121. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7122. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7123. *
  7124. * @augments Node
  7125. */
  7126. class RemapNode extends Node {
  7127. static get type() {
  7128. return 'RemapNode';
  7129. }
  7130. /**
  7131. * Constructs a new remap node.
  7132. *
  7133. * @param {Node} node - The node that should be remapped.
  7134. * @param {Node} inLowNode - The source or current lower bound of the range.
  7135. * @param {Node} inHighNode - The source or current upper bound of the range.
  7136. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7137. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7138. */
  7139. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7140. super();
  7141. /**
  7142. * The node that should be remapped.
  7143. *
  7144. * @type {Node}
  7145. */
  7146. this.node = node;
  7147. /**
  7148. * The source or current lower bound of the range.
  7149. *
  7150. * @type {Node}
  7151. */
  7152. this.inLowNode = inLowNode;
  7153. /**
  7154. * The source or current upper bound of the range.
  7155. *
  7156. * @type {Node}
  7157. */
  7158. this.inHighNode = inHighNode;
  7159. /**
  7160. * The target lower bound of the range.
  7161. *
  7162. * @type {Node}
  7163. * @default float(0)
  7164. */
  7165. this.outLowNode = outLowNode;
  7166. /**
  7167. * The target upper bound of the range.
  7168. *
  7169. * @type {Node}
  7170. * @default float(1)
  7171. */
  7172. this.outHighNode = outHighNode;
  7173. /**
  7174. * Whether the node value should be clamped before
  7175. * remapping it to the target range.
  7176. *
  7177. * @type {boolean}
  7178. * @default true
  7179. */
  7180. this.doClamp = true;
  7181. }
  7182. setup() {
  7183. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7184. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7185. if ( doClamp === true ) t = t.clamp();
  7186. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7187. }
  7188. }
  7189. /**
  7190. * TSL function for creating a remap node.
  7191. *
  7192. * @tsl
  7193. * @function
  7194. * @param {Node} node - The node that should be remapped.
  7195. * @param {Node} inLowNode - The source or current lower bound of the range.
  7196. * @param {Node} inHighNode - The source or current upper bound of the range.
  7197. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7198. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7199. * @returns {RemapNode}
  7200. */
  7201. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7202. /**
  7203. * TSL function for creating a remap node, but with enabled clamping.
  7204. *
  7205. * @tsl
  7206. * @function
  7207. * @param {Node} node - The node that should be remapped.
  7208. * @param {Node} inLowNode - The source or current lower bound of the range.
  7209. * @param {Node} inHighNode - The source or current upper bound of the range.
  7210. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7211. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7212. * @returns {RemapNode}
  7213. */
  7214. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7215. addMethodChaining( 'remap', remap );
  7216. addMethodChaining( 'remapClamp', remapClamp );
  7217. /**
  7218. * This class can be used to implement basic expressions in shader code.
  7219. * Basic examples for that are `return`, `continue` or `discard` statements.
  7220. *
  7221. * @augments Node
  7222. */
  7223. class ExpressionNode extends Node {
  7224. static get type() {
  7225. return 'ExpressionNode';
  7226. }
  7227. /**
  7228. * Constructs a new expression node.
  7229. *
  7230. * @param {string} [snippet=''] - The native code snippet.
  7231. * @param {string} [nodeType='void'] - The node type.
  7232. */
  7233. constructor( snippet = '', nodeType = 'void' ) {
  7234. super( nodeType );
  7235. /**
  7236. * The native code snippet.
  7237. *
  7238. * @type {string}
  7239. * @default ''
  7240. */
  7241. this.snippet = snippet;
  7242. }
  7243. generate( builder, output ) {
  7244. const type = this.getNodeType( builder );
  7245. const snippet = this.snippet;
  7246. if ( type === 'void' ) {
  7247. builder.addLineFlowCode( snippet, this );
  7248. } else {
  7249. return builder.format( snippet, type, output );
  7250. }
  7251. }
  7252. }
  7253. /**
  7254. * TSL function for creating an expression node.
  7255. *
  7256. * @tsl
  7257. * @function
  7258. * @param {string} [snippet] - The native code snippet.
  7259. * @param {?string} [nodeType='void'] - The node type.
  7260. * @returns {ExpressionNode}
  7261. */
  7262. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7263. /**
  7264. * Represents a `discard` shader operation in TSL.
  7265. *
  7266. * @tsl
  7267. * @function
  7268. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7269. * @return {Node} The `discard` expression.
  7270. */
  7271. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7272. /**
  7273. * Represents a `return` shader operation in TSL.
  7274. *
  7275. * @tsl
  7276. * @function
  7277. * @return {ExpressionNode} The `return` expression.
  7278. */
  7279. const Return = () => expression( 'return' ).toStack();
  7280. addMethodChaining( 'discard', Discard );
  7281. /**
  7282. * Normally, tone mapping and color conversion happens automatically
  7283. * before outputting pixel too the default (screen) framebuffer. In certain
  7284. * post processing setups this happens to late because certain effects
  7285. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7286. * to apply tone mapping and color space conversion at an arbitrary point
  7287. * in the effect chain.
  7288. *
  7289. * When applying tone mapping and color space conversion manually with this node,
  7290. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7291. *
  7292. * ```js
  7293. * const postProcessing = new PostProcessing( renderer );
  7294. * postProcessing.outputColorTransform = false;
  7295. *
  7296. * const scenePass = pass( scene, camera );
  7297. * const outputPass = renderOutput( scenePass );
  7298. *
  7299. * postProcessing.outputNode = outputPass;
  7300. * ```
  7301. *
  7302. * @augments TempNode
  7303. */
  7304. class RenderOutputNode extends TempNode {
  7305. static get type() {
  7306. return 'RenderOutputNode';
  7307. }
  7308. /**
  7309. * Constructs a new render output node.
  7310. *
  7311. * @param {Node} colorNode - The color node to process.
  7312. * @param {?number} toneMapping - The tone mapping type.
  7313. * @param {?string} outputColorSpace - The output color space.
  7314. */
  7315. constructor( colorNode, toneMapping, outputColorSpace ) {
  7316. super( 'vec4' );
  7317. /**
  7318. * The color node to process.
  7319. *
  7320. * @type {Node}
  7321. */
  7322. this.colorNode = colorNode;
  7323. /**
  7324. * The tone mapping type.
  7325. *
  7326. * @type {?number}
  7327. */
  7328. this.toneMapping = toneMapping;
  7329. /**
  7330. * The output color space.
  7331. *
  7332. * @type {?string}
  7333. */
  7334. this.outputColorSpace = outputColorSpace;
  7335. /**
  7336. * This flag can be used for type testing.
  7337. *
  7338. * @type {boolean}
  7339. * @readonly
  7340. * @default true
  7341. */
  7342. this.isRenderOutputNode = true;
  7343. }
  7344. setup( { context } ) {
  7345. let outputNode = this.colorNode || context.color;
  7346. // tone mapping
  7347. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  7348. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7349. if ( toneMapping !== NoToneMapping ) {
  7350. outputNode = outputNode.toneMapping( toneMapping );
  7351. }
  7352. // working to output color space
  7353. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7354. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7355. }
  7356. return outputNode;
  7357. }
  7358. }
  7359. /**
  7360. * TSL function for creating a posterize node.
  7361. *
  7362. * @tsl
  7363. * @function
  7364. * @param {Node} color - The color node to process.
  7365. * @param {?number} [toneMapping=null] - The tone mapping type.
  7366. * @param {?string} [outputColorSpace=null] - The output color space.
  7367. * @returns {RenderOutputNode}
  7368. */
  7369. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7370. addMethodChaining( 'renderOutput', renderOutput );
  7371. class DebugNode extends TempNode {
  7372. static get type() {
  7373. return 'DebugNode';
  7374. }
  7375. constructor( node, callback = null ) {
  7376. super();
  7377. this.node = node;
  7378. this.callback = callback;
  7379. }
  7380. getNodeType( builder ) {
  7381. return this.node.getNodeType( builder );
  7382. }
  7383. setup( builder ) {
  7384. return this.node.build( builder );
  7385. }
  7386. analyze( builder ) {
  7387. return this.node.build( builder );
  7388. }
  7389. generate( builder ) {
  7390. const callback = this.callback;
  7391. const snippet = this.node.build( builder );
  7392. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7393. const border = '-'.repeat( title.length );
  7394. let code = '';
  7395. code += '// #' + title + '#\n';
  7396. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7397. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7398. code += '// #' + border + '#\n';
  7399. if ( callback !== null ) {
  7400. callback( builder, code );
  7401. } else {
  7402. log$1( code );
  7403. }
  7404. return snippet;
  7405. }
  7406. }
  7407. /**
  7408. * TSL function for creating a debug node.
  7409. *
  7410. * @tsl
  7411. * @function
  7412. * @param {Node} node - The node to debug.
  7413. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7414. * @returns {DebugNode}
  7415. */
  7416. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7417. addMethodChaining( 'debug', debug );
  7418. /**
  7419. * InspectorNode is a wrapper node that allows inspection of node values during rendering.
  7420. * It can be used to debug or analyze node outputs in the rendering pipeline.
  7421. *
  7422. * @augments Node
  7423. */
  7424. class InspectorNode extends Node {
  7425. /**
  7426. * Returns the type of the node.
  7427. *
  7428. * @returns {string}
  7429. */
  7430. static get type() {
  7431. return 'InspectorNode';
  7432. }
  7433. /**
  7434. * Creates an InspectorNode.
  7435. *
  7436. * @param {Node} node - The node to inspect.
  7437. * @param {string} [name=''] - Optional name for the inspector node.
  7438. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7439. */
  7440. constructor( node, name = '', callback = null ) {
  7441. super();
  7442. this.node = node;
  7443. this.name = name;
  7444. this.callback = callback;
  7445. this.updateType = NodeUpdateType.FRAME;
  7446. this.isInspectorNode = true;
  7447. }
  7448. /**
  7449. * Returns the name of the inspector node.
  7450. *
  7451. * @returns {string}
  7452. */
  7453. getName() {
  7454. return this.name || this.node.name;
  7455. }
  7456. /**
  7457. * Updates the inspector node, allowing inspection of the wrapped node.
  7458. *
  7459. * @param {NodeFrame} frame - A reference to the current node frame.
  7460. */
  7461. update( frame ) {
  7462. frame.renderer.inspector.inspect( this );
  7463. }
  7464. /**
  7465. * Returns the type of the wrapped node.
  7466. *
  7467. * @param {NodeBuilder} builder - The node builder.
  7468. * @returns {string}
  7469. */
  7470. getNodeType( builder ) {
  7471. return this.node.getNodeType( builder );
  7472. }
  7473. /**
  7474. * Sets up the inspector node.
  7475. *
  7476. * @param {NodeBuilder} builder - The node builder.
  7477. * @returns {Node} The setup node.
  7478. */
  7479. setup( builder ) {
  7480. let node = this.node;
  7481. if ( builder.context.inspector === true && this.callback !== null ) {
  7482. node = this.callback( node );
  7483. }
  7484. return node;
  7485. }
  7486. }
  7487. /**
  7488. * Creates an inspector node to wrap around a given node for inspection purposes.
  7489. *
  7490. * @tsl
  7491. * @param {Node} node - The node to inspect.
  7492. * @param {string} [name=''] - Optional name for the inspector node.
  7493. * @param {Function|null} [callback=null] - Optional callback to modify the node during setup.
  7494. * @returns {Node} The inspector node.
  7495. */
  7496. function inspector( node, name = '', callback = null ) {
  7497. node = nodeObject( node );
  7498. return node.before( new InspectorNode( node, name, callback ) );
  7499. }
  7500. addMethodChaining( 'toInspector', inspector );
  7501. function addNodeElement( name/*, nodeElement*/ ) {
  7502. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7503. }
  7504. /**
  7505. * Base class for representing shader attributes as nodes.
  7506. *
  7507. * @augments Node
  7508. */
  7509. class AttributeNode extends Node {
  7510. static get type() {
  7511. return 'AttributeNode';
  7512. }
  7513. /**
  7514. * Constructs a new attribute node.
  7515. *
  7516. * @param {string} attributeName - The name of the attribute.
  7517. * @param {?string} nodeType - The node type.
  7518. */
  7519. constructor( attributeName, nodeType = null ) {
  7520. super( nodeType );
  7521. /**
  7522. * `AttributeNode` sets this property to `true` by default.
  7523. *
  7524. * @type {boolean}
  7525. * @default true
  7526. */
  7527. this.global = true;
  7528. this._attributeName = attributeName;
  7529. }
  7530. getHash( builder ) {
  7531. return this.getAttributeName( builder );
  7532. }
  7533. getNodeType( builder ) {
  7534. let nodeType = this.nodeType;
  7535. if ( nodeType === null ) {
  7536. const attributeName = this.getAttributeName( builder );
  7537. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7538. const attribute = builder.geometry.getAttribute( attributeName );
  7539. nodeType = builder.getTypeFromAttribute( attribute );
  7540. } else {
  7541. nodeType = 'float';
  7542. }
  7543. }
  7544. return nodeType;
  7545. }
  7546. /**
  7547. * Sets the attribute name to the given value. The method can be
  7548. * overwritten in derived classes if the final name must be computed
  7549. * analytically.
  7550. *
  7551. * @param {string} attributeName - The name of the attribute.
  7552. * @return {AttributeNode} A reference to this node.
  7553. */
  7554. setAttributeName( attributeName ) {
  7555. this._attributeName = attributeName;
  7556. return this;
  7557. }
  7558. /**
  7559. * Returns the attribute name of this node. The method can be
  7560. * overwritten in derived classes if the final name must be computed
  7561. * analytically.
  7562. *
  7563. * @param {NodeBuilder} builder - The current node builder.
  7564. * @return {string} The attribute name.
  7565. */
  7566. getAttributeName( /*builder*/ ) {
  7567. return this._attributeName;
  7568. }
  7569. generate( builder ) {
  7570. const attributeName = this.getAttributeName( builder );
  7571. const nodeType = this.getNodeType( builder );
  7572. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7573. if ( geometryAttribute === true ) {
  7574. const attribute = builder.geometry.getAttribute( attributeName );
  7575. const attributeType = builder.getTypeFromAttribute( attribute );
  7576. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7577. if ( builder.shaderStage === 'vertex' ) {
  7578. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7579. } else {
  7580. const nodeVarying = varying( this );
  7581. return nodeVarying.build( builder, nodeType );
  7582. }
  7583. } else {
  7584. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7585. return builder.generateConst( nodeType );
  7586. }
  7587. }
  7588. serialize( data ) {
  7589. super.serialize( data );
  7590. data.global = this.global;
  7591. data._attributeName = this._attributeName;
  7592. }
  7593. deserialize( data ) {
  7594. super.deserialize( data );
  7595. this.global = data.global;
  7596. this._attributeName = data._attributeName;
  7597. }
  7598. }
  7599. /**
  7600. * TSL function for creating an attribute node.
  7601. *
  7602. * @tsl
  7603. * @function
  7604. * @param {string} name - The name of the attribute.
  7605. * @param {?string} [nodeType=null] - The node type.
  7606. * @returns {AttributeNode}
  7607. */
  7608. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7609. /**
  7610. * TSL function for creating an uv attribute node with the given index.
  7611. *
  7612. * @tsl
  7613. * @function
  7614. * @param {number} [index=0] - The uv index.
  7615. * @return {AttributeNode<vec2>} The uv attribute node.
  7616. */
  7617. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7618. /**
  7619. * A node that represents the dimensions of a texture. The texture size is
  7620. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7621. * or `textureSize()`.
  7622. *
  7623. * @augments Node
  7624. */
  7625. class TextureSizeNode extends Node {
  7626. static get type() {
  7627. return 'TextureSizeNode';
  7628. }
  7629. /**
  7630. * Constructs a new texture size node.
  7631. *
  7632. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7633. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7634. */
  7635. constructor( textureNode, levelNode = null ) {
  7636. super( 'uvec2' );
  7637. /**
  7638. * This flag can be used for type testing.
  7639. *
  7640. * @type {boolean}
  7641. * @readonly
  7642. * @default true
  7643. */
  7644. this.isTextureSizeNode = true;
  7645. /**
  7646. * A texture node which size should be retrieved.
  7647. *
  7648. * @type {TextureNode}
  7649. */
  7650. this.textureNode = textureNode;
  7651. /**
  7652. * A level node which defines the requested mip.
  7653. *
  7654. * @type {Node<int>}
  7655. * @default null
  7656. */
  7657. this.levelNode = levelNode;
  7658. }
  7659. generate( builder, output ) {
  7660. const textureProperty = this.textureNode.build( builder, 'property' );
  7661. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7662. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7663. }
  7664. }
  7665. /**
  7666. * TSL function for creating a texture size node.
  7667. *
  7668. * @tsl
  7669. * @function
  7670. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7671. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7672. * @returns {TextureSizeNode}
  7673. */
  7674. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7675. /**
  7676. * A special type of uniform node that computes the
  7677. * maximum mipmap level for a given texture node.
  7678. *
  7679. * ```js
  7680. * const level = maxMipLevel( textureNode );
  7681. * ```
  7682. *
  7683. * @augments UniformNode
  7684. */
  7685. class MaxMipLevelNode extends UniformNode {
  7686. static get type() {
  7687. return 'MaxMipLevelNode';
  7688. }
  7689. /**
  7690. * Constructs a new max mip level node.
  7691. *
  7692. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7693. */
  7694. constructor( textureNode ) {
  7695. super( 0 );
  7696. /**
  7697. * The texture node to compute the max mip level for.
  7698. *
  7699. * @private
  7700. * @type {TextureNode}
  7701. */
  7702. this._textureNode = textureNode;
  7703. /**
  7704. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7705. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7706. *
  7707. * @type {string}
  7708. * @default 'frame'
  7709. */
  7710. this.updateType = NodeUpdateType.FRAME;
  7711. }
  7712. /**
  7713. * The texture node to compute the max mip level for.
  7714. *
  7715. * @readonly
  7716. * @type {TextureNode}
  7717. */
  7718. get textureNode() {
  7719. return this._textureNode;
  7720. }
  7721. /**
  7722. * The texture.
  7723. *
  7724. * @readonly
  7725. * @type {Texture}
  7726. */
  7727. get texture() {
  7728. return this._textureNode.value;
  7729. }
  7730. update() {
  7731. const texture = this.texture;
  7732. const images = texture.images;
  7733. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7734. if ( image && image.width !== undefined ) {
  7735. const { width, height } = image;
  7736. this.value = Math.log2( Math.max( width, height ) );
  7737. }
  7738. }
  7739. }
  7740. /**
  7741. * TSL function for creating a max mip level node.
  7742. *
  7743. * @tsl
  7744. * @function
  7745. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7746. * @returns {MaxMipLevelNode}
  7747. */
  7748. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7749. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7750. /**
  7751. * This type of uniform node represents a 2D texture.
  7752. *
  7753. * @augments UniformNode
  7754. */
  7755. class TextureNode extends UniformNode {
  7756. static get type() {
  7757. return 'TextureNode';
  7758. }
  7759. /**
  7760. * Constructs a new texture node.
  7761. *
  7762. * @param {Texture} [value=EmptyTexture] - The texture.
  7763. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7764. * @param {?Node<int>} [levelNode=null] - The level node.
  7765. * @param {?Node<float>} [biasNode=null] - The bias node.
  7766. */
  7767. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7768. super( value );
  7769. /**
  7770. * This flag can be used for type testing.
  7771. *
  7772. * @type {boolean}
  7773. * @readonly
  7774. * @default true
  7775. */
  7776. this.isTextureNode = true;
  7777. /**
  7778. * Represents the texture coordinates.
  7779. *
  7780. * @type {?Node<vec2|vec3>}
  7781. * @default null
  7782. */
  7783. this.uvNode = uvNode;
  7784. /**
  7785. * Represents the mip level that should be selected.
  7786. *
  7787. * @type {?Node<int>}
  7788. * @default null
  7789. */
  7790. this.levelNode = levelNode;
  7791. /**
  7792. * Represents the bias to be applied during level-of-detail computation.
  7793. *
  7794. * @type {?Node<float>}
  7795. * @default null
  7796. */
  7797. this.biasNode = biasNode;
  7798. /**
  7799. * Represents a reference value a texture sample is compared to.
  7800. *
  7801. * @type {?Node<float>}
  7802. * @default null
  7803. */
  7804. this.compareNode = null;
  7805. /**
  7806. * When using texture arrays, the depth node defines the layer to select.
  7807. *
  7808. * @type {?Node<int>}
  7809. * @default null
  7810. */
  7811. this.depthNode = null;
  7812. /**
  7813. * When defined, a texture is sampled using explicit gradients.
  7814. *
  7815. * @type {?Array<Node<vec2>>}
  7816. * @default null
  7817. */
  7818. this.gradNode = null;
  7819. /**
  7820. * Represents the optional texel offset applied to the unnormalized texture
  7821. * coordinate before sampling the texture.
  7822. *
  7823. * @type {?Node<ivec2|ivec3>}
  7824. * @default null
  7825. */
  7826. this.offsetNode = null;
  7827. /**
  7828. * Whether texture values should be sampled or fetched.
  7829. *
  7830. * @type {boolean}
  7831. * @default true
  7832. */
  7833. this.sampler = true;
  7834. /**
  7835. * Whether the uv transformation matrix should be
  7836. * automatically updated or not. Use `setUpdateMatrix()`
  7837. * if you want to change the value of the property.
  7838. *
  7839. * @type {boolean}
  7840. * @default false
  7841. */
  7842. this.updateMatrix = false;
  7843. /**
  7844. * By default the `update()` method is not executed. Depending on
  7845. * whether a uv transformation matrix and/or flipY is applied, `update()`
  7846. * is exeucted per object.
  7847. *
  7848. * @type {string}
  7849. * @default 'none'
  7850. */
  7851. this.updateType = NodeUpdateType.NONE;
  7852. /**
  7853. * The reference node.
  7854. *
  7855. * @type {?Node}
  7856. * @default null
  7857. */
  7858. this.referenceNode = null;
  7859. /**
  7860. * The texture value is stored in a private property.
  7861. *
  7862. * @private
  7863. * @type {Texture}
  7864. */
  7865. this._value = value;
  7866. /**
  7867. * The uniform node that represents the uv transformation matrix.
  7868. *
  7869. * @private
  7870. * @type {?UniformNode<mat3>}
  7871. * @default null
  7872. */
  7873. this._matrixUniform = null;
  7874. /**
  7875. * The uniform node that represents the y-flip. Only required for WebGL.
  7876. *
  7877. * @private
  7878. * @type {?UniformNode<bool>}
  7879. * @default null
  7880. */
  7881. this._flipYUniform = null;
  7882. this.setUpdateMatrix( uvNode === null );
  7883. }
  7884. set value( value ) {
  7885. if ( this.referenceNode ) {
  7886. this.referenceNode.value = value;
  7887. } else {
  7888. this._value = value;
  7889. }
  7890. }
  7891. /**
  7892. * The texture value.
  7893. *
  7894. * @type {Texture}
  7895. */
  7896. get value() {
  7897. return this.referenceNode ? this.referenceNode.value : this._value;
  7898. }
  7899. /**
  7900. * Overwritten since the uniform hash is defined by the texture's UUID.
  7901. *
  7902. * @param {NodeBuilder} builder - The current node builder.
  7903. * @return {string} The uniform hash.
  7904. */
  7905. getUniformHash( /*builder*/ ) {
  7906. return this.value.uuid;
  7907. }
  7908. /**
  7909. * Overwritten since the node type is inferred from the texture type.
  7910. *
  7911. * @param {NodeBuilder} builder - The current node builder.
  7912. * @return {string} The node type.
  7913. */
  7914. getNodeType( /*builder*/ ) {
  7915. if ( this.value.isDepthTexture === true ) return 'float';
  7916. if ( this.value.type === UnsignedIntType ) {
  7917. return 'uvec4';
  7918. } else if ( this.value.type === IntType ) {
  7919. return 'ivec4';
  7920. }
  7921. return 'vec4';
  7922. }
  7923. /**
  7924. * Overwrites the default implementation to return a fixed value `'texture'`.
  7925. *
  7926. * @param {NodeBuilder} builder - The current node builder.
  7927. * @return {string} The input type.
  7928. */
  7929. getInputType( /*builder*/ ) {
  7930. return 'texture';
  7931. }
  7932. /**
  7933. * Returns a default uvs based on the current texture's channel.
  7934. *
  7935. * @return {AttributeNode<vec2>} The default uvs.
  7936. */
  7937. getDefaultUV() {
  7938. return uv$1( this.value.channel );
  7939. }
  7940. /**
  7941. * Overwritten to always return the texture reference of the node.
  7942. *
  7943. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7944. * @return {Texture} The texture reference.
  7945. */
  7946. updateReference( /*state*/ ) {
  7947. return this.value;
  7948. }
  7949. /**
  7950. * Transforms the given uv node with the texture transformation matrix.
  7951. *
  7952. * @param {Node} uvNode - The uv node to transform.
  7953. * @return {Node} The transformed uv node.
  7954. */
  7955. getTransformedUV( uvNode ) {
  7956. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7957. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7958. }
  7959. /**
  7960. * Defines whether the uv transformation matrix should automatically be updated or not.
  7961. *
  7962. * @param {boolean} value - The update toggle.
  7963. * @return {TextureNode} A reference to this node.
  7964. */
  7965. setUpdateMatrix( value ) {
  7966. this.updateMatrix = value;
  7967. return this;
  7968. }
  7969. /**
  7970. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7971. * to modify the uv node for correct sampling.
  7972. *
  7973. * @param {NodeBuilder} builder - The current node builder.
  7974. * @param {Node} uvNode - The uv node to setup.
  7975. * @return {Node} The updated uv node.
  7976. */
  7977. setupUV( builder, uvNode ) {
  7978. if ( builder.isFlipY() ) {
  7979. if ( this._flipYUniform === null ) this._flipYUniform = uniform( false );
  7980. uvNode = uvNode.toVar();
  7981. if ( this.sampler ) {
  7982. uvNode = this._flipYUniform.select( uvNode.flipY(), uvNode );
  7983. } else {
  7984. uvNode = this._flipYUniform.select( uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) ), uvNode );
  7985. }
  7986. }
  7987. return uvNode;
  7988. }
  7989. /**
  7990. * Setups texture node by preparing the internal nodes for code generation.
  7991. *
  7992. * @param {NodeBuilder} builder - The current node builder.
  7993. */
  7994. setup( builder ) {
  7995. const properties = builder.getNodeProperties( this );
  7996. properties.referenceNode = this.referenceNode;
  7997. //
  7998. const texture = this.value;
  7999. if ( ! texture || texture.isTexture !== true ) {
  8000. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  8001. }
  8002. //
  8003. const uvNode = Fn( () => {
  8004. let uvNode = this.uvNode;
  8005. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  8006. uvNode = builder.context.getUV( this, builder );
  8007. }
  8008. if ( ! uvNode ) uvNode = this.getDefaultUV();
  8009. if ( this.updateMatrix === true ) {
  8010. uvNode = this.getTransformedUV( uvNode );
  8011. }
  8012. uvNode = this.setupUV( builder, uvNode );
  8013. //
  8014. this.updateType = ( this._matrixUniform !== null || this._flipYUniform !== null ) ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  8015. //
  8016. return uvNode;
  8017. } )();
  8018. //
  8019. let levelNode = this.levelNode;
  8020. if ( levelNode === null && builder.context.getTextureLevel ) {
  8021. levelNode = builder.context.getTextureLevel( this );
  8022. }
  8023. //
  8024. properties.uvNode = uvNode;
  8025. properties.levelNode = levelNode;
  8026. properties.biasNode = this.biasNode;
  8027. properties.compareNode = this.compareNode;
  8028. properties.gradNode = this.gradNode;
  8029. properties.depthNode = this.depthNode;
  8030. properties.offsetNode = this.offsetNode;
  8031. }
  8032. /**
  8033. * Generates the uv code snippet.
  8034. *
  8035. * @param {NodeBuilder} builder - The current node builder.
  8036. * @param {Node} uvNode - The uv node to generate code for.
  8037. * @return {string} The generated code snippet.
  8038. */
  8039. generateUV( builder, uvNode ) {
  8040. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  8041. }
  8042. /**
  8043. * Generates the offset code snippet.
  8044. *
  8045. * @param {NodeBuilder} builder - The current node builder.
  8046. * @param {Node} offsetNode - The offset node to generate code for.
  8047. * @return {string} The generated code snippet.
  8048. */
  8049. generateOffset( builder, offsetNode ) {
  8050. return offsetNode.build( builder, 'ivec2' );
  8051. }
  8052. /**
  8053. * Generates the snippet for the texture sampling.
  8054. *
  8055. * @param {NodeBuilder} builder - The current node builder.
  8056. * @param {string} textureProperty - The texture property.
  8057. * @param {string} uvSnippet - The uv snippet.
  8058. * @param {?string} levelSnippet - The level snippet.
  8059. * @param {?string} biasSnippet - The bias snippet.
  8060. * @param {?string} depthSnippet - The depth snippet.
  8061. * @param {?string} compareSnippet - The compare snippet.
  8062. * @param {?Array<string>} gradSnippet - The grad snippet.
  8063. * @param {?string} offsetSnippet - The offset snippet.
  8064. * @return {string} The generated code snippet.
  8065. */
  8066. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  8067. const texture = this.value;
  8068. let snippet;
  8069. if ( biasSnippet ) {
  8070. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  8071. } else if ( gradSnippet ) {
  8072. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  8073. } else if ( compareSnippet ) {
  8074. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  8075. } else if ( this.sampler === false ) {
  8076. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8077. } else if ( levelSnippet ) {
  8078. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  8079. } else {
  8080. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  8081. }
  8082. return snippet;
  8083. }
  8084. /**
  8085. * Generates the code snippet of the texture node.
  8086. *
  8087. * @param {NodeBuilder} builder - The current node builder.
  8088. * @param {string} output - The current output.
  8089. * @return {string} The generated code snippet.
  8090. */
  8091. generate( builder, output ) {
  8092. const texture = this.value;
  8093. const properties = builder.getNodeProperties( this );
  8094. const textureProperty = super.generate( builder, 'property' );
  8095. if ( /^sampler/.test( output ) ) {
  8096. return textureProperty + '_sampler';
  8097. } else if ( builder.isReference( output ) ) {
  8098. return textureProperty;
  8099. } else {
  8100. const nodeData = builder.getDataFromNode( this );
  8101. let propertyName = nodeData.propertyName;
  8102. if ( propertyName === undefined ) {
  8103. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  8104. const uvSnippet = this.generateUV( builder, uvNode );
  8105. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  8106. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  8107. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  8108. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  8109. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  8110. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  8111. const nodeVar = builder.getVarFromNode( this );
  8112. propertyName = builder.getPropertyName( nodeVar );
  8113. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  8114. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  8115. nodeData.snippet = snippet;
  8116. nodeData.propertyName = propertyName;
  8117. }
  8118. let snippet = propertyName;
  8119. const nodeType = this.getNodeType( builder );
  8120. if ( builder.needsToWorkingColorSpace( texture ) ) {
  8121. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  8122. }
  8123. return builder.format( snippet, nodeType, output );
  8124. }
  8125. }
  8126. /**
  8127. * Sets the sampler value.
  8128. *
  8129. * @param {boolean} value - The sampler value to set.
  8130. * @return {TextureNode} A reference to this texture node.
  8131. */
  8132. setSampler( value ) {
  8133. this.sampler = value;
  8134. return this;
  8135. }
  8136. /**
  8137. * Returns the sampler value.
  8138. *
  8139. * @return {boolean} The sampler value.
  8140. */
  8141. getSampler() {
  8142. return this.sampler;
  8143. }
  8144. // @TODO: Move to TSL
  8145. /**
  8146. * @function
  8147. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8148. *
  8149. * @param {Node} uvNode - The uv node.
  8150. * @return {TextureNode} A texture node representing the texture sample.
  8151. */
  8152. uv( uvNode ) { // @deprecated, r172
  8153. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8154. return this.sample( uvNode );
  8155. }
  8156. /**
  8157. * Samples the texture with the given uv node.
  8158. *
  8159. * @param {Node} uvNode - The uv node.
  8160. * @return {TextureNode} A texture node representing the texture sample.
  8161. */
  8162. sample( uvNode ) {
  8163. const textureNode = this.clone();
  8164. textureNode.uvNode = nodeObject( uvNode );
  8165. textureNode.referenceNode = this.getBase();
  8166. return nodeObject( textureNode );
  8167. }
  8168. /**
  8169. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8170. *
  8171. * @param {Node<uvec2>} uvNode - The uv node.
  8172. * @returns {TextureNode} A texture node representing the texture load.
  8173. */
  8174. load( uvNode ) {
  8175. return this.sample( uvNode ).setSampler( false );
  8176. }
  8177. /**
  8178. * Samples a blurred version of the texture by defining an internal bias.
  8179. *
  8180. * @param {Node<float>} amountNode - How blurred the texture should be.
  8181. * @return {TextureNode} A texture node representing the texture sample.
  8182. */
  8183. blur( amountNode ) {
  8184. const textureNode = this.clone();
  8185. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8186. textureNode.referenceNode = this.getBase();
  8187. const map = textureNode.value;
  8188. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8189. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8190. textureNode.biasNode = null;
  8191. }
  8192. return nodeObject( textureNode );
  8193. }
  8194. /**
  8195. * Samples a specific mip of the texture.
  8196. *
  8197. * @param {Node<int>} levelNode - The mip level to sample.
  8198. * @return {TextureNode} A texture node representing the texture sample.
  8199. */
  8200. level( levelNode ) {
  8201. const textureNode = this.clone();
  8202. textureNode.levelNode = nodeObject( levelNode );
  8203. textureNode.referenceNode = this.getBase();
  8204. return nodeObject( textureNode );
  8205. }
  8206. /**
  8207. * Returns the texture size of the requested level.
  8208. *
  8209. * @param {Node<int>} levelNode - The level to compute the size for.
  8210. * @return {TextureSizeNode} The texture size.
  8211. */
  8212. size( levelNode ) {
  8213. return textureSize( this, levelNode );
  8214. }
  8215. /**
  8216. * Samples the texture with the given bias.
  8217. *
  8218. * @param {Node<float>} biasNode - The bias node.
  8219. * @return {TextureNode} A texture node representing the texture sample.
  8220. */
  8221. bias( biasNode ) {
  8222. const textureNode = this.clone();
  8223. textureNode.biasNode = nodeObject( biasNode );
  8224. textureNode.referenceNode = this.getBase();
  8225. return nodeObject( textureNode );
  8226. }
  8227. /**
  8228. * Returns the base texture of this node.
  8229. * @return {TextureNode} The base texture node.
  8230. */
  8231. getBase() {
  8232. return this.referenceNode ? this.referenceNode.getBase() : this;
  8233. }
  8234. /**
  8235. * Samples the texture by executing a compare operation.
  8236. *
  8237. * @param {Node<float>} compareNode - The node that defines the compare value.
  8238. * @return {TextureNode} A texture node representing the texture sample.
  8239. */
  8240. compare( compareNode ) {
  8241. const textureNode = this.clone();
  8242. textureNode.compareNode = nodeObject( compareNode );
  8243. textureNode.referenceNode = this.getBase();
  8244. return nodeObject( textureNode );
  8245. }
  8246. /**
  8247. * Samples the texture using an explicit gradient.
  8248. *
  8249. * @param {Node<vec2>} gradNodeX - The gradX node.
  8250. * @param {Node<vec2>} gradNodeY - The gradY node.
  8251. * @return {TextureNode} A texture node representing the texture sample.
  8252. */
  8253. grad( gradNodeX, gradNodeY ) {
  8254. const textureNode = this.clone();
  8255. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8256. textureNode.referenceNode = this.getBase();
  8257. return nodeObject( textureNode );
  8258. }
  8259. /**
  8260. * Samples the texture by defining a depth node.
  8261. *
  8262. * @param {Node<int>} depthNode - The depth node.
  8263. * @return {TextureNode} A texture node representing the texture sample.
  8264. */
  8265. depth( depthNode ) {
  8266. const textureNode = this.clone();
  8267. textureNode.depthNode = nodeObject( depthNode );
  8268. textureNode.referenceNode = this.getBase();
  8269. return nodeObject( textureNode );
  8270. }
  8271. /**
  8272. * Samples the texture by defining an offset node.
  8273. *
  8274. * @param {Node<ivec2>} offsetNode - The offset node.
  8275. * @return {TextureNode} A texture node representing the texture sample.
  8276. */
  8277. offset( offsetNode ) {
  8278. const textureNode = this.clone();
  8279. textureNode.offsetNode = nodeObject( offsetNode );
  8280. textureNode.referenceNode = this.getBase();
  8281. return nodeObject( textureNode );
  8282. }
  8283. // --
  8284. serialize( data ) {
  8285. super.serialize( data );
  8286. data.value = this.value.toJSON( data.meta ).uuid;
  8287. data.sampler = this.sampler;
  8288. data.updateMatrix = this.updateMatrix;
  8289. data.updateType = this.updateType;
  8290. }
  8291. deserialize( data ) {
  8292. super.deserialize( data );
  8293. this.value = data.meta.textures[ data.value ];
  8294. this.sampler = data.sampler;
  8295. this.updateMatrix = data.updateMatrix;
  8296. this.updateType = data.updateType;
  8297. }
  8298. /**
  8299. * The update is used to implement the update of the uv transformation matrix.
  8300. */
  8301. update() {
  8302. const texture = this.value;
  8303. const matrixUniform = this._matrixUniform;
  8304. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8305. if ( texture.matrixAutoUpdate === true ) {
  8306. texture.updateMatrix();
  8307. }
  8308. //
  8309. const flipYUniform = this._flipYUniform;
  8310. if ( flipYUniform !== null ) {
  8311. flipYUniform.value = ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true );
  8312. }
  8313. }
  8314. /**
  8315. * Clones the texture node.
  8316. *
  8317. * @return {TextureNode} The cloned texture node.
  8318. */
  8319. clone() {
  8320. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8321. newNode.sampler = this.sampler;
  8322. newNode.depthNode = this.depthNode;
  8323. newNode.compareNode = this.compareNode;
  8324. newNode.gradNode = this.gradNode;
  8325. newNode.offsetNode = this.offsetNode;
  8326. return newNode;
  8327. }
  8328. }
  8329. /**
  8330. * TSL function for creating a texture node.
  8331. *
  8332. * @tsl
  8333. * @function
  8334. * @param {?Texture} value - The texture.
  8335. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8336. * @param {?Node<int>} [levelNode=null] - The level node.
  8337. * @param {?Node<float>} [biasNode=null] - The bias node.
  8338. * @returns {TextureNode}
  8339. */
  8340. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8341. /**
  8342. * TSL function for creating a texture node or sample a texture node already existing.
  8343. *
  8344. * @tsl
  8345. * @function
  8346. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8347. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8348. * @param {?Node<int>} [levelNode=null] - The level node.
  8349. * @param {?Node<float>} [biasNode=null] - The bias node.
  8350. * @returns {TextureNode}
  8351. */
  8352. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8353. let textureNode;
  8354. if ( value && value.isTextureNode === true ) {
  8355. textureNode = nodeObject( value.clone() );
  8356. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8357. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8358. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8359. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8360. } else {
  8361. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8362. }
  8363. return textureNode;
  8364. };
  8365. /**
  8366. * TSL function for creating a uniform texture node.
  8367. *
  8368. * @tsl
  8369. * @function
  8370. * @param {?Texture} value - The texture.
  8371. * @returns {TextureNode}
  8372. */
  8373. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8374. /**
  8375. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8376. *
  8377. * @tsl
  8378. * @function
  8379. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8380. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8381. * @param {?Node<int>} [levelNode=null] - The level node.
  8382. * @param {?Node<float>} [biasNode=null] - The bias node.
  8383. * @returns {TextureNode}
  8384. */
  8385. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8386. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8387. /**
  8388. * Converts a texture or texture node to a sampler.
  8389. *
  8390. * @tsl
  8391. * @function
  8392. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8393. * @returns {Node}
  8394. */
  8395. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8396. /**
  8397. * Converts a texture or texture node to a sampler comparison.
  8398. *
  8399. * @tsl
  8400. * @function
  8401. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8402. * @returns {Node}
  8403. */
  8404. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8405. /**
  8406. * A special type of uniform node which represents array-like data
  8407. * as uniform buffers. The access usually happens via `element()`
  8408. * which returns an instance of {@link ArrayElementNode}. For example:
  8409. *
  8410. * ```js
  8411. * const bufferNode = buffer( array, 'mat4', count );
  8412. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8413. * ```
  8414. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8415. * since it handles more input types and automatically cares about buffer paddings.
  8416. *
  8417. * @augments UniformNode
  8418. */
  8419. class BufferNode extends UniformNode {
  8420. static get type() {
  8421. return 'BufferNode';
  8422. }
  8423. /**
  8424. * Constructs a new buffer node.
  8425. *
  8426. * @param {Array<number>} value - Array-like buffer data.
  8427. * @param {string} bufferType - The data type of the buffer.
  8428. * @param {number} [bufferCount=0] - The count of buffer elements.
  8429. */
  8430. constructor( value, bufferType, bufferCount = 0 ) {
  8431. super( value, bufferType );
  8432. /**
  8433. * This flag can be used for type testing.
  8434. *
  8435. * @type {boolean}
  8436. * @readonly
  8437. * @default true
  8438. */
  8439. this.isBufferNode = true;
  8440. /**
  8441. * The data type of the buffer.
  8442. *
  8443. * @type {string}
  8444. */
  8445. this.bufferType = bufferType;
  8446. /**
  8447. * The uniform node that holds the value of the reference node.
  8448. *
  8449. * @type {number}
  8450. * @default 0
  8451. */
  8452. this.bufferCount = bufferCount;
  8453. }
  8454. /**
  8455. * The data type of the buffer elements.
  8456. *
  8457. * @param {NodeBuilder} builder - The current node builder.
  8458. * @return {string} The element type.
  8459. */
  8460. getElementType( builder ) {
  8461. return this.getNodeType( builder );
  8462. }
  8463. /**
  8464. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8465. *
  8466. * @param {NodeBuilder} builder - The current node builder.
  8467. * @return {string} The input type.
  8468. */
  8469. getInputType( /*builder*/ ) {
  8470. return 'buffer';
  8471. }
  8472. }
  8473. /**
  8474. * TSL function for creating a buffer node.
  8475. *
  8476. * @tsl
  8477. * @function
  8478. * @param {Array<number>} value - Array-like buffer data.
  8479. * @param {string} type - The data type of a buffer element.
  8480. * @param {number} count - The count of buffer elements.
  8481. * @returns {BufferNode}
  8482. */
  8483. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8484. /**
  8485. * Represents the element access on uniform array nodes.
  8486. *
  8487. * @augments ArrayElementNode
  8488. */
  8489. class UniformArrayElementNode extends ArrayElementNode {
  8490. static get type() {
  8491. return 'UniformArrayElementNode';
  8492. }
  8493. /**
  8494. * Constructs a new buffer node.
  8495. *
  8496. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8497. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8498. */
  8499. constructor( uniformArrayNode, indexNode ) {
  8500. super( uniformArrayNode, indexNode );
  8501. /**
  8502. * This flag can be used for type testing.
  8503. *
  8504. * @type {boolean}
  8505. * @readonly
  8506. * @default true
  8507. */
  8508. this.isArrayBufferElementNode = true;
  8509. }
  8510. generate( builder ) {
  8511. const snippet = super.generate( builder );
  8512. const type = this.getNodeType();
  8513. const paddedType = this.node.getPaddedType();
  8514. return builder.format( snippet, paddedType, type );
  8515. }
  8516. }
  8517. /**
  8518. * Similar to {@link BufferNode} this module represents array-like data as
  8519. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8520. * data types in the array (e.g `three.js` primitives) and automatically
  8521. * manage buffer padding. It should be the first choice when working with
  8522. * uniforms buffers.
  8523. * ```js
  8524. * const tintColors = uniformArray( [
  8525. * new Color( 1, 0, 0 ),
  8526. * new Color( 0, 1, 0 ),
  8527. * new Color( 0, 0, 1 )
  8528. * ], 'color' );
  8529. *
  8530. * const redColor = tintColors.element( 0 );
  8531. *
  8532. * @augments BufferNode
  8533. */
  8534. class UniformArrayNode extends BufferNode {
  8535. static get type() {
  8536. return 'UniformArrayNode';
  8537. }
  8538. /**
  8539. * Constructs a new uniform array node.
  8540. *
  8541. * @param {Array<any>} value - Array holding the buffer data.
  8542. * @param {?string} [elementType=null] - The data type of a buffer element.
  8543. */
  8544. constructor( value, elementType = null ) {
  8545. super( null );
  8546. /**
  8547. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8548. * hold number primitives as well as three.js objects like vectors, matrices
  8549. * or colors.
  8550. *
  8551. * @type {Array<any>}
  8552. */
  8553. this.array = value;
  8554. /**
  8555. * The data type of an array element.
  8556. *
  8557. * @type {string}
  8558. */
  8559. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8560. /**
  8561. * The padded type. Uniform buffers must conform to a certain buffer layout
  8562. * so a separate type is computed to ensure correct buffer size.
  8563. *
  8564. * @type {string}
  8565. */
  8566. this.paddedType = this.getPaddedType();
  8567. /**
  8568. * Overwritten since uniform array nodes are updated per render.
  8569. *
  8570. * @type {string}
  8571. * @default 'render'
  8572. */
  8573. this.updateType = NodeUpdateType.RENDER;
  8574. /**
  8575. * This flag can be used for type testing.
  8576. *
  8577. * @type {boolean}
  8578. * @readonly
  8579. * @default true
  8580. */
  8581. this.isArrayBufferNode = true;
  8582. }
  8583. /**
  8584. * This method is overwritten since the node type is inferred from the
  8585. * {@link UniformArrayNode#paddedType}.
  8586. *
  8587. * @param {NodeBuilder} builder - The current node builder.
  8588. * @return {string} The node type.
  8589. */
  8590. getNodeType( /*builder*/ ) {
  8591. return this.paddedType;
  8592. }
  8593. /**
  8594. * The data type of the array elements.
  8595. *
  8596. * @param {NodeBuilder} builder - The current node builder.
  8597. * @return {string} The element type.
  8598. */
  8599. getElementType() {
  8600. return this.elementType;
  8601. }
  8602. /**
  8603. * Returns the padded type based on the element type.
  8604. *
  8605. * @return {string} The padded type.
  8606. */
  8607. getPaddedType() {
  8608. const elementType = this.elementType;
  8609. let paddedType = 'vec4';
  8610. if ( elementType === 'mat2' ) {
  8611. paddedType = 'mat2';
  8612. } else if ( /mat/.test( elementType ) === true ) {
  8613. paddedType = 'mat4';
  8614. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8615. paddedType = 'ivec4';
  8616. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8617. paddedType = 'uvec4';
  8618. }
  8619. return paddedType;
  8620. }
  8621. /**
  8622. * The update makes sure to correctly transfer the data from the (complex) objects
  8623. * in the array to the internal, correctly padded value buffer.
  8624. *
  8625. * @param {NodeFrame} frame - A reference to the current node frame.
  8626. */
  8627. update( /*frame*/ ) {
  8628. const { array, value } = this;
  8629. const elementType = this.elementType;
  8630. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8631. for ( let i = 0; i < array.length; i ++ ) {
  8632. const index = i * 4;
  8633. value[ index ] = array[ i ];
  8634. }
  8635. } else if ( elementType === 'color' ) {
  8636. for ( let i = 0; i < array.length; i ++ ) {
  8637. const index = i * 4;
  8638. const vector = array[ i ];
  8639. value[ index ] = vector.r;
  8640. value[ index + 1 ] = vector.g;
  8641. value[ index + 2 ] = vector.b || 0;
  8642. //value[ index + 3 ] = vector.a || 0;
  8643. }
  8644. } else if ( elementType === 'mat2' ) {
  8645. for ( let i = 0; i < array.length; i ++ ) {
  8646. const index = i * 4;
  8647. const matrix = array[ i ];
  8648. value[ index ] = matrix.elements[ 0 ];
  8649. value[ index + 1 ] = matrix.elements[ 1 ];
  8650. value[ index + 2 ] = matrix.elements[ 2 ];
  8651. value[ index + 3 ] = matrix.elements[ 3 ];
  8652. }
  8653. } else if ( elementType === 'mat3' ) {
  8654. for ( let i = 0; i < array.length; i ++ ) {
  8655. const index = i * 16;
  8656. const matrix = array[ i ];
  8657. value[ index ] = matrix.elements[ 0 ];
  8658. value[ index + 1 ] = matrix.elements[ 1 ];
  8659. value[ index + 2 ] = matrix.elements[ 2 ];
  8660. value[ index + 4 ] = matrix.elements[ 3 ];
  8661. value[ index + 5 ] = matrix.elements[ 4 ];
  8662. value[ index + 6 ] = matrix.elements[ 5 ];
  8663. value[ index + 8 ] = matrix.elements[ 6 ];
  8664. value[ index + 9 ] = matrix.elements[ 7 ];
  8665. value[ index + 10 ] = matrix.elements[ 8 ];
  8666. value[ index + 15 ] = 1;
  8667. }
  8668. } else if ( elementType === 'mat4' ) {
  8669. for ( let i = 0; i < array.length; i ++ ) {
  8670. const index = i * 16;
  8671. const matrix = array[ i ];
  8672. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8673. value[ index + i ] = matrix.elements[ i ];
  8674. }
  8675. }
  8676. } else {
  8677. for ( let i = 0; i < array.length; i ++ ) {
  8678. const index = i * 4;
  8679. const vector = array[ i ];
  8680. value[ index ] = vector.x;
  8681. value[ index + 1 ] = vector.y;
  8682. value[ index + 2 ] = vector.z || 0;
  8683. value[ index + 3 ] = vector.w || 0;
  8684. }
  8685. }
  8686. }
  8687. /**
  8688. * Implement the value buffer creation based on the array data.
  8689. *
  8690. * @param {NodeBuilder} builder - A reference to the current node builder.
  8691. * @return {null}
  8692. */
  8693. setup( builder ) {
  8694. const length = this.array.length;
  8695. const elementType = this.elementType;
  8696. let arrayType = Float32Array;
  8697. const paddedType = this.paddedType;
  8698. const paddedElementLength = builder.getTypeLength( paddedType );
  8699. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8700. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8701. this.value = new arrayType( length * paddedElementLength );
  8702. this.bufferCount = length;
  8703. this.bufferType = paddedType;
  8704. return super.setup( builder );
  8705. }
  8706. /**
  8707. * Overwrites the default `element()` method to provide element access
  8708. * based on {@link UniformArrayNode}.
  8709. *
  8710. * @param {IndexNode} indexNode - The index node.
  8711. * @return {UniformArrayElementNode}
  8712. */
  8713. element( indexNode ) {
  8714. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8715. }
  8716. }
  8717. /**
  8718. * TSL function for creating an uniform array node.
  8719. *
  8720. * @tsl
  8721. * @function
  8722. * @param {Array<any>} values - Array-like data.
  8723. * @param {?string} [nodeType] - The data type of the array elements.
  8724. * @returns {UniformArrayNode}
  8725. */
  8726. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8727. /**
  8728. * The node allows to set values for built-in shader variables. That is
  8729. * required for features like hardware-accelerated vertex clipping.
  8730. *
  8731. * @augments Node
  8732. */
  8733. class BuiltinNode extends Node {
  8734. /**
  8735. * Constructs a new builtin node.
  8736. *
  8737. * @param {string} name - The name of the built-in shader variable.
  8738. */
  8739. constructor( name ) {
  8740. super( 'float' );
  8741. /**
  8742. * The name of the built-in shader variable.
  8743. *
  8744. * @type {string}
  8745. */
  8746. this.name = name;
  8747. /**
  8748. * This flag can be used for type testing.
  8749. *
  8750. * @type {boolean}
  8751. * @readonly
  8752. * @default true
  8753. */
  8754. this.isBuiltinNode = true;
  8755. }
  8756. /**
  8757. * Generates the code snippet of the builtin node.
  8758. *
  8759. * @param {NodeBuilder} builder - The current node builder.
  8760. * @return {string} The generated code snippet.
  8761. */
  8762. generate( /* builder */ ) {
  8763. return this.name;
  8764. }
  8765. }
  8766. /**
  8767. * TSL function for creating a builtin node.
  8768. *
  8769. * @tsl
  8770. * @function
  8771. * @param {string} name - The name of the built-in shader variable.
  8772. * @returns {BuiltinNode}
  8773. */
  8774. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8775. let _screenSizeVec, _viewportVec;
  8776. /**
  8777. * This node provides a collection of screen related metrics.
  8778. * Depending on {@link ScreenNode#scope}, the nodes can represent
  8779. * resolution or viewport data as well as fragment or uv coordinates.
  8780. *
  8781. * @augments Node
  8782. */
  8783. class ScreenNode extends Node {
  8784. static get type() {
  8785. return 'ScreenNode';
  8786. }
  8787. /**
  8788. * Constructs a new screen node.
  8789. *
  8790. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  8791. */
  8792. constructor( scope ) {
  8793. super();
  8794. /**
  8795. * The node represents different metric depending on which scope is selected.
  8796. *
  8797. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  8798. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  8799. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  8800. * - `ScreenNode.UV`: Normalized coordinates.
  8801. * - `ScreenNode.DPR`: Device pixel ratio.
  8802. *
  8803. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  8804. */
  8805. this.scope = scope;
  8806. /**
  8807. * This output node.
  8808. *
  8809. * @type {?Node}
  8810. * @default null
  8811. */
  8812. this._output = null;
  8813. /**
  8814. * This flag can be used for type testing.
  8815. *
  8816. * @type {boolean}
  8817. * @readonly
  8818. * @default true
  8819. */
  8820. this.isViewportNode = true;
  8821. }
  8822. /**
  8823. * This method is overwritten since the node type depends on the selected scope.
  8824. *
  8825. * @return {('float'|'vec2'|'vec4')} The node type.
  8826. */
  8827. getNodeType() {
  8828. if ( this.scope === ScreenNode.DPR ) return 'float';
  8829. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  8830. else return 'vec2';
  8831. }
  8832. /**
  8833. * This method is overwritten since the node's update type depends on the selected scope.
  8834. *
  8835. * @return {NodeUpdateType} The update type.
  8836. */
  8837. getUpdateType() {
  8838. let updateType = NodeUpdateType.NONE;
  8839. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  8840. updateType = NodeUpdateType.RENDER;
  8841. }
  8842. this.updateType = updateType;
  8843. return updateType;
  8844. }
  8845. /**
  8846. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  8847. * from the current renderer.
  8848. *
  8849. * @param {NodeFrame} frame - A reference to the current node frame.
  8850. */
  8851. update( { renderer } ) {
  8852. const renderTarget = renderer.getRenderTarget();
  8853. if ( this.scope === ScreenNode.VIEWPORT ) {
  8854. if ( renderTarget !== null ) {
  8855. _viewportVec.copy( renderTarget.viewport );
  8856. } else {
  8857. renderer.getViewport( _viewportVec );
  8858. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  8859. }
  8860. } else if ( this.scope === ScreenNode.DPR ) {
  8861. this._output.value = renderer.getPixelRatio();
  8862. } else {
  8863. if ( renderTarget !== null ) {
  8864. _screenSizeVec.width = renderTarget.width;
  8865. _screenSizeVec.height = renderTarget.height;
  8866. } else {
  8867. renderer.getDrawingBufferSize( _screenSizeVec );
  8868. }
  8869. }
  8870. }
  8871. setup( /*builder*/ ) {
  8872. const scope = this.scope;
  8873. let output = null;
  8874. if ( scope === ScreenNode.SIZE ) {
  8875. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  8876. } else if ( scope === ScreenNode.VIEWPORT ) {
  8877. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  8878. } else if ( scope === ScreenNode.DPR ) {
  8879. output = uniform( 1 );
  8880. } else {
  8881. output = vec2( screenCoordinate.div( screenSize ) );
  8882. }
  8883. this._output = output;
  8884. return output;
  8885. }
  8886. generate( builder ) {
  8887. if ( this.scope === ScreenNode.COORDINATE ) {
  8888. let coord = builder.getFragCoord();
  8889. if ( builder.isFlipY() ) {
  8890. // follow webgpu standards
  8891. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  8892. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  8893. }
  8894. return coord;
  8895. }
  8896. return super.generate( builder );
  8897. }
  8898. }
  8899. ScreenNode.COORDINATE = 'coordinate';
  8900. ScreenNode.VIEWPORT = 'viewport';
  8901. ScreenNode.SIZE = 'size';
  8902. ScreenNode.UV = 'uv';
  8903. ScreenNode.DPR = 'dpr';
  8904. // Screen
  8905. /**
  8906. * TSL object that represents the current DPR.
  8907. *
  8908. * @tsl
  8909. * @type {ScreenNode<float>}
  8910. */
  8911. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  8912. /**
  8913. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  8914. *
  8915. * @tsl
  8916. * @type {ScreenNode<vec2>}
  8917. */
  8918. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  8919. /**
  8920. * TSL object that represents the screen resolution in physical pixel units.
  8921. *
  8922. * @tsl
  8923. * @type {ScreenNode<vec2>}
  8924. */
  8925. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  8926. /**
  8927. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  8928. *
  8929. * @tsl
  8930. * @type {ScreenNode<vec2>}
  8931. */
  8932. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  8933. // Viewport
  8934. /**
  8935. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  8936. *
  8937. * @tsl
  8938. * @type {ScreenNode<vec4>}
  8939. */
  8940. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  8941. /**
  8942. * TSL object that represents the viewport resolution in physical pixel units.
  8943. *
  8944. * @tsl
  8945. * @type {ScreenNode<vec2>}
  8946. */
  8947. const viewportSize = viewport.zw;
  8948. /**
  8949. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  8950. *
  8951. * @tsl
  8952. * @type {ScreenNode<vec2>}
  8953. */
  8954. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  8955. /**
  8956. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  8957. *
  8958. * @tsl
  8959. * @type {ScreenNode<vec2>}
  8960. */
  8961. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  8962. // Deprecated
  8963. /**
  8964. * @deprecated since r169. Use {@link screenSize} instead.
  8965. */
  8966. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  8967. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  8968. return screenSize;
  8969. }, 'vec2' ).once() )();
  8970. /**
  8971. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8972. *
  8973. * @tsl
  8974. * @type {UniformNode<uint>}
  8975. */
  8976. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8977. /**
  8978. * TSL object that represents the `near` value of the camera used for the current render.
  8979. *
  8980. * @tsl
  8981. * @type {UniformNode<float>}
  8982. */
  8983. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8984. /**
  8985. * TSL object that represents the `far` value of the camera used for the current render.
  8986. *
  8987. * @tsl
  8988. * @type {UniformNode<float>}
  8989. */
  8990. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8991. /**
  8992. * TSL object that represents the projection matrix of the camera used for the current render.
  8993. *
  8994. * @tsl
  8995. * @type {UniformNode<mat4>}
  8996. */
  8997. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8998. let cameraProjectionMatrix;
  8999. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9000. const matrices = [];
  9001. for ( const subCamera of camera.cameras ) {
  9002. matrices.push( subCamera.projectionMatrix );
  9003. }
  9004. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  9005. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  9006. } else {
  9007. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  9008. }
  9009. return cameraProjectionMatrix;
  9010. } ).once() )();
  9011. /**
  9012. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  9013. *
  9014. * @tsl
  9015. * @type {UniformNode<mat4>}
  9016. */
  9017. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9018. let cameraProjectionMatrixInverse;
  9019. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9020. const matrices = [];
  9021. for ( const subCamera of camera.cameras ) {
  9022. matrices.push( subCamera.projectionMatrixInverse );
  9023. }
  9024. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  9025. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  9026. } else {
  9027. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  9028. }
  9029. return cameraProjectionMatrixInverse;
  9030. } ).once() )();
  9031. /**
  9032. * TSL object that represents the view matrix of the camera used for the current render.
  9033. *
  9034. * @tsl
  9035. * @type {UniformNode<mat4>}
  9036. */
  9037. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9038. let cameraViewMatrix;
  9039. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9040. const matrices = [];
  9041. for ( const subCamera of camera.cameras ) {
  9042. matrices.push( subCamera.matrixWorldInverse );
  9043. }
  9044. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  9045. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  9046. } else {
  9047. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  9048. }
  9049. return cameraViewMatrix;
  9050. } ).once() )();
  9051. /**
  9052. * TSL object that represents the world matrix of the camera used for the current render.
  9053. *
  9054. * @tsl
  9055. * @type {UniformNode<mat4>}
  9056. */
  9057. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9058. let cameraWorldMatrix;
  9059. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9060. const matrices = [];
  9061. for ( const subCamera of camera.cameras ) {
  9062. matrices.push( subCamera.matrixWorld );
  9063. }
  9064. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  9065. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  9066. } else {
  9067. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  9068. }
  9069. return cameraWorldMatrix;
  9070. } ).once() )();
  9071. /**
  9072. * TSL object that represents the normal matrix of the camera used for the current render.
  9073. *
  9074. * @tsl
  9075. * @type {UniformNode<mat3>}
  9076. */
  9077. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9078. let cameraNormalMatrix;
  9079. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9080. const matrices = [];
  9081. for ( const subCamera of camera.cameras ) {
  9082. matrices.push( subCamera.normalMatrix );
  9083. }
  9084. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  9085. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  9086. } else {
  9087. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  9088. }
  9089. return cameraNormalMatrix;
  9090. } ).once() )();
  9091. /**
  9092. * TSL object that represents the position in world space of the camera used for the current render.
  9093. *
  9094. * @tsl
  9095. * @type {UniformNode<vec3>}
  9096. */
  9097. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9098. let cameraPosition;
  9099. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9100. const positions = [];
  9101. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  9102. positions.push( new Vector3() );
  9103. }
  9104. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  9105. const subCameras = camera.cameras;
  9106. const array = self.array;
  9107. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  9108. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  9109. }
  9110. } );
  9111. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  9112. } else {
  9113. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  9114. }
  9115. return cameraPosition;
  9116. } ).once() )();
  9117. /**
  9118. * TSL object that represents the viewport of the camera used for the current render.
  9119. *
  9120. * @tsl
  9121. * @type {UniformNode<vec4>}
  9122. */
  9123. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  9124. let cameraViewport;
  9125. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  9126. const viewports = [];
  9127. for ( const subCamera of camera.cameras ) {
  9128. viewports.push( subCamera.viewport );
  9129. }
  9130. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  9131. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  9132. } else {
  9133. // Fallback for single camera
  9134. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  9135. }
  9136. return cameraViewport;
  9137. } ).once() )();
  9138. const _sphere = /*@__PURE__*/ new Sphere();
  9139. /**
  9140. * This node can be used to access transformation related metrics of 3D objects.
  9141. * Depending on the selected scope, a different metric is represented as a uniform
  9142. * in the shader. The following scopes are supported:
  9143. *
  9144. * - `POSITION`: The object's position in world space.
  9145. * - `VIEW_POSITION`: The object's position in view/camera space.
  9146. * - `DIRECTION`: The object's direction in world space.
  9147. * - `SCALE`: The object's scale in world space.
  9148. * - `WORLD_MATRIX`: The object's matrix in world space.
  9149. *
  9150. * @augments Node
  9151. */
  9152. class Object3DNode extends Node {
  9153. static get type() {
  9154. return 'Object3DNode';
  9155. }
  9156. /**
  9157. * Constructs a new object 3D node.
  9158. *
  9159. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9160. * @param {?Object3D} [object3d=null] - The 3D object.
  9161. */
  9162. constructor( scope, object3d = null ) {
  9163. super();
  9164. /**
  9165. * The node reports a different type of transformation depending on the scope.
  9166. *
  9167. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9168. */
  9169. this.scope = scope;
  9170. /**
  9171. * The 3D object.
  9172. *
  9173. * @type {?Object3D}
  9174. * @default null
  9175. */
  9176. this.object3d = object3d;
  9177. /**
  9178. * Overwritten since this type of node is updated per object.
  9179. *
  9180. * @type {string}
  9181. * @default 'object'
  9182. */
  9183. this.updateType = NodeUpdateType.OBJECT;
  9184. /**
  9185. * Holds the value of the node as a uniform.
  9186. *
  9187. * @type {UniformNode}
  9188. */
  9189. this.uniformNode = new UniformNode( null );
  9190. }
  9191. /**
  9192. * Overwritten since the node type is inferred from the scope.
  9193. *
  9194. * @return {('mat4'|'vec3'|'float')} The node type.
  9195. */
  9196. getNodeType() {
  9197. const scope = this.scope;
  9198. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9199. return 'mat4';
  9200. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9201. return 'vec3';
  9202. } else if ( scope === Object3DNode.RADIUS ) {
  9203. return 'float';
  9204. }
  9205. }
  9206. /**
  9207. * Updates the uniform value depending on the scope.
  9208. *
  9209. * @param {NodeFrame} frame - The current node frame.
  9210. */
  9211. update( frame ) {
  9212. const object = this.object3d;
  9213. const uniformNode = this.uniformNode;
  9214. const scope = this.scope;
  9215. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9216. uniformNode.value = object.matrixWorld;
  9217. } else if ( scope === Object3DNode.POSITION ) {
  9218. uniformNode.value = uniformNode.value || new Vector3();
  9219. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9220. } else if ( scope === Object3DNode.SCALE ) {
  9221. uniformNode.value = uniformNode.value || new Vector3();
  9222. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9223. } else if ( scope === Object3DNode.DIRECTION ) {
  9224. uniformNode.value = uniformNode.value || new Vector3();
  9225. object.getWorldDirection( uniformNode.value );
  9226. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9227. const camera = frame.camera;
  9228. uniformNode.value = uniformNode.value || new Vector3();
  9229. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9230. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9231. } else if ( scope === Object3DNode.RADIUS ) {
  9232. const geometry = frame.object.geometry;
  9233. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9234. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9235. uniformNode.value = _sphere.radius;
  9236. }
  9237. }
  9238. /**
  9239. * Generates the code snippet of the uniform node. The node type of the uniform
  9240. * node also depends on the selected scope.
  9241. *
  9242. * @param {NodeBuilder} builder - The current node builder.
  9243. * @return {string} The generated code snippet.
  9244. */
  9245. generate( builder ) {
  9246. const scope = this.scope;
  9247. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9248. this.uniformNode.nodeType = 'mat4';
  9249. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9250. this.uniformNode.nodeType = 'vec3';
  9251. } else if ( scope === Object3DNode.RADIUS ) {
  9252. this.uniformNode.nodeType = 'float';
  9253. }
  9254. return this.uniformNode.build( builder );
  9255. }
  9256. serialize( data ) {
  9257. super.serialize( data );
  9258. data.scope = this.scope;
  9259. }
  9260. deserialize( data ) {
  9261. super.deserialize( data );
  9262. this.scope = data.scope;
  9263. }
  9264. }
  9265. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9266. Object3DNode.POSITION = 'position';
  9267. Object3DNode.SCALE = 'scale';
  9268. Object3DNode.VIEW_POSITION = 'viewPosition';
  9269. Object3DNode.DIRECTION = 'direction';
  9270. Object3DNode.RADIUS = 'radius';
  9271. /**
  9272. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9273. *
  9274. * @tsl
  9275. * @function
  9276. * @param {?Object3D} [object3d] - The 3D object.
  9277. * @returns {Object3DNode<vec3>}
  9278. */
  9279. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9280. /**
  9281. * TSL function for creating an object 3D node that represents the object's world matrix.
  9282. *
  9283. * @tsl
  9284. * @function
  9285. * @param {?Object3D} [object3d] - The 3D object.
  9286. * @returns {Object3DNode<mat4>}
  9287. */
  9288. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9289. /**
  9290. * TSL function for creating an object 3D node that represents the object's position in world space.
  9291. *
  9292. * @tsl
  9293. * @function
  9294. * @param {?Object3D} [object3d] - The 3D object.
  9295. * @returns {Object3DNode<vec3>}
  9296. */
  9297. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9298. /**
  9299. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9300. *
  9301. * @tsl
  9302. * @function
  9303. * @param {?Object3D} [object3d] - The 3D object.
  9304. * @returns {Object3DNode<vec3>}
  9305. */
  9306. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9307. /**
  9308. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9309. *
  9310. * @tsl
  9311. * @function
  9312. * @param {?Object3D} [object3d] - The 3D object.
  9313. * @returns {Object3DNode<vec3>}
  9314. */
  9315. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9316. /**
  9317. * TSL function for creating an object 3D node that represents the object's radius.
  9318. *
  9319. * @tsl
  9320. * @function
  9321. * @param {?Object3D} [object3d] - The 3D object.
  9322. * @returns {Object3DNode<float>}
  9323. */
  9324. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9325. /**
  9326. * This type of node is a specialized version of `Object3DNode`
  9327. * with larger set of model related metrics. Unlike `Object3DNode`,
  9328. * `ModelNode` extracts the reference to the 3D object from the
  9329. * current node frame state.
  9330. *
  9331. * @augments Object3DNode
  9332. */
  9333. class ModelNode extends Object3DNode {
  9334. static get type() {
  9335. return 'ModelNode';
  9336. }
  9337. /**
  9338. * Constructs a new object model node.
  9339. *
  9340. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9341. */
  9342. constructor( scope ) {
  9343. super( scope );
  9344. }
  9345. /**
  9346. * Extracts the model reference from the frame state and then
  9347. * updates the uniform value depending on the scope.
  9348. *
  9349. * @param {NodeFrame} frame - The current node frame.
  9350. */
  9351. update( frame ) {
  9352. this.object3d = frame.object;
  9353. super.update( frame );
  9354. }
  9355. }
  9356. /**
  9357. * TSL object that represents the object's direction in world space.
  9358. *
  9359. * @tsl
  9360. * @type {ModelNode<vec3>}
  9361. */
  9362. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9363. /**
  9364. * TSL object that represents the object's world matrix.
  9365. *
  9366. * @tsl
  9367. * @type {ModelNode<mat4>}
  9368. */
  9369. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9370. /**
  9371. * TSL object that represents the object's position in world space.
  9372. *
  9373. * @tsl
  9374. * @type {ModelNode<vec3>}
  9375. */
  9376. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9377. /**
  9378. * TSL object that represents the object's scale in world space.
  9379. *
  9380. * @tsl
  9381. * @type {ModelNode<vec3>}
  9382. */
  9383. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9384. /**
  9385. * TSL object that represents the object's position in view/camera space.
  9386. *
  9387. * @tsl
  9388. * @type {ModelNode<vec3>}
  9389. */
  9390. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9391. /**
  9392. * TSL object that represents the object's radius.
  9393. *
  9394. * @tsl
  9395. * @type {ModelNode<float>}
  9396. */
  9397. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9398. /**
  9399. * TSL object that represents the object's normal matrix.
  9400. *
  9401. * @tsl
  9402. * @type {UniformNode<mat3>}
  9403. */
  9404. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9405. /**
  9406. * TSL object that represents the object's inverse world matrix.
  9407. *
  9408. * @tsl
  9409. * @type {UniformNode<mat4>}
  9410. */
  9411. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9412. /**
  9413. * TSL object that represents the object's model view matrix.
  9414. *
  9415. * @tsl
  9416. * @type {Node<mat4>}
  9417. */
  9418. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9419. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9420. } ).once() )().toVar( 'modelViewMatrix' );
  9421. // GPU Precision
  9422. /**
  9423. * TSL object that represents the object's model view in `mediump` precision.
  9424. *
  9425. * @tsl
  9426. * @type {Node<mat4>}
  9427. */
  9428. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9429. // CPU Precision
  9430. /**
  9431. * TSL object that represents the object's model view in `highp` precision
  9432. * which is achieved by computing the matrix in JS and not in the shader.
  9433. *
  9434. * @tsl
  9435. * @type {Node<mat4>}
  9436. */
  9437. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9438. builder.context.isHighPrecisionModelViewMatrix = true;
  9439. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9440. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9441. } );
  9442. } ).once() )().toVar( 'highpModelViewMatrix' );
  9443. /**
  9444. * TSL object that represents the object's model normal view in `highp` precision
  9445. * which is achieved by computing the matrix in JS and not in the shader.
  9446. *
  9447. * @tsl
  9448. * @type {Node<mat3>}
  9449. */
  9450. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9451. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9452. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9453. if ( isHighPrecisionModelViewMatrix !== true ) {
  9454. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9455. }
  9456. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9457. } );
  9458. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9459. /**
  9460. * TSL object that represents the position attribute of the current rendered object.
  9461. *
  9462. * @tsl
  9463. * @type {AttributeNode<vec3>}
  9464. */
  9465. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9466. /**
  9467. * TSL object that represents the vertex position in local space of the current rendered object.
  9468. *
  9469. * @tsl
  9470. * @type {AttributeNode<vec3>}
  9471. */
  9472. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9473. /**
  9474. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9475. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9476. *
  9477. * @tsl
  9478. * @type {AttributeNode<vec3>}
  9479. */
  9480. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9481. /**
  9482. * TSL object that represents the vertex position in world space of the current rendered object.
  9483. *
  9484. * @tsl
  9485. * @type {VaryingNode<vec3>}
  9486. */
  9487. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9488. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9489. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9490. /**
  9491. * TSL object that represents the position world direction of the current rendered object.
  9492. *
  9493. * @tsl
  9494. * @type {Node<vec3>}
  9495. */
  9496. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9497. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9498. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9499. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9500. /**
  9501. * TSL object that represents the vertex position in view space of the current rendered object.
  9502. *
  9503. * @tsl
  9504. * @type {VaryingNode<vec3>}
  9505. */
  9506. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9507. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9508. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9509. /**
  9510. * TSL object that represents the position view direction of the current rendered object.
  9511. *
  9512. * @tsl
  9513. * @type {VaryingNode<vec3>}
  9514. */
  9515. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  9516. /**
  9517. * This node can be used to evaluate whether a primitive is front or back facing.
  9518. *
  9519. * @augments Node
  9520. */
  9521. class FrontFacingNode extends Node {
  9522. static get type() {
  9523. return 'FrontFacingNode';
  9524. }
  9525. /**
  9526. * Constructs a new front facing node.
  9527. */
  9528. constructor() {
  9529. super( 'bool' );
  9530. /**
  9531. * This flag can be used for type testing.
  9532. *
  9533. * @type {boolean}
  9534. * @readonly
  9535. * @default true
  9536. */
  9537. this.isFrontFacingNode = true;
  9538. }
  9539. generate( builder ) {
  9540. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9541. //
  9542. const { material } = builder;
  9543. if ( material.side === BackSide ) {
  9544. return 'false';
  9545. }
  9546. return builder.getFrontFacing();
  9547. }
  9548. }
  9549. /**
  9550. * TSL object that represents whether a primitive is front or back facing
  9551. *
  9552. * @tsl
  9553. * @type {FrontFacingNode<bool>}
  9554. */
  9555. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9556. /**
  9557. * TSL object that represents the front facing status as a number instead of a bool.
  9558. * `1` means front facing, `-1` means back facing.
  9559. *
  9560. * @tsl
  9561. * @type {Node<float>}
  9562. */
  9563. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9564. /**
  9565. * Converts a direction vector to a face direction vector based on the material's side.
  9566. *
  9567. * If the material is set to `BackSide`, the direction is inverted.
  9568. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9569. *
  9570. * @tsl
  9571. * @param {Node<vec3>} direction - The direction vector to convert.
  9572. * @returns {Node<vec3>} The converted direction vector.
  9573. */
  9574. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9575. const side = material.side;
  9576. if ( side === BackSide ) {
  9577. direction = direction.mul( -1 );
  9578. } else if ( side === DoubleSide ) {
  9579. direction = direction.mul( faceDirection );
  9580. }
  9581. return direction;
  9582. } );
  9583. /**
  9584. * TSL object that represents the normal attribute of the current rendered object in local space.
  9585. *
  9586. * @tsl
  9587. * @type {Node<vec3>}
  9588. */
  9589. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9590. /**
  9591. * TSL object that represents the vertex normal of the current rendered object in local space.
  9592. *
  9593. * @tsl
  9594. * @type {Node<vec3>}
  9595. */
  9596. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9597. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9598. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9599. return vec3( 0, 1, 0 );
  9600. }
  9601. return normalGeometry;
  9602. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9603. /**
  9604. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9605. *
  9606. * @tsl
  9607. * @type {Node<vec3>}
  9608. */
  9609. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9610. /**
  9611. * TSL object that represents the vertex normal of the current rendered object in view space.
  9612. *
  9613. * @tsl
  9614. * @type {Node<vec3>}
  9615. */
  9616. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9617. let node;
  9618. if ( builder.material.flatShading === true ) {
  9619. node = normalFlat;
  9620. } else {
  9621. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9622. }
  9623. return node;
  9624. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9625. /**
  9626. * TSL object that represents the vertex normal of the current rendered object in world space.
  9627. *
  9628. * @tsl
  9629. * @type {Node<vec3>}
  9630. */
  9631. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9632. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9633. if ( builder.material.flatShading !== true ) {
  9634. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9635. }
  9636. return normal.normalize().toVar( 'normalWorldGeometry' );
  9637. }, 'vec3' ).once() )();
  9638. /**
  9639. * TSL object that represents the vertex normal of the current rendered object in view space.
  9640. *
  9641. * @tsl
  9642. * @type {Node<vec3>}
  9643. */
  9644. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9645. let node;
  9646. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9647. node = normalViewGeometry;
  9648. if ( material.flatShading !== true ) {
  9649. node = directionToFaceDirection( node );
  9650. }
  9651. } else {
  9652. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9653. node = context.setupNormal().context( { getUV: null } );
  9654. }
  9655. return node;
  9656. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9657. /**
  9658. * TSL object that represents the vertex normal of the current rendered object in world space.
  9659. *
  9660. * @tsl
  9661. * @type {Node<vec3>}
  9662. */
  9663. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9664. /**
  9665. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9666. *
  9667. * @tsl
  9668. * @type {Node<vec3>}
  9669. */
  9670. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9671. let node;
  9672. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9673. node = normalView;
  9674. } else {
  9675. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9676. node = context.setupClearcoatNormal().context( { getUV: null } );
  9677. }
  9678. return node;
  9679. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9680. /**
  9681. * Transforms the normal with the given matrix.
  9682. *
  9683. * @tsl
  9684. * @function
  9685. * @param {Node<vec3>} normal - The normal.
  9686. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9687. * @return {Node<vec3>} The transformed normal.
  9688. */
  9689. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9690. const m = mat3( matrix );
  9691. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9692. return m.mul( transformedNormal ).xyz;
  9693. } );
  9694. /**
  9695. * Transforms the given normal from local to view space.
  9696. *
  9697. * @tsl
  9698. * @function
  9699. * @param {Node<vec3>} normal - The normal.
  9700. * @param {NodeBuilder} builder - The current node builder.
  9701. * @return {Node<vec3>} The transformed normal.
  9702. */
  9703. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9704. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9705. if ( modelNormalViewMatrix !== null ) {
  9706. return modelNormalViewMatrix.transformDirection( normal );
  9707. }
  9708. //
  9709. const transformedNormal = modelNormalMatrix.mul( normal );
  9710. return cameraViewMatrix.transformDirection( transformedNormal );
  9711. } );
  9712. // Deprecated
  9713. /**
  9714. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9715. *
  9716. * @tsl
  9717. * @type {Node<vec3>}
  9718. * @deprecated since r178. Use `normalView` instead.
  9719. */
  9720. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9721. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9722. return normalView;
  9723. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9724. /**
  9725. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9726. *
  9727. * @tsl
  9728. * @type {Node<vec3>}
  9729. * @deprecated since r178. Use `normalWorld` instead.
  9730. */
  9731. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9732. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9733. return normalWorld;
  9734. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9735. /**
  9736. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9737. *
  9738. * @tsl
  9739. * @type {Node<vec3>}
  9740. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9741. */
  9742. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9743. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9744. return clearcoatNormalView;
  9745. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9746. const _e1$1 = /*@__PURE__*/ new Euler();
  9747. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9748. /**
  9749. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9750. *
  9751. * @tsl
  9752. * @type {UniformNode<float>}
  9753. */
  9754. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9755. /**
  9756. * TSL object that represents the intensity of environment maps of PBR materials.
  9757. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9758. *
  9759. * @tsl
  9760. * @type {Node<float>}
  9761. */
  9762. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9763. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9764. } );
  9765. /**
  9766. * TSL object that represents the rotation of environment maps.
  9767. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9768. * rotation of `scene.environment` instead.
  9769. *
  9770. * @tsl
  9771. * @type {Node<mat4>}
  9772. */
  9773. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9774. return frame.material;
  9775. } ).onObjectUpdate( function ( { material, scene } ) {
  9776. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9777. if ( rotation ) {
  9778. _e1$1.copy( rotation );
  9779. _m1$1.makeRotationFromEuler( _e1$1 );
  9780. } else {
  9781. _m1$1.identity();
  9782. }
  9783. return _m1$1;
  9784. } );
  9785. /**
  9786. * The reflect vector in view space.
  9787. *
  9788. * @tsl
  9789. * @type {Node<vec3>}
  9790. */
  9791. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9792. /**
  9793. * The refract vector in view space.
  9794. *
  9795. * @tsl
  9796. * @type {Node<vec3>}
  9797. */
  9798. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  9799. /**
  9800. * Used for sampling cube maps when using cube reflection mapping.
  9801. *
  9802. * @tsl
  9803. * @type {Node<vec3>}
  9804. */
  9805. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9806. /**
  9807. * Used for sampling cube maps when using cube refraction mapping.
  9808. *
  9809. * @tsl
  9810. * @type {Node<vec3>}
  9811. */
  9812. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9813. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  9814. /**
  9815. * This type of uniform node represents a cube texture.
  9816. *
  9817. * @augments TextureNode
  9818. */
  9819. class CubeTextureNode extends TextureNode {
  9820. static get type() {
  9821. return 'CubeTextureNode';
  9822. }
  9823. /**
  9824. * Constructs a new cube texture node.
  9825. *
  9826. * @param {CubeTexture} value - The cube texture.
  9827. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9828. * @param {?Node<int>} [levelNode=null] - The level node.
  9829. * @param {?Node<float>} [biasNode=null] - The bias node.
  9830. */
  9831. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  9832. super( value, uvNode, levelNode, biasNode );
  9833. /**
  9834. * This flag can be used for type testing.
  9835. *
  9836. * @type {boolean}
  9837. * @readonly
  9838. * @default true
  9839. */
  9840. this.isCubeTextureNode = true;
  9841. }
  9842. /**
  9843. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  9844. *
  9845. * @param {NodeBuilder} builder - The current node builder.
  9846. * @return {string} The input type.
  9847. */
  9848. getInputType( /*builder*/ ) {
  9849. return 'cubeTexture';
  9850. }
  9851. /**
  9852. * Returns a default uvs based on the mapping type of the cube texture.
  9853. *
  9854. * @return {Node<vec3>} The default uv attribute.
  9855. */
  9856. getDefaultUV() {
  9857. const texture = this.value;
  9858. if ( texture.mapping === CubeReflectionMapping ) {
  9859. return reflectVector;
  9860. } else if ( texture.mapping === CubeRefractionMapping ) {
  9861. return refractVector;
  9862. } else {
  9863. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  9864. return vec3( 0, 0, 0 );
  9865. }
  9866. }
  9867. /**
  9868. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  9869. * for cube textures. The uv transformation matrix is not applied to cube textures.
  9870. *
  9871. * @param {boolean} value - The update toggle.
  9872. */
  9873. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  9874. /**
  9875. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  9876. * to modify the uv node for correct sampling.
  9877. *
  9878. * @param {NodeBuilder} builder - The current node builder.
  9879. * @param {Node} uvNode - The uv node to setup.
  9880. * @return {Node} The updated uv node.
  9881. */
  9882. setupUV( builder, uvNode ) {
  9883. const texture = this.value;
  9884. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  9885. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9886. }
  9887. return materialEnvRotation.mul( uvNode );
  9888. }
  9889. /**
  9890. * Generates the uv code snippet.
  9891. *
  9892. * @param {NodeBuilder} builder - The current node builder.
  9893. * @param {Node} cubeUV - The uv node to generate code for.
  9894. * @return {string} The generated code snippet.
  9895. */
  9896. generateUV( builder, cubeUV ) {
  9897. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  9898. }
  9899. }
  9900. /**
  9901. * TSL function for creating a cube texture node.
  9902. *
  9903. * @tsl
  9904. * @function
  9905. * @param {CubeTexture} value - The cube texture.
  9906. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9907. * @param {?Node<int>} [levelNode=null] - The level node.
  9908. * @param {?Node<float>} [biasNode=null] - The bias node.
  9909. * @returns {CubeTextureNode}
  9910. */
  9911. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  9912. /**
  9913. * TSL function for creating a cube texture uniform node.
  9914. *
  9915. * @tsl
  9916. * @function
  9917. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  9918. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9919. * @param {?Node<int>} [levelNode=null] - The level node.
  9920. * @param {?Node<float>} [biasNode=null] - The bias node.
  9921. * @returns {CubeTextureNode}
  9922. */
  9923. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  9924. let textureNode;
  9925. if ( value && value.isCubeTextureNode === true ) {
  9926. textureNode = nodeObject( value.clone() );
  9927. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  9928. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9929. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9930. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9931. } else {
  9932. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  9933. }
  9934. return textureNode;
  9935. };
  9936. /**
  9937. * TSL function for creating a uniform cube texture node.
  9938. *
  9939. * @tsl
  9940. * @function
  9941. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  9942. * @returns {CubeTextureNode}
  9943. */
  9944. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  9945. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  9946. /**
  9947. * This class is only relevant if the referenced property is array-like.
  9948. * In this case, `ReferenceElementNode` allows to refer to a specific
  9949. * element inside the data structure via an index.
  9950. *
  9951. * @augments ArrayElementNode
  9952. */
  9953. class ReferenceElementNode extends ArrayElementNode {
  9954. static get type() {
  9955. return 'ReferenceElementNode';
  9956. }
  9957. /**
  9958. * Constructs a new reference element node.
  9959. *
  9960. * @param {?ReferenceNode} referenceNode - The reference node.
  9961. * @param {Node} indexNode - The index node that defines the element access.
  9962. */
  9963. constructor( referenceNode, indexNode ) {
  9964. super( referenceNode, indexNode );
  9965. /**
  9966. * Similar to {@link ReferenceNode#reference}, an additional
  9967. * property references to the current node.
  9968. *
  9969. * @type {?ReferenceNode}
  9970. * @default null
  9971. */
  9972. this.referenceNode = referenceNode;
  9973. /**
  9974. * This flag can be used for type testing.
  9975. *
  9976. * @type {boolean}
  9977. * @readonly
  9978. * @default true
  9979. */
  9980. this.isReferenceElementNode = true;
  9981. }
  9982. /**
  9983. * This method is overwritten since the node type is inferred from
  9984. * the uniform type of the reference node.
  9985. *
  9986. * @return {string} The node type.
  9987. */
  9988. getNodeType() {
  9989. return this.referenceNode.uniformType;
  9990. }
  9991. generate( builder ) {
  9992. const snippet = super.generate( builder );
  9993. const arrayType = this.referenceNode.getNodeType();
  9994. const elementType = this.getNodeType();
  9995. return builder.format( snippet, arrayType, elementType );
  9996. }
  9997. }
  9998. /**
  9999. * This type of node establishes a reference to a property of another object.
  10000. * In this way, the value of the node is automatically linked to the value of
  10001. * referenced object. Reference nodes internally represent the linked value
  10002. * as a uniform.
  10003. *
  10004. * @augments Node
  10005. */
  10006. class ReferenceNode extends Node {
  10007. static get type() {
  10008. return 'ReferenceNode';
  10009. }
  10010. /**
  10011. * Constructs a new reference node.
  10012. *
  10013. * @param {string} property - The name of the property the node refers to.
  10014. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  10015. * @param {?Object} [object=null] - The object the property belongs to.
  10016. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  10017. */
  10018. constructor( property, uniformType, object = null, count = null ) {
  10019. super();
  10020. /**
  10021. * The name of the property the node refers to.
  10022. *
  10023. * @type {string}
  10024. */
  10025. this.property = property;
  10026. /**
  10027. * The uniform type that should be used to represent the property value.
  10028. *
  10029. * @type {string}
  10030. */
  10031. this.uniformType = uniformType;
  10032. /**
  10033. * The object the property belongs to.
  10034. *
  10035. * @type {?Object}
  10036. * @default null
  10037. */
  10038. this.object = object;
  10039. /**
  10040. * When the linked property is an array, this parameter defines its length.
  10041. *
  10042. * @type {?number}
  10043. * @default null
  10044. */
  10045. this.count = count;
  10046. /**
  10047. * The property name might have dots so nested properties can be referred.
  10048. * The hierarchy of the names is stored inside this array.
  10049. *
  10050. * @type {Array<string>}
  10051. */
  10052. this.properties = property.split( '.' );
  10053. /**
  10054. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  10055. * since the final reference might be updated from calling code.
  10056. *
  10057. * @type {?Object}
  10058. * @default null
  10059. */
  10060. this.reference = object;
  10061. /**
  10062. * The uniform node that holds the value of the reference node.
  10063. *
  10064. * @type {UniformNode}
  10065. * @default null
  10066. */
  10067. this.node = null;
  10068. /**
  10069. * The uniform group of the internal uniform.
  10070. *
  10071. * @type {UniformGroupNode}
  10072. * @default null
  10073. */
  10074. this.group = null;
  10075. /**
  10076. * An optional label of the internal uniform node.
  10077. *
  10078. * @type {?string}
  10079. * @default null
  10080. */
  10081. this.name = null;
  10082. /**
  10083. * Overwritten since reference nodes are updated per object.
  10084. *
  10085. * @type {string}
  10086. * @default 'object'
  10087. */
  10088. this.updateType = NodeUpdateType.OBJECT;
  10089. }
  10090. /**
  10091. * When the referred property is array-like, this method can be used
  10092. * to access elements via an index node.
  10093. *
  10094. * @param {IndexNode} indexNode - indexNode.
  10095. * @return {ReferenceElementNode} A reference to an element.
  10096. */
  10097. element( indexNode ) {
  10098. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  10099. }
  10100. /**
  10101. * Sets the uniform group for this reference node.
  10102. *
  10103. * @param {UniformGroupNode} group - The uniform group to set.
  10104. * @return {ReferenceNode} A reference to this node.
  10105. */
  10106. setGroup( group ) {
  10107. this.group = group;
  10108. return this;
  10109. }
  10110. /**
  10111. * Sets the name for the internal uniform.
  10112. *
  10113. * @param {string} name - The label to set.
  10114. * @return {ReferenceNode} A reference to this node.
  10115. */
  10116. setName( name ) {
  10117. this.name = name;
  10118. return this;
  10119. }
  10120. /**
  10121. * Sets the label for the internal uniform.
  10122. *
  10123. * @deprecated
  10124. * @param {string} name - The label to set.
  10125. * @return {ReferenceNode} A reference to this node.
  10126. */
  10127. label( name ) {
  10128. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  10129. return this.setName( name );
  10130. }
  10131. /**
  10132. * Sets the node type which automatically defines the internal
  10133. * uniform type.
  10134. *
  10135. * @param {string} uniformType - The type to set.
  10136. */
  10137. setNodeType( uniformType ) {
  10138. let node = null;
  10139. if ( this.count !== null ) {
  10140. node = buffer( null, uniformType, this.count );
  10141. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  10142. node = uniformArray( null, uniformType );
  10143. } else if ( uniformType === 'texture' ) {
  10144. node = texture( null );
  10145. } else if ( uniformType === 'cubeTexture' ) {
  10146. node = cubeTexture( null );
  10147. } else {
  10148. node = uniform( null, uniformType );
  10149. }
  10150. if ( this.group !== null ) {
  10151. node.setGroup( this.group );
  10152. }
  10153. if ( this.name !== null ) node.setName( this.name );
  10154. this.node = node;
  10155. }
  10156. /**
  10157. * This method is overwritten since the node type is inferred from
  10158. * the type of the reference node.
  10159. *
  10160. * @param {NodeBuilder} builder - The current node builder.
  10161. * @return {string} The node type.
  10162. */
  10163. getNodeType( builder ) {
  10164. if ( this.node === null ) {
  10165. this.updateReference( builder );
  10166. this.updateValue();
  10167. }
  10168. return this.node.getNodeType( builder );
  10169. }
  10170. /**
  10171. * Returns the property value from the given referred object.
  10172. *
  10173. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10174. * @return {any} The value.
  10175. */
  10176. getValueFromReference( object = this.reference ) {
  10177. const { properties } = this;
  10178. let value = object[ properties[ 0 ] ];
  10179. for ( let i = 1; i < properties.length; i ++ ) {
  10180. value = value[ properties[ i ] ];
  10181. }
  10182. return value;
  10183. }
  10184. /**
  10185. * Allows to update the reference based on the given state. The state is only
  10186. * evaluated {@link ReferenceNode#object} is not set.
  10187. *
  10188. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10189. * @return {Object} The updated reference.
  10190. */
  10191. updateReference( state ) {
  10192. this.reference = this.object !== null ? this.object : state.object;
  10193. return this.reference;
  10194. }
  10195. /**
  10196. * The output of the reference node is the internal uniform node.
  10197. *
  10198. * @param {NodeBuilder} builder - The current node builder.
  10199. * @return {UniformNode} The output node.
  10200. */
  10201. setup( /* builder */ ) {
  10202. this.updateValue();
  10203. return this.node;
  10204. }
  10205. /**
  10206. * Overwritten to update the internal uniform value.
  10207. *
  10208. * @param {NodeFrame} frame - A reference to the current node frame.
  10209. */
  10210. update( /*frame*/ ) {
  10211. this.updateValue();
  10212. }
  10213. /**
  10214. * Retrieves the value from the referred object property and uses it
  10215. * to updated the internal uniform.
  10216. */
  10217. updateValue() {
  10218. if ( this.node === null ) this.setNodeType( this.uniformType );
  10219. const value = this.getValueFromReference();
  10220. if ( Array.isArray( value ) ) {
  10221. this.node.array = value;
  10222. } else {
  10223. this.node.value = value;
  10224. }
  10225. }
  10226. }
  10227. /**
  10228. * TSL function for creating a reference node.
  10229. *
  10230. * @tsl
  10231. * @function
  10232. * @param {string} name - The name of the property the node refers to.
  10233. * @param {string} type - The uniform type that should be used to represent the property value.
  10234. * @param {?Object} [object] - The object the property belongs to.
  10235. * @returns {ReferenceNode}
  10236. */
  10237. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10238. /**
  10239. * TSL function for creating a reference node. Use this function if you want need a reference
  10240. * to an array-like property that should be represented as a uniform buffer.
  10241. *
  10242. * @tsl
  10243. * @function
  10244. * @param {string} name - The name of the property the node refers to.
  10245. * @param {string} type - The uniform type that should be used to represent the property value.
  10246. * @param {number} count - The number of value inside the array-like object.
  10247. * @param {Object} object - An array-like object the property belongs to.
  10248. * @returns {ReferenceNode}
  10249. */
  10250. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10251. /**
  10252. * This node is a special type of reference node which is intended
  10253. * for linking material properties with node values.
  10254. * ```js
  10255. * const opacityNode = materialReference( 'opacity', 'float', material );
  10256. * ```
  10257. * When changing `material.opacity`, the node value of `opacityNode` will
  10258. * automatically be updated.
  10259. *
  10260. * @augments ReferenceNode
  10261. */
  10262. class MaterialReferenceNode extends ReferenceNode {
  10263. static get type() {
  10264. return 'MaterialReferenceNode';
  10265. }
  10266. /**
  10267. * Constructs a new material reference node.
  10268. *
  10269. * @param {string} property - The name of the property the node refers to.
  10270. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10271. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10272. * the node refers to the material of the current rendered object.
  10273. */
  10274. constructor( property, inputType, material = null ) {
  10275. super( property, inputType, material );
  10276. /**
  10277. * The material the property belongs to. When no material is set,
  10278. * the node refers to the material of the current rendered object.
  10279. *
  10280. * @type {?Material}
  10281. * @default null
  10282. */
  10283. this.material = material;
  10284. /**
  10285. * This flag can be used for type testing.
  10286. *
  10287. * @type {boolean}
  10288. * @readonly
  10289. * @default true
  10290. */
  10291. this.isMaterialReferenceNode = true;
  10292. }
  10293. /**
  10294. * Updates the reference based on the given state. The state is only evaluated
  10295. * {@link MaterialReferenceNode#material} is not set.
  10296. *
  10297. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10298. * @return {Object} The updated reference.
  10299. */
  10300. updateReference( state ) {
  10301. this.reference = this.material !== null ? this.material : state.material;
  10302. return this.reference;
  10303. }
  10304. }
  10305. /**
  10306. * TSL function for creating a material reference node.
  10307. *
  10308. * @tsl
  10309. * @function
  10310. * @param {string} name - The name of the property the node refers to.
  10311. * @param {string} type - The uniform type that should be used to represent the property value.
  10312. * @param {?Material} [material=null] - The material the property belongs to.
  10313. * When no material is set, the node refers to the material of the current rendered object.
  10314. * @returns {MaterialReferenceNode}
  10315. */
  10316. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10317. // Normal Mapping Without Precomputed Tangents
  10318. // http://www.thetenthplanet.de/archives/1180
  10319. const uv = uv$1();
  10320. const q0 = positionView.dFdx();
  10321. const q1 = positionView.dFdy();
  10322. const st0 = uv.dFdx();
  10323. const st1 = uv.dFdy();
  10324. const N = normalView;
  10325. const q1perp = q1.cross( N );
  10326. const q0perp = N.cross( q0 );
  10327. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10328. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10329. const det = T.dot( T ).max( B.dot( B ) );
  10330. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10331. /**
  10332. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10333. * Useful for normal mapping without precomputed tangents.
  10334. *
  10335. * Reference: http://www.thetenthplanet.de/archives/1180
  10336. *
  10337. * @tsl
  10338. * @type {Node<vec3>}
  10339. */
  10340. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10341. /**
  10342. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10343. * Complements the tangentViewFrame for constructing the tangent space basis.
  10344. *
  10345. * Reference: http://www.thetenthplanet.de/archives/1180
  10346. *
  10347. * @tsl
  10348. * @type {Node<vec3>}
  10349. */
  10350. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10351. /**
  10352. * TSL object that represents the tangent attribute of the current rendered object.
  10353. *
  10354. * @tsl
  10355. * @type {Node<vec4>}
  10356. */
  10357. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10358. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10359. builder.geometry.computeTangents();
  10360. }
  10361. return attribute( 'tangent', 'vec4' );
  10362. } )();
  10363. /**
  10364. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10365. *
  10366. * @tsl
  10367. * @type {Node<vec3>}
  10368. */
  10369. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10370. /**
  10371. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10372. *
  10373. * @tsl
  10374. * @type {Node<vec3>}
  10375. */
  10376. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10377. let node;
  10378. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10379. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10380. } else {
  10381. node = tangentViewFrame;
  10382. }
  10383. if ( material.flatShading !== true ) {
  10384. node = directionToFaceDirection( node );
  10385. }
  10386. return node;
  10387. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10388. /**
  10389. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10390. *
  10391. * @tsl
  10392. * @type {Node<vec3>}
  10393. */
  10394. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10395. /**
  10396. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10397. *
  10398. * @tsl
  10399. * @private
  10400. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10401. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10402. * @returns {Node<vec3>} The bitangent node.
  10403. */
  10404. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10405. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10406. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10407. bitangent = bitangent.toVarying( varyingName );
  10408. }
  10409. return bitangent;
  10410. } ).once( [ 'NORMAL' ] );
  10411. /**
  10412. * TSL object that represents the bitangent attribute of the current rendered object.
  10413. *
  10414. * @tsl
  10415. * @type {Node<vec3>}
  10416. */
  10417. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10418. /**
  10419. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10420. *
  10421. * @tsl
  10422. * @type {Node<vec3>}
  10423. */
  10424. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10425. /**
  10426. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10427. *
  10428. * @tsl
  10429. * @type {Node<vec3>}
  10430. */
  10431. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10432. let node;
  10433. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10434. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10435. } else {
  10436. node = bitangentViewFrame;
  10437. }
  10438. if ( material.flatShading !== true ) {
  10439. node = directionToFaceDirection( node );
  10440. }
  10441. return node;
  10442. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10443. /**
  10444. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10445. *
  10446. * @tsl
  10447. * @type {Node<vec3>}
  10448. */
  10449. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10450. /**
  10451. * TSL object that represents the TBN matrix in view space.
  10452. *
  10453. * @tsl
  10454. * @type {Node<mat3>}
  10455. */
  10456. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10457. /**
  10458. * TSL object that represents the parallax direction.
  10459. *
  10460. * @tsl
  10461. * @type {Node<mat3>}
  10462. */
  10463. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10464. /**
  10465. * TSL function for computing parallax uv coordinates.
  10466. *
  10467. * @tsl
  10468. * @function
  10469. * @param {Node<vec2>} uv - A uv node.
  10470. * @param {Node<vec2>} scale - A scale node.
  10471. * @returns {Node<vec2>} Parallax uv coordinates.
  10472. */
  10473. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10474. /**
  10475. * TSL function for computing bent normals.
  10476. *
  10477. * @tsl
  10478. * @function
  10479. * @returns {Node<vec3>} Bent normals.
  10480. */
  10481. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10482. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10483. let bentNormal = anisotropyB.cross( positionViewDirection );
  10484. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10485. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10486. return bentNormal;
  10487. } ).once() )();
  10488. /**
  10489. * This class can be used for applying normals maps to materials.
  10490. *
  10491. * ```js
  10492. * material.normalNode = normalMap( texture( normalTex ) );
  10493. * ```
  10494. *
  10495. * @augments TempNode
  10496. */
  10497. class NormalMapNode extends TempNode {
  10498. static get type() {
  10499. return 'NormalMapNode';
  10500. }
  10501. /**
  10502. * Constructs a new normal map node.
  10503. *
  10504. * @param {Node<vec3>} node - Represents the normal map data.
  10505. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10506. */
  10507. constructor( node, scaleNode = null ) {
  10508. super( 'vec3' );
  10509. /**
  10510. * Represents the normal map data.
  10511. *
  10512. * @type {Node<vec3>}
  10513. */
  10514. this.node = node;
  10515. /**
  10516. * Controls the intensity of the effect.
  10517. *
  10518. * @type {?Node<vec2>}
  10519. * @default null
  10520. */
  10521. this.scaleNode = scaleNode;
  10522. /**
  10523. * The normal map type.
  10524. *
  10525. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10526. * @default TangentSpaceNormalMap
  10527. */
  10528. this.normalMapType = TangentSpaceNormalMap;
  10529. }
  10530. setup( { material } ) {
  10531. const { normalMapType, scaleNode } = this;
  10532. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10533. if ( scaleNode !== null ) {
  10534. let scale = scaleNode;
  10535. if ( material.flatShading === true ) {
  10536. scale = directionToFaceDirection( scale );
  10537. }
  10538. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10539. }
  10540. let output = null;
  10541. if ( normalMapType === ObjectSpaceNormalMap ) {
  10542. output = transformNormalToView( normalMap );
  10543. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10544. output = TBNViewMatrix.mul( normalMap ).normalize();
  10545. } else {
  10546. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10547. output = normalView; // Fallback to default normal view
  10548. }
  10549. return output;
  10550. }
  10551. }
  10552. /**
  10553. * TSL function for creating a normal map node.
  10554. *
  10555. * @tsl
  10556. * @function
  10557. * @param {Node<vec3>} node - Represents the normal map data.
  10558. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10559. * @returns {NormalMapNode}
  10560. */
  10561. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10562. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10563. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10564. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10565. // It's used to preserve the same TextureNode instance
  10566. const sampleTexture = ( callback ) => textureNode.isolate().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10567. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10568. return vec2(
  10569. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10570. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10571. ).mul( bumpScale );
  10572. } );
  10573. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10574. const perturbNormalArb = Fn( ( inputs ) => {
  10575. const { surf_pos, surf_norm, dHdxy } = inputs;
  10576. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10577. const vSigmaX = surf_pos.dFdx().normalize();
  10578. const vSigmaY = surf_pos.dFdy().normalize();
  10579. const vN = surf_norm; // normalized
  10580. const R1 = vSigmaY.cross( vN );
  10581. const R2 = vN.cross( vSigmaX );
  10582. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10583. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10584. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10585. } );
  10586. /**
  10587. * This class can be used for applying bump maps to materials.
  10588. *
  10589. * ```js
  10590. * material.normalNode = bumpMap( texture( bumpTex ) );
  10591. * ```
  10592. *
  10593. * @augments TempNode
  10594. */
  10595. class BumpMapNode extends TempNode {
  10596. static get type() {
  10597. return 'BumpMapNode';
  10598. }
  10599. /**
  10600. * Constructs a new bump map node.
  10601. *
  10602. * @param {Node<float>} textureNode - Represents the bump map data.
  10603. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10604. */
  10605. constructor( textureNode, scaleNode = null ) {
  10606. super( 'vec3' );
  10607. /**
  10608. * Represents the bump map data.
  10609. *
  10610. * @type {Node<float>}
  10611. */
  10612. this.textureNode = textureNode;
  10613. /**
  10614. * Controls the intensity of the bump effect.
  10615. *
  10616. * @type {?Node<float>}
  10617. * @default null
  10618. */
  10619. this.scaleNode = scaleNode;
  10620. }
  10621. setup() {
  10622. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10623. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10624. return perturbNormalArb( {
  10625. surf_pos: positionView,
  10626. surf_norm: normalView,
  10627. dHdxy
  10628. } );
  10629. }
  10630. }
  10631. /**
  10632. * TSL function for creating a bump map node.
  10633. *
  10634. * @tsl
  10635. * @function
  10636. * @param {Node<float>} textureNode - Represents the bump map data.
  10637. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10638. * @returns {BumpMapNode}
  10639. */
  10640. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10641. const _propertyCache = new Map();
  10642. /**
  10643. * This class should simplify the node access to material properties.
  10644. * It internal uses reference nodes to make sure changes to material
  10645. * properties are automatically reflected to predefined TSL objects
  10646. * like e.g. `materialColor`.
  10647. *
  10648. * @augments Node
  10649. */
  10650. class MaterialNode extends Node {
  10651. static get type() {
  10652. return 'MaterialNode';
  10653. }
  10654. /**
  10655. * Constructs a new material node.
  10656. *
  10657. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10658. */
  10659. constructor( scope ) {
  10660. super();
  10661. /**
  10662. * The scope defines what material property is referred by the node.
  10663. *
  10664. * @type {string}
  10665. */
  10666. this.scope = scope;
  10667. }
  10668. /**
  10669. * Returns a cached reference node for the given property and type.
  10670. *
  10671. * @param {string} property - The name of the material property.
  10672. * @param {string} type - The uniform type of the property.
  10673. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10674. */
  10675. getCache( property, type ) {
  10676. let node = _propertyCache.get( property );
  10677. if ( node === undefined ) {
  10678. node = materialReference( property, type );
  10679. _propertyCache.set( property, node );
  10680. }
  10681. return node;
  10682. }
  10683. /**
  10684. * Returns a float-typed material reference node for the given property name.
  10685. *
  10686. * @param {string} property - The name of the material property.
  10687. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10688. */
  10689. getFloat( property ) {
  10690. return this.getCache( property, 'float' );
  10691. }
  10692. /**
  10693. * Returns a color-typed material reference node for the given property name.
  10694. *
  10695. * @param {string} property - The name of the material property.
  10696. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10697. */
  10698. getColor( property ) {
  10699. return this.getCache( property, 'color' );
  10700. }
  10701. /**
  10702. * Returns a texture-typed material reference node for the given property name.
  10703. *
  10704. * @param {string} property - The name of the material property.
  10705. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10706. */
  10707. getTexture( property ) {
  10708. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10709. }
  10710. /**
  10711. * The node setup is done depending on the selected scope. Multiple material properties
  10712. * might be grouped into a single node composition if they logically belong together.
  10713. *
  10714. * @param {NodeBuilder} builder - The current node builder.
  10715. * @return {Node} The node representing the selected scope.
  10716. */
  10717. setup( builder ) {
  10718. const material = builder.context.material;
  10719. const scope = this.scope;
  10720. let node = null;
  10721. if ( scope === MaterialNode.COLOR ) {
  10722. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10723. if ( material.map && material.map.isTexture === true ) {
  10724. node = colorNode.mul( this.getTexture( 'map' ) );
  10725. } else {
  10726. node = colorNode;
  10727. }
  10728. } else if ( scope === MaterialNode.OPACITY ) {
  10729. const opacityNode = this.getFloat( scope );
  10730. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10731. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10732. } else {
  10733. node = opacityNode;
  10734. }
  10735. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10736. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10737. node = this.getTexture( 'specular' ).r;
  10738. } else {
  10739. node = float( 1 );
  10740. }
  10741. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10742. const specularIntensityNode = this.getFloat( scope );
  10743. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10744. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10745. } else {
  10746. node = specularIntensityNode;
  10747. }
  10748. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10749. const specularColorNode = this.getColor( scope );
  10750. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10751. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10752. } else {
  10753. node = specularColorNode;
  10754. }
  10755. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10756. const roughnessNode = this.getFloat( scope );
  10757. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10758. node = roughnessNode.mul( this.getTexture( scope ).g );
  10759. } else {
  10760. node = roughnessNode;
  10761. }
  10762. } else if ( scope === MaterialNode.METALNESS ) {
  10763. const metalnessNode = this.getFloat( scope );
  10764. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10765. node = metalnessNode.mul( this.getTexture( scope ).b );
  10766. } else {
  10767. node = metalnessNode;
  10768. }
  10769. } else if ( scope === MaterialNode.EMISSIVE ) {
  10770. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10771. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10772. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10773. node = emissiveNode.mul( this.getTexture( scope ) );
  10774. } else {
  10775. node = emissiveNode;
  10776. }
  10777. } else if ( scope === MaterialNode.NORMAL ) {
  10778. if ( material.normalMap ) {
  10779. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10780. node.normalMapType = material.normalMapType;
  10781. } else if ( material.bumpMap ) {
  10782. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10783. } else {
  10784. node = normalView;
  10785. }
  10786. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10787. const clearcoatNode = this.getFloat( scope );
  10788. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10789. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10790. } else {
  10791. node = clearcoatNode;
  10792. }
  10793. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  10794. const clearcoatRoughnessNode = this.getFloat( scope );
  10795. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  10796. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  10797. } else {
  10798. node = clearcoatRoughnessNode;
  10799. }
  10800. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  10801. if ( material.clearcoatNormalMap ) {
  10802. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  10803. } else {
  10804. node = normalView;
  10805. }
  10806. } else if ( scope === MaterialNode.SHEEN ) {
  10807. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  10808. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  10809. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  10810. } else {
  10811. node = sheenNode;
  10812. }
  10813. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  10814. const sheenRoughnessNode = this.getFloat( scope );
  10815. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  10816. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  10817. } else {
  10818. node = sheenRoughnessNode;
  10819. }
  10820. node = node.clamp( 0.07, 1.0 );
  10821. } else if ( scope === MaterialNode.ANISOTROPY ) {
  10822. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  10823. const anisotropyPolar = this.getTexture( scope );
  10824. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  10825. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  10826. } else {
  10827. node = materialAnisotropyVector;
  10828. }
  10829. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  10830. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  10831. if ( material.iridescenceThicknessMap ) {
  10832. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  10833. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  10834. } else {
  10835. node = iridescenceThicknessMaximum;
  10836. }
  10837. } else if ( scope === MaterialNode.TRANSMISSION ) {
  10838. const transmissionNode = this.getFloat( scope );
  10839. if ( material.transmissionMap ) {
  10840. node = transmissionNode.mul( this.getTexture( scope ).r );
  10841. } else {
  10842. node = transmissionNode;
  10843. }
  10844. } else if ( scope === MaterialNode.THICKNESS ) {
  10845. const thicknessNode = this.getFloat( scope );
  10846. if ( material.thicknessMap ) {
  10847. node = thicknessNode.mul( this.getTexture( scope ).g );
  10848. } else {
  10849. node = thicknessNode;
  10850. }
  10851. } else if ( scope === MaterialNode.IOR ) {
  10852. node = this.getFloat( scope );
  10853. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  10854. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  10855. } else if ( scope === MaterialNode.AO ) {
  10856. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  10857. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  10858. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  10859. } else {
  10860. const outputType = this.getNodeType( builder );
  10861. node = this.getCache( scope, outputType );
  10862. }
  10863. return node;
  10864. }
  10865. }
  10866. MaterialNode.ALPHA_TEST = 'alphaTest';
  10867. MaterialNode.COLOR = 'color';
  10868. MaterialNode.OPACITY = 'opacity';
  10869. MaterialNode.SHININESS = 'shininess';
  10870. MaterialNode.SPECULAR = 'specular';
  10871. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  10872. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  10873. MaterialNode.SPECULAR_COLOR = 'specularColor';
  10874. MaterialNode.REFLECTIVITY = 'reflectivity';
  10875. MaterialNode.ROUGHNESS = 'roughness';
  10876. MaterialNode.METALNESS = 'metalness';
  10877. MaterialNode.NORMAL = 'normal';
  10878. MaterialNode.CLEARCOAT = 'clearcoat';
  10879. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  10880. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  10881. MaterialNode.EMISSIVE = 'emissive';
  10882. MaterialNode.ROTATION = 'rotation';
  10883. MaterialNode.SHEEN = 'sheen';
  10884. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  10885. MaterialNode.ANISOTROPY = 'anisotropy';
  10886. MaterialNode.IRIDESCENCE = 'iridescence';
  10887. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  10888. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  10889. MaterialNode.IOR = 'ior';
  10890. MaterialNode.TRANSMISSION = 'transmission';
  10891. MaterialNode.THICKNESS = 'thickness';
  10892. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  10893. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  10894. MaterialNode.LINE_SCALE = 'scale';
  10895. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  10896. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  10897. MaterialNode.LINE_WIDTH = 'linewidth';
  10898. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  10899. MaterialNode.POINT_SIZE = 'size';
  10900. MaterialNode.DISPERSION = 'dispersion';
  10901. MaterialNode.LIGHT_MAP = 'light';
  10902. MaterialNode.AO = 'ao';
  10903. /**
  10904. * TSL object that represents alpha test of the current material.
  10905. *
  10906. * @tsl
  10907. * @type {Node<float>}
  10908. */
  10909. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  10910. /**
  10911. * TSL object that represents the diffuse color of the current material.
  10912. * The value is composed via `color` * `map`.
  10913. *
  10914. * @tsl
  10915. * @type {Node<vec3>}
  10916. */
  10917. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  10918. /**
  10919. * TSL object that represents the shininess of the current material.
  10920. *
  10921. * @tsl
  10922. * @type {Node<float>}
  10923. */
  10924. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  10925. /**
  10926. * TSL object that represents the emissive color of the current material.
  10927. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  10928. *
  10929. * @tsl
  10930. * @type {Node<vec3>}
  10931. */
  10932. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  10933. /**
  10934. * TSL object that represents the opacity of the current material.
  10935. * The value is composed via `opacity` * `alphaMap`.
  10936. *
  10937. * @tsl
  10938. * @type {Node<float>}
  10939. */
  10940. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  10941. /**
  10942. * TSL object that represents the specular of the current material.
  10943. *
  10944. * @tsl
  10945. * @type {Node<vec3>}
  10946. */
  10947. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  10948. /**
  10949. * TSL object that represents the specular intensity of the current material.
  10950. * The value is composed via `specularIntensity` * `specularMap.a`.
  10951. *
  10952. * @tsl
  10953. * @type {Node<float>}
  10954. */
  10955. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  10956. /**
  10957. * TSL object that represents the specular color of the current material.
  10958. * The value is composed via `specularColor` * `specularMap.rgb`.
  10959. *
  10960. * @tsl
  10961. * @type {Node<vec3>}
  10962. */
  10963. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  10964. /**
  10965. * TSL object that represents the specular strength of the current material.
  10966. * The value is composed via `specularMap.r`.
  10967. *
  10968. * @tsl
  10969. * @type {Node<float>}
  10970. */
  10971. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  10972. /**
  10973. * TSL object that represents the reflectivity of the current material.
  10974. *
  10975. * @tsl
  10976. * @type {Node<float>}
  10977. */
  10978. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  10979. /**
  10980. * TSL object that represents the roughness of the current material.
  10981. * The value is composed via `roughness` * `roughnessMap.g`.
  10982. *
  10983. * @tsl
  10984. * @type {Node<float>}
  10985. */
  10986. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  10987. /**
  10988. * TSL object that represents the metalness of the current material.
  10989. * The value is composed via `metalness` * `metalnessMap.b`.
  10990. *
  10991. * @tsl
  10992. * @type {Node<float>}
  10993. */
  10994. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  10995. /**
  10996. * TSL object that represents the normal of the current material.
  10997. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  10998. *
  10999. * @tsl
  11000. * @type {Node<vec3>}
  11001. */
  11002. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  11003. /**
  11004. * TSL object that represents the clearcoat of the current material.
  11005. * The value is composed via `clearcoat` * `clearcoatMap.r`
  11006. *
  11007. * @tsl
  11008. * @type {Node<float>}
  11009. */
  11010. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  11011. /**
  11012. * TSL object that represents the clearcoat roughness of the current material.
  11013. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  11014. *
  11015. * @tsl
  11016. * @type {Node<float>}
  11017. */
  11018. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  11019. /**
  11020. * TSL object that represents the clearcoat normal of the current material.
  11021. * The value will be either `clearcoatNormalMap` or `normalView`.
  11022. *
  11023. * @tsl
  11024. * @type {Node<vec3>}
  11025. */
  11026. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  11027. /**
  11028. * TSL object that represents the rotation of the current sprite material.
  11029. *
  11030. * @tsl
  11031. * @type {Node<float>}
  11032. */
  11033. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  11034. /**
  11035. * TSL object that represents the sheen color of the current material.
  11036. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  11037. *
  11038. * @tsl
  11039. * @type {Node<vec3>}
  11040. */
  11041. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  11042. /**
  11043. * TSL object that represents the sheen roughness of the current material.
  11044. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  11045. *
  11046. * @tsl
  11047. * @type {Node<float>}
  11048. */
  11049. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  11050. /**
  11051. * TSL object that represents the anisotropy of the current material.
  11052. *
  11053. * @tsl
  11054. * @type {Node<vec2>}
  11055. */
  11056. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  11057. /**
  11058. * TSL object that represents the iridescence of the current material.
  11059. *
  11060. * @tsl
  11061. * @type {Node<float>}
  11062. */
  11063. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  11064. /**
  11065. * TSL object that represents the iridescence IOR of the current material.
  11066. *
  11067. * @tsl
  11068. * @type {Node<float>}
  11069. */
  11070. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  11071. /**
  11072. * TSL object that represents the iridescence thickness of the current material.
  11073. *
  11074. * @tsl
  11075. * @type {Node<float>}
  11076. */
  11077. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  11078. /**
  11079. * TSL object that represents the transmission of the current material.
  11080. * The value is composed via `transmission` * `transmissionMap.r`.
  11081. *
  11082. * @tsl
  11083. * @type {Node<float>}
  11084. */
  11085. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  11086. /**
  11087. * TSL object that represents the thickness of the current material.
  11088. * The value is composed via `thickness` * `thicknessMap.g`.
  11089. *
  11090. * @tsl
  11091. * @type {Node<float>}
  11092. */
  11093. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  11094. /**
  11095. * TSL object that represents the IOR of the current material.
  11096. *
  11097. * @tsl
  11098. * @type {Node<float>}
  11099. */
  11100. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  11101. /**
  11102. * TSL object that represents the attenuation distance of the current material.
  11103. *
  11104. * @tsl
  11105. * @type {Node<float>}
  11106. */
  11107. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  11108. /**
  11109. * TSL object that represents the attenuation color of the current material.
  11110. *
  11111. * @tsl
  11112. * @type {Node<vec3>}
  11113. */
  11114. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  11115. /**
  11116. * TSL object that represents the scale of the current dashed line material.
  11117. *
  11118. * @tsl
  11119. * @type {Node<float>}
  11120. */
  11121. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  11122. /**
  11123. * TSL object that represents the dash size of the current dashed line material.
  11124. *
  11125. * @tsl
  11126. * @type {Node<float>}
  11127. */
  11128. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  11129. /**
  11130. * TSL object that represents the gap size of the current dashed line material.
  11131. *
  11132. * @tsl
  11133. * @type {Node<float>}
  11134. */
  11135. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  11136. /**
  11137. * TSL object that represents the line width of the current line material.
  11138. *
  11139. * @tsl
  11140. * @type {Node<float>}
  11141. */
  11142. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  11143. /**
  11144. * TSL object that represents the dash offset of the current line material.
  11145. *
  11146. * @tsl
  11147. * @type {Node<float>}
  11148. */
  11149. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11150. /**
  11151. * TSL object that represents the point size of the current points material.
  11152. *
  11153. * @tsl
  11154. * @type {Node<float>}
  11155. */
  11156. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11157. /**
  11158. * TSL object that represents the dispersion of the current material.
  11159. *
  11160. * @tsl
  11161. * @type {Node<float>}
  11162. */
  11163. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11164. /**
  11165. * TSL object that represents the light map of the current material.
  11166. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11167. *
  11168. * @tsl
  11169. * @type {Node<vec3>}
  11170. */
  11171. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11172. /**
  11173. * TSL object that represents the ambient occlusion map of the current material.
  11174. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11175. *
  11176. * @tsl
  11177. * @type {Node<float>}
  11178. */
  11179. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11180. /**
  11181. * TSL object that represents the anisotropy vector of the current material.
  11182. *
  11183. * @tsl
  11184. * @type {Node<vec2>}
  11185. */
  11186. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11187. return frame.material;
  11188. } ).onRenderUpdate( function ( { material } ) {
  11189. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11190. } );
  11191. /**
  11192. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11193. *
  11194. * @tsl
  11195. * @type {VaryingNode<vec4>}
  11196. */
  11197. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11198. return builder.context.setupModelViewProjection();
  11199. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11200. /**
  11201. * This class represents shader indices of different types. The following predefined node
  11202. * objects cover frequent use cases:
  11203. *
  11204. * - `vertexIndex`: The index of a vertex within a mesh.
  11205. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  11206. * - `drawIndex`: The index of a draw call.
  11207. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  11208. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  11209. * - `subgroupIndex`: The index of a compute invocation's subgroup within its workgroup.
  11210. *
  11211. * @augments Node
  11212. */
  11213. class IndexNode extends Node {
  11214. static get type() {
  11215. return 'IndexNode';
  11216. }
  11217. /**
  11218. * Constructs a new index node.
  11219. *
  11220. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationGlobal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  11221. */
  11222. constructor( scope ) {
  11223. super( 'uint' );
  11224. /**
  11225. * The scope of the index node.
  11226. *
  11227. * @type {string}
  11228. */
  11229. this.scope = scope;
  11230. /**
  11231. * This flag can be used for type testing.
  11232. *
  11233. * @type {boolean}
  11234. * @readonly
  11235. * @default true
  11236. */
  11237. this.isIndexNode = true;
  11238. }
  11239. generate( builder ) {
  11240. const nodeType = this.getNodeType( builder );
  11241. const scope = this.scope;
  11242. let propertyName;
  11243. if ( scope === IndexNode.VERTEX ) {
  11244. propertyName = builder.getVertexIndex();
  11245. } else if ( scope === IndexNode.INSTANCE ) {
  11246. propertyName = builder.getInstanceIndex();
  11247. } else if ( scope === IndexNode.DRAW ) {
  11248. propertyName = builder.getDrawIndex();
  11249. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  11250. propertyName = builder.getInvocationLocalIndex();
  11251. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  11252. propertyName = builder.getInvocationSubgroupIndex();
  11253. } else if ( scope === IndexNode.SUBGROUP ) {
  11254. propertyName = builder.getSubgroupIndex();
  11255. } else {
  11256. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  11257. }
  11258. let output;
  11259. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  11260. output = propertyName;
  11261. } else {
  11262. const nodeVarying = varying( this );
  11263. output = nodeVarying.build( builder, nodeType );
  11264. }
  11265. return output;
  11266. }
  11267. }
  11268. IndexNode.VERTEX = 'vertex';
  11269. IndexNode.INSTANCE = 'instance';
  11270. IndexNode.SUBGROUP = 'subgroup';
  11271. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  11272. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  11273. IndexNode.DRAW = 'draw';
  11274. /**
  11275. * TSL object that represents the index of a vertex within a mesh.
  11276. *
  11277. * @tsl
  11278. * @type {IndexNode}
  11279. */
  11280. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  11281. /**
  11282. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  11283. *
  11284. * @tsl
  11285. * @type {IndexNode}
  11286. */
  11287. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  11288. /**
  11289. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  11290. *
  11291. * @tsl
  11292. * @type {IndexNode}
  11293. */
  11294. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11295. /**
  11296. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11297. *
  11298. * @tsl
  11299. * @type {IndexNode}
  11300. */
  11301. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11302. /**
  11303. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11304. *
  11305. * @tsl
  11306. * @type {IndexNode}
  11307. */
  11308. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11309. /**
  11310. * TSL object that represents the index of a draw call.
  11311. *
  11312. * @tsl
  11313. * @type {IndexNode}
  11314. */
  11315. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11316. /**
  11317. * This node implements the vertex shader logic which is required
  11318. * when rendering 3D objects via instancing. The code makes sure
  11319. * vertex positions, normals and colors can be modified via instanced
  11320. * data.
  11321. *
  11322. * @augments Node
  11323. */
  11324. class InstanceNode extends Node {
  11325. static get type() {
  11326. return 'InstanceNode';
  11327. }
  11328. /**
  11329. * Constructs a new instance node.
  11330. *
  11331. * @param {number} count - The number of instances.
  11332. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11333. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11334. */
  11335. constructor( count, instanceMatrix, instanceColor = null ) {
  11336. super( 'void' );
  11337. /**
  11338. * The number of instances.
  11339. *
  11340. * @type {number}
  11341. */
  11342. this.count = count;
  11343. /**
  11344. * Instanced buffer attribute representing the transformation of instances.
  11345. *
  11346. * @type {InstancedBufferAttribute}
  11347. */
  11348. this.instanceMatrix = instanceMatrix;
  11349. /**
  11350. * Instanced buffer attribute representing the color of instances.
  11351. *
  11352. * @type {InstancedBufferAttribute}
  11353. */
  11354. this.instanceColor = instanceColor;
  11355. /**
  11356. * The node that represents the instance matrix data.
  11357. *
  11358. * @type {?Node}
  11359. */
  11360. this.instanceMatrixNode = null;
  11361. /**
  11362. * The node that represents the instance color data.
  11363. *
  11364. * @type {?Node}
  11365. * @default null
  11366. */
  11367. this.instanceColorNode = null;
  11368. /**
  11369. * The update type is set to `frame` since an update
  11370. * of instanced buffer data must be checked per frame.
  11371. *
  11372. * @type {string}
  11373. * @default 'frame'
  11374. */
  11375. this.updateType = NodeUpdateType.FRAME;
  11376. /**
  11377. * A reference to a buffer that is used by `instanceMatrixNode`.
  11378. *
  11379. * @type {?InstancedInterleavedBuffer}
  11380. */
  11381. this.buffer = null;
  11382. /**
  11383. * A reference to a buffer that is used by `instanceColorNode`.
  11384. *
  11385. * @type {?InstancedBufferAttribute}
  11386. */
  11387. this.bufferColor = null;
  11388. }
  11389. /**
  11390. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11391. * to predefined node variables for accumulation. That follows the same patterns
  11392. * like with morph and skinning nodes.
  11393. *
  11394. * @param {NodeBuilder} builder - The current node builder.
  11395. */
  11396. setup( builder ) {
  11397. const { instanceMatrix, instanceColor } = this;
  11398. const { count } = instanceMatrix;
  11399. let { instanceMatrixNode, instanceColorNode } = this;
  11400. if ( instanceMatrixNode === null ) {
  11401. // 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.
  11402. if ( count <= 1000 ) {
  11403. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11404. } else {
  11405. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11406. this.buffer = buffer;
  11407. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11408. const instanceBuffers = [
  11409. // F.Signature -> bufferAttribute( array, type, stride, offset )
  11410. bufferFn( buffer, 'vec4', 16, 0 ),
  11411. bufferFn( buffer, 'vec4', 16, 4 ),
  11412. bufferFn( buffer, 'vec4', 16, 8 ),
  11413. bufferFn( buffer, 'vec4', 16, 12 )
  11414. ];
  11415. instanceMatrixNode = mat4( ...instanceBuffers );
  11416. }
  11417. this.instanceMatrixNode = instanceMatrixNode;
  11418. }
  11419. if ( instanceColor && instanceColorNode === null ) {
  11420. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11421. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11422. this.bufferColor = buffer;
  11423. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11424. this.instanceColorNode = instanceColorNode;
  11425. }
  11426. // POSITION
  11427. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11428. positionLocal.assign( instancePosition );
  11429. // NORMAL
  11430. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11431. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11432. // ASSIGNS
  11433. normalLocal.assign( instanceNormal );
  11434. }
  11435. // COLOR
  11436. if ( this.instanceColorNode !== null ) {
  11437. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11438. }
  11439. }
  11440. /**
  11441. * Checks if the internal buffers required an update.
  11442. *
  11443. * @param {NodeFrame} frame - The current node frame.
  11444. */
  11445. update( /*frame*/ ) {
  11446. if ( this.buffer !== null ) {
  11447. // keep update ranges in sync
  11448. this.buffer.clearUpdateRanges();
  11449. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  11450. // update version if necessary
  11451. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  11452. this.buffer.version = this.instanceMatrix.version;
  11453. }
  11454. }
  11455. if ( this.instanceColor && this.bufferColor !== null ) {
  11456. this.bufferColor.clearUpdateRanges();
  11457. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  11458. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  11459. this.bufferColor.version = this.instanceColor.version;
  11460. }
  11461. }
  11462. }
  11463. }
  11464. /**
  11465. * TSL function for creating an instance node.
  11466. *
  11467. * @tsl
  11468. * @function
  11469. * @param {number} count - The number of instances.
  11470. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11471. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11472. * @returns {InstanceNode}
  11473. */
  11474. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11475. /**
  11476. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11477. * It allows an easier setup of the instance node.
  11478. *
  11479. * @augments InstanceNode
  11480. */
  11481. class InstancedMeshNode extends InstanceNode {
  11482. static get type() {
  11483. return 'InstancedMeshNode';
  11484. }
  11485. /**
  11486. * Constructs a new instanced mesh node.
  11487. *
  11488. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11489. */
  11490. constructor( instancedMesh ) {
  11491. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11492. super( count, instanceMatrix, instanceColor );
  11493. /**
  11494. * A reference to the instanced mesh.
  11495. *
  11496. * @type {InstancedMesh}
  11497. */
  11498. this.instancedMesh = instancedMesh;
  11499. }
  11500. }
  11501. /**
  11502. * TSL function for creating an instanced mesh node.
  11503. *
  11504. * @tsl
  11505. * @function
  11506. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11507. * @returns {InstancedMeshNode}
  11508. */
  11509. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11510. /**
  11511. * This node implements the vertex shader logic which is required
  11512. * when rendering 3D objects via batching. `BatchNode` must be used
  11513. * with instances of {@link BatchedMesh}.
  11514. *
  11515. * @augments Node
  11516. */
  11517. class BatchNode extends Node {
  11518. static get type() {
  11519. return 'BatchNode';
  11520. }
  11521. /**
  11522. * Constructs a new batch node.
  11523. *
  11524. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11525. */
  11526. constructor( batchMesh ) {
  11527. super( 'void' );
  11528. /**
  11529. * A reference to batched mesh.
  11530. *
  11531. * @type {BatchedMesh}
  11532. */
  11533. this.batchMesh = batchMesh;
  11534. /**
  11535. * The batching index node.
  11536. *
  11537. * @type {?IndexNode}
  11538. * @default null
  11539. */
  11540. this.batchingIdNode = null;
  11541. }
  11542. /**
  11543. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11544. * to predefined node variables for accumulation. That follows the same patterns
  11545. * like with morph and skinning nodes.
  11546. *
  11547. * @param {NodeBuilder} builder - The current node builder.
  11548. */
  11549. setup( builder ) {
  11550. if ( this.batchingIdNode === null ) {
  11551. if ( builder.getDrawIndex() === null ) {
  11552. this.batchingIdNode = instanceIndex;
  11553. } else {
  11554. this.batchingIdNode = drawIndex;
  11555. }
  11556. }
  11557. const getIndirectIndex = Fn( ( [ id ] ) => {
  11558. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  11559. const x = int( id ).mod( size );
  11560. const y = int( id ).div( size );
  11561. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11562. } ).setLayout( {
  11563. name: 'getIndirectIndex',
  11564. type: 'uint',
  11565. inputs: [
  11566. { name: 'id', type: 'int' }
  11567. ]
  11568. } );
  11569. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11570. const matricesTexture = this.batchMesh._matricesTexture;
  11571. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  11572. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  11573. const x = j.mod( size );
  11574. const y = j.div( size );
  11575. const batchingMatrix = mat4(
  11576. textureLoad( matricesTexture, ivec2( x, y ) ),
  11577. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11578. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11579. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11580. );
  11581. const colorsTexture = this.batchMesh._colorsTexture;
  11582. if ( colorsTexture !== null ) {
  11583. const getBatchingColor = Fn( ( [ id ] ) => {
  11584. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  11585. const j = id;
  11586. const x = j.mod( size );
  11587. const y = j.div( size );
  11588. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11589. } ).setLayout( {
  11590. name: 'getBatchingColor',
  11591. type: 'vec3',
  11592. inputs: [
  11593. { name: 'id', type: 'int' }
  11594. ]
  11595. } );
  11596. const color = getBatchingColor( indirectId );
  11597. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11598. }
  11599. const bm = mat3( batchingMatrix );
  11600. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11601. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11602. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11603. normalLocal.assign( batchingNormal );
  11604. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11605. tangentLocal.mulAssign( bm );
  11606. }
  11607. }
  11608. }
  11609. /**
  11610. * TSL function for creating a batch node.
  11611. *
  11612. * @tsl
  11613. * @function
  11614. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11615. * @returns {BatchNode}
  11616. */
  11617. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11618. /**
  11619. * This class enables element access on instances of {@link StorageBufferNode}.
  11620. * In most cases, it is indirectly used when accessing elements with the
  11621. * {@link StorageBufferNode#element} method.
  11622. *
  11623. * ```js
  11624. * const position = positionStorage.element( instanceIndex );
  11625. * ```
  11626. *
  11627. * @augments ArrayElementNode
  11628. */
  11629. class StorageArrayElementNode extends ArrayElementNode {
  11630. static get type() {
  11631. return 'StorageArrayElementNode';
  11632. }
  11633. /**
  11634. * Constructs storage buffer element node.
  11635. *
  11636. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11637. * @param {Node} indexNode - The index node that defines the element access.
  11638. */
  11639. constructor( storageBufferNode, indexNode ) {
  11640. super( storageBufferNode, indexNode );
  11641. /**
  11642. * This flag can be used for type testing.
  11643. *
  11644. * @type {boolean}
  11645. * @readonly
  11646. * @default true
  11647. */
  11648. this.isStorageArrayElementNode = true;
  11649. }
  11650. /**
  11651. * The storage buffer node.
  11652. *
  11653. * @param {Node} value
  11654. * @type {StorageBufferNode}
  11655. */
  11656. set storageBufferNode( value ) {
  11657. this.node = value;
  11658. }
  11659. get storageBufferNode() {
  11660. return this.node;
  11661. }
  11662. getMemberType( builder, name ) {
  11663. const structTypeNode = this.storageBufferNode.structTypeNode;
  11664. if ( structTypeNode ) {
  11665. return structTypeNode.getMemberType( builder, name );
  11666. }
  11667. return 'void';
  11668. }
  11669. setup( builder ) {
  11670. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11671. if ( this.node.isPBO === true ) {
  11672. builder.setupPBO( this.node );
  11673. }
  11674. }
  11675. return super.setup( builder );
  11676. }
  11677. generate( builder, output ) {
  11678. let snippet;
  11679. const isAssignContext = builder.context.assign;
  11680. //
  11681. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11682. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11683. snippet = builder.generatePBO( this );
  11684. } else {
  11685. snippet = this.node.build( builder );
  11686. }
  11687. } else {
  11688. snippet = super.generate( builder );
  11689. }
  11690. if ( isAssignContext !== true ) {
  11691. const type = this.getNodeType( builder );
  11692. snippet = builder.format( snippet, type, output );
  11693. }
  11694. return snippet;
  11695. }
  11696. }
  11697. /**
  11698. * TSL function for creating a storage element node.
  11699. *
  11700. * @tsl
  11701. * @function
  11702. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11703. * @param {Node} indexNode - The index node that defines the element access.
  11704. * @returns {StorageArrayElementNode}
  11705. */
  11706. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11707. /**
  11708. * This node is used in context of compute shaders and allows to define a
  11709. * storage buffer for data. A typical workflow is to create instances of
  11710. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11711. * setup up a compute shader that writes into the buffers and then convert
  11712. * the storage buffers to attribute nodes for rendering.
  11713. *
  11714. * ```js
  11715. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11716. *
  11717. * const computeInit = Fn( () => { // the compute shader
  11718. *
  11719. * const position = positionBuffer.element( instanceIndex );
  11720. *
  11721. * // compute position data
  11722. *
  11723. * position.x = 1;
  11724. * position.y = 1;
  11725. * position.z = 1;
  11726. *
  11727. * } )().compute( particleCount );
  11728. *
  11729. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11730. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11731. *
  11732. * renderer.computeAsync( computeInit );
  11733. *
  11734. * ```
  11735. *
  11736. * @augments BufferNode
  11737. */
  11738. class StorageBufferNode extends BufferNode {
  11739. static get type() {
  11740. return 'StorageBufferNode';
  11741. }
  11742. /**
  11743. * Constructs a new storage buffer node.
  11744. *
  11745. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11746. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11747. * @param {number} [bufferCount=0] - The buffer count.
  11748. */
  11749. constructor( value, bufferType = null, bufferCount = 0 ) {
  11750. let nodeType, structTypeNode = null;
  11751. if ( bufferType && bufferType.isStruct ) {
  11752. nodeType = 'struct';
  11753. structTypeNode = bufferType.layout;
  11754. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11755. bufferCount = value.count;
  11756. }
  11757. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11758. nodeType = getTypeFromLength( value.itemSize );
  11759. bufferCount = value.count;
  11760. } else {
  11761. nodeType = bufferType;
  11762. }
  11763. super( value, nodeType, bufferCount );
  11764. /**
  11765. * This flag can be used for type testing.
  11766. *
  11767. * @type {boolean}
  11768. * @readonly
  11769. * @default true
  11770. */
  11771. this.isStorageBufferNode = true;
  11772. /**
  11773. * The buffer struct type.
  11774. *
  11775. * @type {?StructTypeNode}
  11776. * @default null
  11777. */
  11778. this.structTypeNode = structTypeNode;
  11779. /**
  11780. * The access type of the texture node.
  11781. *
  11782. * @type {string}
  11783. * @default 'readWrite'
  11784. */
  11785. this.access = NodeAccess.READ_WRITE;
  11786. /**
  11787. * Whether the node is atomic or not.
  11788. *
  11789. * @type {boolean}
  11790. * @default false
  11791. */
  11792. this.isAtomic = false;
  11793. /**
  11794. * Whether the node represents a PBO or not.
  11795. * Only relevant for WebGL.
  11796. *
  11797. * @type {boolean}
  11798. * @default false
  11799. */
  11800. this.isPBO = false;
  11801. /**
  11802. * A reference to the internal buffer attribute node.
  11803. *
  11804. * @type {?BufferAttributeNode}
  11805. * @default null
  11806. */
  11807. this._attribute = null;
  11808. /**
  11809. * A reference to the internal varying node.
  11810. *
  11811. * @type {?VaryingNode}
  11812. * @default null
  11813. */
  11814. this._varying = null;
  11815. /**
  11816. * `StorageBufferNode` sets this property to `true` by default.
  11817. *
  11818. * @type {boolean}
  11819. * @default true
  11820. */
  11821. this.global = true;
  11822. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11823. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11824. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11825. else value.isStorageBufferAttribute = true;
  11826. }
  11827. }
  11828. /**
  11829. * This method is overwritten since the buffer data might be shared
  11830. * and thus the hash should be shared as well.
  11831. *
  11832. * @param {NodeBuilder} builder - The current node builder.
  11833. * @return {string} The hash.
  11834. */
  11835. getHash( builder ) {
  11836. if ( this.bufferCount === 0 ) {
  11837. let bufferData = builder.globalCache.getData( this.value );
  11838. if ( bufferData === undefined ) {
  11839. bufferData = {
  11840. node: this
  11841. };
  11842. builder.globalCache.setData( this.value, bufferData );
  11843. }
  11844. return bufferData.node.uuid;
  11845. }
  11846. return this.uuid;
  11847. }
  11848. /**
  11849. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11850. *
  11851. * @param {NodeBuilder} builder - The current node builder.
  11852. * @return {string} The input type.
  11853. */
  11854. getInputType( /*builder*/ ) {
  11855. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11856. }
  11857. /**
  11858. * Enables element access with the given index node.
  11859. *
  11860. * @param {IndexNode} indexNode - The index node.
  11861. * @return {StorageArrayElementNode} A node representing the element access.
  11862. */
  11863. element( indexNode ) {
  11864. return storageElement( this, indexNode );
  11865. }
  11866. /**
  11867. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11868. *
  11869. * @param {boolean} value - The value so set.
  11870. * @return {StorageBufferNode} A reference to this node.
  11871. */
  11872. setPBO( value ) {
  11873. this.isPBO = value;
  11874. return this;
  11875. }
  11876. /**
  11877. * Returns the `isPBO` value.
  11878. *
  11879. * @return {boolean} Whether the node represents a PBO or not.
  11880. */
  11881. getPBO() {
  11882. return this.isPBO;
  11883. }
  11884. /**
  11885. * Defines the node access.
  11886. *
  11887. * @param {string} value - The node access.
  11888. * @return {StorageBufferNode} A reference to this node.
  11889. */
  11890. setAccess( value ) {
  11891. this.access = value;
  11892. return this;
  11893. }
  11894. /**
  11895. * Convenience method for configuring a read-only node access.
  11896. *
  11897. * @return {StorageBufferNode} A reference to this node.
  11898. */
  11899. toReadOnly() {
  11900. return this.setAccess( NodeAccess.READ_ONLY );
  11901. }
  11902. /**
  11903. * Defines whether the node is atomic or not.
  11904. *
  11905. * @param {boolean} value - The atomic flag.
  11906. * @return {StorageBufferNode} A reference to this node.
  11907. */
  11908. setAtomic( value ) {
  11909. this.isAtomic = value;
  11910. return this;
  11911. }
  11912. /**
  11913. * Convenience method for making this node atomic.
  11914. *
  11915. * @return {StorageBufferNode} A reference to this node.
  11916. */
  11917. toAtomic() {
  11918. return this.setAtomic( true );
  11919. }
  11920. /**
  11921. * Returns attribute data for this storage buffer node.
  11922. *
  11923. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11924. */
  11925. getAttributeData() {
  11926. if ( this._attribute === null ) {
  11927. this._attribute = bufferAttribute( this.value );
  11928. this._varying = varying( this._attribute );
  11929. }
  11930. return {
  11931. attribute: this._attribute,
  11932. varying: this._varying
  11933. };
  11934. }
  11935. /**
  11936. * This method is overwritten since the node type from the availability of storage buffers
  11937. * and the attribute data.
  11938. *
  11939. * @param {NodeBuilder} builder - The current node builder.
  11940. * @return {string} The node type.
  11941. */
  11942. getNodeType( builder ) {
  11943. if ( this.structTypeNode !== null ) {
  11944. return this.structTypeNode.getNodeType( builder );
  11945. }
  11946. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11947. return super.getNodeType( builder );
  11948. }
  11949. const { attribute } = this.getAttributeData();
  11950. return attribute.getNodeType( builder );
  11951. }
  11952. /**
  11953. * Returns the type of a member of the struct.
  11954. *
  11955. * @param {NodeBuilder} builder - The current node builder.
  11956. * @param {string} name - The name of the member.
  11957. * @return {string} The type of the member.
  11958. */
  11959. getMemberType( builder, name ) {
  11960. if ( this.structTypeNode !== null ) {
  11961. return this.structTypeNode.getMemberType( builder, name );
  11962. }
  11963. return 'void';
  11964. }
  11965. /**
  11966. * Generates the code snippet of the storage buffer node.
  11967. *
  11968. * @param {NodeBuilder} builder - The current node builder.
  11969. * @return {string} The generated code snippet.
  11970. */
  11971. generate( builder ) {
  11972. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11973. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11974. return super.generate( builder );
  11975. }
  11976. const { attribute, varying } = this.getAttributeData();
  11977. const output = varying.build( builder );
  11978. builder.registerTransform( output, attribute );
  11979. return output;
  11980. }
  11981. }
  11982. /**
  11983. * TSL function for creating a storage buffer node.
  11984. *
  11985. * @tsl
  11986. * @function
  11987. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11988. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11989. * @param {number} [count=0] - The buffer count.
  11990. * @returns {StorageBufferNode}
  11991. */
  11992. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11993. /**
  11994. * @tsl
  11995. * @function
  11996. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11997. *
  11998. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11999. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  12000. * @param {number} count - The buffer count.
  12001. * @returns {StorageBufferNode}
  12002. */
  12003. const storageObject = ( value, type, count ) => { // @deprecated, r171
  12004. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  12005. return storage( value, type, count ).setPBO( true );
  12006. };
  12007. const _frameId = new WeakMap();
  12008. /**
  12009. * This node implements the vertex transformation shader logic which is required
  12010. * for skinning/skeletal animation.
  12011. *
  12012. * @augments Node
  12013. */
  12014. class SkinningNode extends Node {
  12015. static get type() {
  12016. return 'SkinningNode';
  12017. }
  12018. /**
  12019. * Constructs a new skinning node.
  12020. *
  12021. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12022. */
  12023. constructor( skinnedMesh ) {
  12024. super( 'void' );
  12025. /**
  12026. * The skinned mesh.
  12027. *
  12028. * @type {SkinnedMesh}
  12029. */
  12030. this.skinnedMesh = skinnedMesh;
  12031. /**
  12032. * The update type overwritten since skinning nodes are updated per object.
  12033. *
  12034. * @type {string}
  12035. */
  12036. this.updateType = NodeUpdateType.OBJECT;
  12037. //
  12038. /**
  12039. * The skin index attribute.
  12040. *
  12041. * @type {AttributeNode}
  12042. */
  12043. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  12044. /**
  12045. * The skin weight attribute.
  12046. *
  12047. * @type {AttributeNode}
  12048. */
  12049. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  12050. /**
  12051. * The bind matrix node.
  12052. *
  12053. * @type {Node<mat4>}
  12054. */
  12055. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  12056. /**
  12057. * The bind matrix inverse node.
  12058. *
  12059. * @type {Node<mat4>}
  12060. */
  12061. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  12062. /**
  12063. * The bind matrices as a uniform buffer node.
  12064. *
  12065. * @type {Node}
  12066. */
  12067. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12068. /**
  12069. * The current vertex position in local space.
  12070. *
  12071. * @type {Node<vec3>}
  12072. */
  12073. this.positionNode = positionLocal;
  12074. /**
  12075. * The result of vertex position in local space.
  12076. *
  12077. * @type {Node<vec3>}
  12078. */
  12079. this.toPositionNode = positionLocal;
  12080. /**
  12081. * The previous bind matrices as a uniform buffer node.
  12082. * Required for computing motion vectors.
  12083. *
  12084. * @type {?Node}
  12085. * @default null
  12086. */
  12087. this.previousBoneMatricesNode = null;
  12088. }
  12089. /**
  12090. * Transforms the given vertex position via skinning.
  12091. *
  12092. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12093. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  12094. * @return {Node<vec3>} The transformed vertex position.
  12095. */
  12096. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  12097. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12098. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12099. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12100. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12101. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12102. // POSITION
  12103. const skinVertex = bindMatrixNode.mul( position );
  12104. const skinned = add(
  12105. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  12106. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  12107. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  12108. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  12109. );
  12110. return bindMatrixInverseNode.mul( skinned ).xyz;
  12111. }
  12112. /**
  12113. * Transforms the given vertex normal via skinning.
  12114. *
  12115. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  12116. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  12117. * @return {Node<vec3>} The transformed vertex normal.
  12118. */
  12119. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  12120. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  12121. const boneMatX = boneMatrices.element( skinIndexNode.x );
  12122. const boneMatY = boneMatrices.element( skinIndexNode.y );
  12123. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  12124. const boneMatW = boneMatrices.element( skinIndexNode.w );
  12125. // NORMAL
  12126. let skinMatrix = add(
  12127. skinWeightNode.x.mul( boneMatX ),
  12128. skinWeightNode.y.mul( boneMatY ),
  12129. skinWeightNode.z.mul( boneMatZ ),
  12130. skinWeightNode.w.mul( boneMatW )
  12131. );
  12132. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  12133. return skinMatrix.transformDirection( normal ).xyz;
  12134. }
  12135. /**
  12136. * Computes the transformed/skinned vertex position of the previous frame.
  12137. *
  12138. * @param {NodeBuilder} builder - The current node builder.
  12139. * @return {Node<vec3>} The skinned position from the previous frame.
  12140. */
  12141. getPreviousSkinnedPosition( builder ) {
  12142. const skinnedMesh = builder.object;
  12143. if ( this.previousBoneMatricesNode === null ) {
  12144. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  12145. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  12146. }
  12147. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12148. }
  12149. /**
  12150. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12151. * when computing motion vectors with {@link VelocityNode}.
  12152. *
  12153. * @param {NodeBuilder} builder - The current node builder.
  12154. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12155. */
  12156. needsPreviousBoneMatrices( builder ) {
  12157. const mrt = builder.renderer.getMRT();
  12158. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12159. }
  12160. /**
  12161. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12162. *
  12163. * @param {NodeBuilder} builder - The current node builder.
  12164. * @return {Node<vec3>} The transformed vertex position.
  12165. */
  12166. setup( builder ) {
  12167. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12168. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12169. }
  12170. const skinPosition = this.getSkinnedPosition();
  12171. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12172. //
  12173. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12174. const skinNormal = this.getSkinnedNormal();
  12175. normalLocal.assign( skinNormal );
  12176. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12177. tangentLocal.assign( skinNormal );
  12178. }
  12179. }
  12180. return skinPosition;
  12181. }
  12182. /**
  12183. * Generates the code snippet of the skinning node.
  12184. *
  12185. * @param {NodeBuilder} builder - The current node builder.
  12186. * @param {string} output - The current output.
  12187. * @return {string} The generated code snippet.
  12188. */
  12189. generate( builder, output ) {
  12190. if ( output !== 'void' ) {
  12191. return super.generate( builder, output );
  12192. }
  12193. }
  12194. /**
  12195. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12196. *
  12197. * @param {NodeFrame} frame - The current node frame.
  12198. */
  12199. update( frame ) {
  12200. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12201. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12202. _frameId.set( skeleton, frame.frameId );
  12203. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12204. skeleton.update();
  12205. }
  12206. }
  12207. /**
  12208. * TSL function for creating a skinning node.
  12209. *
  12210. * @tsl
  12211. * @function
  12212. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12213. * @returns {SkinningNode}
  12214. */
  12215. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12216. /**
  12217. * TSL function for computing skinning.
  12218. *
  12219. * @tsl
  12220. * @function
  12221. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12222. * @param {Node<vec3>} [toPosition=null] - The target position.
  12223. * @returns {SkinningNode}
  12224. */
  12225. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12226. const node = new SkinningNode( skinnedMesh );
  12227. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12228. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12229. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12230. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12231. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12232. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12233. node.toPositionNode = toPosition;
  12234. return nodeObject( node );
  12235. };
  12236. /**
  12237. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12238. * ```js
  12239. * Loop( count, ( { i } ) => {
  12240. *
  12241. * } );
  12242. * ```
  12243. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12244. * ```js
  12245. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12246. *
  12247. * } );
  12248. *```
  12249. * Nested loops can be defined in a compacted form:
  12250. * ```js
  12251. * Loop( 10, 5, ( { i, j } ) => {
  12252. *
  12253. * } );
  12254. * ```
  12255. * Loops that should run backwards can be defined like so:
  12256. * ```js
  12257. * Loop( { start: 10 }, () => {} );
  12258. * ```
  12259. * It is possible to execute with boolean values, similar to the `while` syntax.
  12260. * ```js
  12261. * const value = float( 0 ).toVar();
  12262. *
  12263. * Loop( value.lessThan( 10 ), () => {
  12264. *
  12265. * value.addAssign( 1 );
  12266. *
  12267. * } );
  12268. * ```
  12269. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12270. * @augments Node
  12271. */
  12272. class LoopNode extends Node {
  12273. static get type() {
  12274. return 'LoopNode';
  12275. }
  12276. /**
  12277. * Constructs a new loop node.
  12278. *
  12279. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12280. */
  12281. constructor( params = [] ) {
  12282. super();
  12283. this.params = params;
  12284. }
  12285. /**
  12286. * Returns a loop variable name based on an index. The pattern is
  12287. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12288. *
  12289. * @param {number} index - The index.
  12290. * @return {string} The loop variable name.
  12291. */
  12292. getVarName( index ) {
  12293. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12294. }
  12295. /**
  12296. * Returns properties about this node.
  12297. *
  12298. * @param {NodeBuilder} builder - The current node builder.
  12299. * @return {Object} The node properties.
  12300. */
  12301. getProperties( builder ) {
  12302. const properties = builder.getNodeProperties( this );
  12303. if ( properties.stackNode !== undefined ) return properties;
  12304. //
  12305. const inputs = {};
  12306. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12307. const param = this.params[ i ];
  12308. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12309. const type = ( param.isNode !== true && param.type ) || 'int';
  12310. inputs[ name ] = expression( name, type );
  12311. }
  12312. const stack = builder.addStack(); // TODO: cache() it
  12313. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  12314. properties.stackNode = stack;
  12315. const baseParam = this.params[ 0 ];
  12316. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12317. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  12318. }
  12319. builder.removeStack();
  12320. return properties;
  12321. }
  12322. /**
  12323. * This method is overwritten since the node type is inferred based on the loop configuration.
  12324. *
  12325. * @param {NodeBuilder} builder - The current node builder.
  12326. * @return {string} The node type.
  12327. */
  12328. getNodeType( builder ) {
  12329. const { returnsNode } = this.getProperties( builder );
  12330. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  12331. }
  12332. setup( builder ) {
  12333. // setup properties
  12334. this.getProperties( builder );
  12335. }
  12336. generate( builder ) {
  12337. const properties = this.getProperties( builder );
  12338. const params = this.params;
  12339. const stackNode = properties.stackNode;
  12340. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12341. const param = params[ i ];
  12342. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12343. if ( param.isNode ) {
  12344. if ( param.getNodeType( builder ) === 'bool' ) {
  12345. isWhile = true;
  12346. type = 'bool';
  12347. end = param.build( builder, type );
  12348. } else {
  12349. type = 'int';
  12350. name = this.getVarName( i );
  12351. start = '0';
  12352. end = param.build( builder, type );
  12353. condition = '<';
  12354. }
  12355. } else {
  12356. type = param.type || 'int';
  12357. name = param.name || this.getVarName( i );
  12358. start = param.start;
  12359. end = param.end;
  12360. condition = param.condition;
  12361. update = param.update;
  12362. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12363. else if ( start && start.isNode ) start = start.build( builder, type );
  12364. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12365. else if ( end && end.isNode ) end = end.build( builder, type );
  12366. if ( start !== undefined && end === undefined ) {
  12367. start = start + ' - 1';
  12368. end = '0';
  12369. condition = '>=';
  12370. } else if ( end !== undefined && start === undefined ) {
  12371. start = '0';
  12372. condition = '<';
  12373. }
  12374. if ( condition === undefined ) {
  12375. if ( Number( start ) > Number( end ) ) {
  12376. condition = '>=';
  12377. } else {
  12378. condition = '<';
  12379. }
  12380. }
  12381. }
  12382. let loopSnippet;
  12383. if ( isWhile ) {
  12384. loopSnippet = `while ( ${ end } )`;
  12385. } else {
  12386. const internalParam = { start, end};
  12387. //
  12388. const startSnippet = internalParam.start;
  12389. const endSnippet = internalParam.end;
  12390. let updateSnippet;
  12391. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12392. if ( update !== undefined && update !== null ) {
  12393. switch ( typeof update ) {
  12394. case 'function':
  12395. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12396. const snippet = flow.code.replace( /\t|;/g, '' );
  12397. updateSnippet = snippet;
  12398. break;
  12399. case 'number':
  12400. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12401. break;
  12402. case 'string':
  12403. updateSnippet = name + ' ' + update;
  12404. break;
  12405. default:
  12406. if ( update.isNode ) {
  12407. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12408. } else {
  12409. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12410. updateSnippet = 'break /* invalid update */';
  12411. }
  12412. }
  12413. } else {
  12414. if ( type === 'int' || type === 'uint' ) {
  12415. update = condition.includes( '<' ) ? '++' : '--';
  12416. } else {
  12417. update = deltaOperator() + ' 1.';
  12418. }
  12419. updateSnippet = name + ' ' + update;
  12420. }
  12421. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12422. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12423. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12424. }
  12425. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12426. }
  12427. const stackSnippet = stackNode.build( builder, 'void' );
  12428. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  12429. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12430. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12431. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12432. }
  12433. builder.addFlowTab();
  12434. return returnsSnippet;
  12435. }
  12436. }
  12437. /**
  12438. * TSL function for creating a loop node.
  12439. *
  12440. * @tsl
  12441. * @function
  12442. * @param {...any} params - A list of parameters.
  12443. * @returns {LoopNode}
  12444. */
  12445. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  12446. /**
  12447. * TSL function for creating a `Continue()` expression.
  12448. *
  12449. * @tsl
  12450. * @function
  12451. * @returns {ExpressionNode}
  12452. */
  12453. const Continue = () => expression( 'continue' ).toStack();
  12454. /**
  12455. * TSL function for creating a `Break()` expression.
  12456. *
  12457. * @tsl
  12458. * @function
  12459. * @returns {ExpressionNode}
  12460. */
  12461. const Break = () => expression( 'break' ).toStack();
  12462. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12463. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12464. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12465. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12466. const y = texelIndex.div( width );
  12467. const x = texelIndex.sub( y.mul( width ) );
  12468. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12469. return bufferAttrib.mul( influence );
  12470. } );
  12471. function getEntry( geometry ) {
  12472. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12473. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12474. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12475. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12476. // into an array of data textures. Each layer represents a single morph target.
  12477. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12478. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12479. let entry = _morphTextures.get( geometry );
  12480. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12481. if ( entry !== undefined ) entry.texture.dispose();
  12482. const morphTargets = geometry.morphAttributes.position || [];
  12483. const morphNormals = geometry.morphAttributes.normal || [];
  12484. const morphColors = geometry.morphAttributes.color || [];
  12485. let vertexDataCount = 0;
  12486. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12487. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12488. if ( hasMorphColors === true ) vertexDataCount = 3;
  12489. let width = geometry.attributes.position.count * vertexDataCount;
  12490. let height = 1;
  12491. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12492. if ( width > maxTextureSize ) {
  12493. height = Math.ceil( width / maxTextureSize );
  12494. width = maxTextureSize;
  12495. }
  12496. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12497. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12498. bufferTexture.type = FloatType;
  12499. bufferTexture.needsUpdate = true;
  12500. // fill buffer
  12501. const vertexDataStride = vertexDataCount * 4;
  12502. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12503. const morphTarget = morphTargets[ i ];
  12504. const morphNormal = morphNormals[ i ];
  12505. const morphColor = morphColors[ i ];
  12506. const offset = width * height * 4 * i;
  12507. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12508. const stride = j * vertexDataStride;
  12509. if ( hasMorphPosition === true ) {
  12510. _morphVec4.fromBufferAttribute( morphTarget, j );
  12511. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12512. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12513. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12514. buffer[ offset + stride + 3 ] = 0;
  12515. }
  12516. if ( hasMorphNormals === true ) {
  12517. _morphVec4.fromBufferAttribute( morphNormal, j );
  12518. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12519. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12520. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12521. buffer[ offset + stride + 7 ] = 0;
  12522. }
  12523. if ( hasMorphColors === true ) {
  12524. _morphVec4.fromBufferAttribute( morphColor, j );
  12525. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12526. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12527. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12528. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12529. }
  12530. }
  12531. }
  12532. entry = {
  12533. count: morphTargetsCount,
  12534. texture: bufferTexture,
  12535. stride: vertexDataCount,
  12536. size: new Vector2( width, height )
  12537. };
  12538. _morphTextures.set( geometry, entry );
  12539. function disposeTexture() {
  12540. bufferTexture.dispose();
  12541. _morphTextures.delete( geometry );
  12542. geometry.removeEventListener( 'dispose', disposeTexture );
  12543. }
  12544. geometry.addEventListener( 'dispose', disposeTexture );
  12545. }
  12546. return entry;
  12547. }
  12548. /**
  12549. * This node implements the vertex transformation shader logic which is required
  12550. * for morph target animation.
  12551. *
  12552. * @augments Node
  12553. */
  12554. class MorphNode extends Node {
  12555. static get type() {
  12556. return 'MorphNode';
  12557. }
  12558. /**
  12559. * Constructs a new morph node.
  12560. *
  12561. * @param {Mesh} mesh - The mesh holding the morph targets.
  12562. */
  12563. constructor( mesh ) {
  12564. super( 'void' );
  12565. /**
  12566. * The mesh holding the morph targets.
  12567. *
  12568. * @type {Mesh}
  12569. */
  12570. this.mesh = mesh;
  12571. /**
  12572. * A uniform node which represents the morph base influence value.
  12573. *
  12574. * @type {UniformNode<float>}
  12575. */
  12576. this.morphBaseInfluence = uniform( 1 );
  12577. /**
  12578. * The update type overwritten since morph nodes are updated per object.
  12579. *
  12580. * @type {string}
  12581. */
  12582. this.updateType = NodeUpdateType.OBJECT;
  12583. }
  12584. /**
  12585. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12586. *
  12587. * @param {NodeBuilder} builder - The current node builder.
  12588. */
  12589. setup( builder ) {
  12590. const { geometry } = builder;
  12591. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12592. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12593. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12594. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12595. // nodes
  12596. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12597. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12598. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12599. const width = int( size.width );
  12600. Loop( morphTargetsCount, ( { i } ) => {
  12601. const influence = float( 0 ).toVar();
  12602. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12603. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12604. } else {
  12605. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12606. }
  12607. If( influence.notEqual( 0 ), () => {
  12608. if ( hasMorphPosition === true ) {
  12609. positionLocal.addAssign( getMorph( {
  12610. bufferMap,
  12611. influence,
  12612. stride,
  12613. width,
  12614. depth: i,
  12615. offset: int( 0 )
  12616. } ) );
  12617. }
  12618. if ( hasMorphNormals === true ) {
  12619. normalLocal.addAssign( getMorph( {
  12620. bufferMap,
  12621. influence,
  12622. stride,
  12623. width,
  12624. depth: i,
  12625. offset: int( 1 )
  12626. } ) );
  12627. }
  12628. } );
  12629. } );
  12630. }
  12631. /**
  12632. * Updates the state of the morphed mesh by updating the base influence.
  12633. *
  12634. * @param {NodeFrame} frame - The current node frame.
  12635. */
  12636. update( /*frame*/ ) {
  12637. const morphBaseInfluence = this.morphBaseInfluence;
  12638. if ( this.mesh.geometry.morphTargetsRelative ) {
  12639. morphBaseInfluence.value = 1;
  12640. } else {
  12641. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12642. }
  12643. }
  12644. }
  12645. /**
  12646. * TSL function for creating a morph node.
  12647. *
  12648. * @tsl
  12649. * @function
  12650. * @param {Mesh} mesh - The mesh holding the morph targets.
  12651. * @returns {MorphNode}
  12652. */
  12653. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12654. /**
  12655. * Base class for lighting nodes.
  12656. *
  12657. * @augments Node
  12658. */
  12659. class LightingNode extends Node {
  12660. static get type() {
  12661. return 'LightingNode';
  12662. }
  12663. /**
  12664. * Constructs a new lighting node.
  12665. */
  12666. constructor() {
  12667. super( 'vec3' );
  12668. /**
  12669. * This flag can be used for type testing.
  12670. *
  12671. * @type {boolean}
  12672. * @readonly
  12673. * @default true
  12674. */
  12675. this.isLightingNode = true;
  12676. }
  12677. }
  12678. /**
  12679. * A generic class that can be used by nodes which contribute
  12680. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12681. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12682. *
  12683. * @augments LightingNode
  12684. */
  12685. class AONode extends LightingNode {
  12686. static get type() {
  12687. return 'AONode';
  12688. }
  12689. /**
  12690. * Constructs a new AO node.
  12691. *
  12692. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12693. */
  12694. constructor( aoNode = null ) {
  12695. super();
  12696. /**
  12697. * The ambient occlusion node.
  12698. *
  12699. * @type {?Node<float>}
  12700. * @default null
  12701. */
  12702. this.aoNode = aoNode;
  12703. }
  12704. setup( builder ) {
  12705. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12706. }
  12707. }
  12708. /**
  12709. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12710. * by adding lighting specific context data. It represents the runtime context of
  12711. * {@link LightsNode}.
  12712. *
  12713. * @augments ContextNode
  12714. */
  12715. class LightingContextNode extends ContextNode {
  12716. static get type() {
  12717. return 'LightingContextNode';
  12718. }
  12719. /**
  12720. * Constructs a new lighting context node.
  12721. *
  12722. * @param {LightsNode} lightsNode - The lights node.
  12723. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12724. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12725. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12726. */
  12727. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12728. super( lightsNode );
  12729. /**
  12730. * The current lighting model.
  12731. *
  12732. * @type {?LightingModel}
  12733. * @default null
  12734. */
  12735. this.lightingModel = lightingModel;
  12736. /**
  12737. * A backdrop node.
  12738. *
  12739. * @type {?Node<vec3>}
  12740. * @default null
  12741. */
  12742. this.backdropNode = backdropNode;
  12743. /**
  12744. * A backdrop alpha node.
  12745. *
  12746. * @type {?Node<float>}
  12747. * @default null
  12748. */
  12749. this.backdropAlphaNode = backdropAlphaNode;
  12750. this._value = null;
  12751. }
  12752. /**
  12753. * Returns a lighting context object.
  12754. *
  12755. * @return {{
  12756. * radiance: Node<vec3>,
  12757. * irradiance: Node<vec3>,
  12758. * iblIrradiance: Node<vec3>,
  12759. * ambientOcclusion: Node<float>,
  12760. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12761. * backdrop: Node<vec3>,
  12762. * backdropAlpha: Node<float>
  12763. * }} The lighting context object.
  12764. */
  12765. getContext() {
  12766. const { backdropNode, backdropAlphaNode } = this;
  12767. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12768. directSpecular = vec3().toVar( 'directSpecular' ),
  12769. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12770. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12771. const reflectedLight = {
  12772. directDiffuse,
  12773. directSpecular,
  12774. indirectDiffuse,
  12775. indirectSpecular
  12776. };
  12777. const context = {
  12778. radiance: vec3().toVar( 'radiance' ),
  12779. irradiance: vec3().toVar( 'irradiance' ),
  12780. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12781. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12782. reflectedLight,
  12783. backdrop: backdropNode,
  12784. backdropAlpha: backdropAlphaNode
  12785. };
  12786. return context;
  12787. }
  12788. setup( builder ) {
  12789. this.value = this._value || ( this._value = this.getContext() );
  12790. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  12791. return super.setup( builder );
  12792. }
  12793. }
  12794. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  12795. /**
  12796. * A generic class that can be used by nodes which contribute
  12797. * irradiance to the scene. E.g. a light map node can be used
  12798. * as input for this module. Used in {@link NodeMaterial}.
  12799. *
  12800. * @augments LightingNode
  12801. */
  12802. class IrradianceNode extends LightingNode {
  12803. static get type() {
  12804. return 'IrradianceNode';
  12805. }
  12806. /**
  12807. * Constructs a new irradiance node.
  12808. *
  12809. * @param {Node<vec3>} node - A node contributing irradiance.
  12810. */
  12811. constructor( node ) {
  12812. super();
  12813. /**
  12814. * A node contributing irradiance.
  12815. *
  12816. * @type {Node<vec3>}
  12817. */
  12818. this.node = node;
  12819. }
  12820. setup( builder ) {
  12821. builder.context.irradiance.addAssign( this.node );
  12822. }
  12823. }
  12824. const _size$5 = /*@__PURE__*/ new Vector2();
  12825. /**
  12826. * A special type of texture node which represents the data of the current viewport
  12827. * as a texture. The module extracts data from the current bound framebuffer with
  12828. * a copy operation so no extra render pass is required to produce the texture data
  12829. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  12830. * variety of effects like refractive or transmissive materials.
  12831. *
  12832. * @augments TextureNode
  12833. */
  12834. class ViewportTextureNode extends TextureNode {
  12835. static get type() {
  12836. return 'ViewportTextureNode';
  12837. }
  12838. /**
  12839. * Constructs a new viewport texture node.
  12840. *
  12841. * @param {Node} [uvNode=screenUV] - The uv node.
  12842. * @param {?Node} [levelNode=null] - The level node.
  12843. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12844. */
  12845. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12846. let defaultFramebuffer = null;
  12847. if ( framebufferTexture === null ) {
  12848. defaultFramebuffer = new FramebufferTexture();
  12849. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  12850. framebufferTexture = defaultFramebuffer;
  12851. } else {
  12852. defaultFramebuffer = framebufferTexture;
  12853. }
  12854. super( framebufferTexture, uvNode, levelNode );
  12855. /**
  12856. * Whether to generate mipmaps or not.
  12857. *
  12858. * @type {boolean}
  12859. * @default false
  12860. */
  12861. this.generateMipmaps = false;
  12862. /**
  12863. * The reference framebuffer texture. This is used to store the framebuffer texture
  12864. * for the current render target. If the render target changes, a new framebuffer texture
  12865. * is created automatically.
  12866. *
  12867. * @type {FramebufferTexture}
  12868. * @default null
  12869. */
  12870. this.defaultFramebuffer = defaultFramebuffer;
  12871. /**
  12872. * This flag can be used for type testing.
  12873. *
  12874. * @type {boolean}
  12875. * @readonly
  12876. * @default true
  12877. */
  12878. this.isOutputTextureNode = true;
  12879. /**
  12880. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  12881. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  12882. *
  12883. * @type {string}
  12884. * @default 'frame'
  12885. */
  12886. this.updateBeforeType = NodeUpdateType.FRAME;
  12887. /**
  12888. * The framebuffer texture for the current renderer context.
  12889. *
  12890. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  12891. * @private
  12892. */
  12893. this._cacheTextures = new WeakMap();
  12894. }
  12895. /**
  12896. * This methods returns a texture for the given render target reference.
  12897. *
  12898. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  12899. * for different render contexts.
  12900. *
  12901. * @param {?RenderTarget} [reference=null] - The render target reference.
  12902. * @return {Texture} The framebuffer texture.
  12903. */
  12904. getTextureForReference( reference = null ) {
  12905. let defaultFramebuffer;
  12906. let cacheTextures;
  12907. if ( this.referenceNode ) {
  12908. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  12909. cacheTextures = this.referenceNode._cacheTextures;
  12910. } else {
  12911. defaultFramebuffer = this.defaultFramebuffer;
  12912. cacheTextures = this._cacheTextures;
  12913. }
  12914. if ( reference === null ) {
  12915. return defaultFramebuffer;
  12916. }
  12917. if ( cacheTextures.has( reference ) === false ) {
  12918. const framebufferTexture = defaultFramebuffer.clone();
  12919. cacheTextures.set( reference, framebufferTexture );
  12920. }
  12921. return cacheTextures.get( reference );
  12922. }
  12923. updateReference( frame ) {
  12924. const renderTarget = frame.renderer.getRenderTarget();
  12925. this.value = this.getTextureForReference( renderTarget );
  12926. return this.value;
  12927. }
  12928. updateBefore( frame ) {
  12929. const renderer = frame.renderer;
  12930. const renderTarget = renderer.getRenderTarget();
  12931. if ( renderTarget === null ) {
  12932. renderer.getDrawingBufferSize( _size$5 );
  12933. } else {
  12934. _size$5.set( renderTarget.width, renderTarget.height );
  12935. }
  12936. //
  12937. const framebufferTexture = this.getTextureForReference( renderTarget );
  12938. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  12939. framebufferTexture.image.width = _size$5.width;
  12940. framebufferTexture.image.height = _size$5.height;
  12941. framebufferTexture.needsUpdate = true;
  12942. }
  12943. //
  12944. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12945. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12946. renderer.copyFramebufferToTexture( framebufferTexture );
  12947. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12948. }
  12949. clone() {
  12950. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12951. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12952. return viewportTextureNode;
  12953. }
  12954. }
  12955. /**
  12956. * TSL function for creating a viewport texture node.
  12957. *
  12958. * @tsl
  12959. * @function
  12960. * @param {?Node} [uvNode=screenUV] - The uv node.
  12961. * @param {?Node} [levelNode=null] - The level node.
  12962. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12963. * @returns {ViewportTextureNode}
  12964. */
  12965. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12966. /**
  12967. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12968. *
  12969. * @tsl
  12970. * @function
  12971. * @param {?Node} [uvNode=screenUV] - The uv node.
  12972. * @param {?Node} [levelNode=null] - The level node.
  12973. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12974. * @returns {ViewportTextureNode}
  12975. */
  12976. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12977. let _sharedDepthbuffer = null;
  12978. /**
  12979. * Represents the depth of the current viewport as a texture. This module
  12980. * can be used in combination with viewport texture to achieve effects
  12981. * that require depth evaluation.
  12982. *
  12983. * @augments ViewportTextureNode
  12984. */
  12985. class ViewportDepthTextureNode extends ViewportTextureNode {
  12986. static get type() {
  12987. return 'ViewportDepthTextureNode';
  12988. }
  12989. /**
  12990. * Constructs a new viewport depth texture node.
  12991. *
  12992. * @param {Node} [uvNode=screenUV] - The uv node.
  12993. * @param {?Node} [levelNode=null] - The level node.
  12994. */
  12995. constructor( uvNode = screenUV, levelNode = null ) {
  12996. if ( _sharedDepthbuffer === null ) {
  12997. _sharedDepthbuffer = new DepthTexture();
  12998. }
  12999. super( uvNode, levelNode, _sharedDepthbuffer );
  13000. }
  13001. /**
  13002. * Overwritten so the method always returns the unique shared
  13003. * depth texture.
  13004. *
  13005. * @return {DepthTexture} The shared depth texture.
  13006. */
  13007. getTextureForReference() {
  13008. return _sharedDepthbuffer;
  13009. }
  13010. }
  13011. /**
  13012. * TSL function for a viewport depth texture node.
  13013. *
  13014. * @tsl
  13015. * @function
  13016. * @param {?Node} [uvNode=screenUV] - The uv node.
  13017. * @param {?Node} [levelNode=null] - The level node.
  13018. * @returns {ViewportDepthTextureNode}
  13019. */
  13020. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  13021. /**
  13022. * This node offers a collection of features in context of the depth logic in the fragment shader.
  13023. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  13024. * fragment or for depth evaluation purposes.
  13025. *
  13026. * @augments Node
  13027. */
  13028. class ViewportDepthNode extends Node {
  13029. static get type() {
  13030. return 'ViewportDepthNode';
  13031. }
  13032. /**
  13033. * Constructs a new viewport depth node.
  13034. *
  13035. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  13036. * @param {?Node} [valueNode=null] - The value node.
  13037. */
  13038. constructor( scope, valueNode = null ) {
  13039. super( 'float' );
  13040. /**
  13041. * The node behaves differently depending on which scope is selected.
  13042. *
  13043. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  13044. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  13045. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  13046. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  13047. *
  13048. * @type {('depth'|'depthBase'|'linearDepth')}
  13049. */
  13050. this.scope = scope;
  13051. /**
  13052. * Can be used to define a custom depth value.
  13053. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  13054. *
  13055. * @type {?Node}
  13056. * @default null
  13057. */
  13058. this.valueNode = valueNode;
  13059. /**
  13060. * This flag can be used for type testing.
  13061. *
  13062. * @type {boolean}
  13063. * @readonly
  13064. * @default true
  13065. */
  13066. this.isViewportDepthNode = true;
  13067. }
  13068. generate( builder ) {
  13069. const { scope } = this;
  13070. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13071. return builder.getFragDepth();
  13072. }
  13073. return super.generate( builder );
  13074. }
  13075. setup( { camera } ) {
  13076. const { scope } = this;
  13077. const value = this.valueNode;
  13078. let node = null;
  13079. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  13080. if ( value !== null ) {
  13081. node = depthBase().assign( value );
  13082. }
  13083. } else if ( scope === ViewportDepthNode.DEPTH ) {
  13084. if ( camera.isPerspectiveCamera ) {
  13085. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  13086. } else {
  13087. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13088. }
  13089. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  13090. if ( value !== null ) {
  13091. if ( camera.isPerspectiveCamera ) {
  13092. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  13093. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  13094. } else {
  13095. node = value;
  13096. }
  13097. } else {
  13098. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13099. }
  13100. }
  13101. return node;
  13102. }
  13103. }
  13104. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  13105. ViewportDepthNode.DEPTH = 'depth';
  13106. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  13107. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  13108. /**
  13109. * TSL function for converting a viewZ value to an orthographic depth value.
  13110. *
  13111. * @tsl
  13112. * @function
  13113. * @param {Node<float>} viewZ - The viewZ node.
  13114. * @param {Node<float>} near - The camera's near value.
  13115. * @param {Node<float>} far - The camera's far value.
  13116. * @returns {Node<float>}
  13117. */
  13118. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  13119. /**
  13120. * TSL function for converting an orthographic depth value to a viewZ value.
  13121. *
  13122. * @tsl
  13123. * @function
  13124. * @param {Node<float>} depth - The orthographic depth.
  13125. * @param {Node<float>} near - The camera's near value.
  13126. * @param {Node<float>} far - The camera's far value.
  13127. * @returns {Node<float>}
  13128. */
  13129. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  13130. /**
  13131. * TSL function for converting a viewZ value to a perspective depth value.
  13132. *
  13133. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  13134. *
  13135. * @tsl
  13136. * @function
  13137. * @param {Node<float>} viewZ - The viewZ node.
  13138. * @param {Node<float>} near - The camera's near value.
  13139. * @param {Node<float>} far - The camera's far value.
  13140. * @returns {Node<float>}
  13141. */
  13142. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  13143. /**
  13144. * TSL function for converting a perspective depth value to a viewZ value.
  13145. *
  13146. * @tsl
  13147. * @function
  13148. * @param {Node<float>} depth - The perspective depth.
  13149. * @param {Node<float>} near - The camera's near value.
  13150. * @param {Node<float>} far - The camera's far value.
  13151. * @returns {Node<float>}
  13152. */
  13153. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13154. /**
  13155. * TSL function for converting a viewZ value to a logarithmic depth value.
  13156. *
  13157. * @tsl
  13158. * @function
  13159. * @param {Node<float>} viewZ - The viewZ node.
  13160. * @param {Node<float>} near - The camera's near value.
  13161. * @param {Node<float>} far - The camera's far value.
  13162. * @returns {Node<float>}
  13163. */
  13164. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13165. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13166. // The final logarithmic depth formula used here is adapted from one described in an
  13167. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13168. // which was an improvement upon an earlier formula one described in an
  13169. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13170. // Ulrich's formula is the following:
  13171. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13172. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13173. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13174. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13175. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13176. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13177. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13178. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13179. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13180. // Outerra eventually made another improvement to their original "C-constant" variant,
  13181. // but it still does not incorporate the camera near plane (for this version,
  13182. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13183. // Here we make 4 changes to Ulrich's formula:
  13184. // 1. Clamp the camera near plane so we don't divide by 0.
  13185. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13186. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13187. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13188. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13189. // so we do the same here, hence the 'viewZ.negate()' call.
  13190. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13191. near = near.max( 1e-6 ).toVar();
  13192. const numerator = log2( viewZ.negate().div( near ) );
  13193. const denominator = log2( far.div( near ) );
  13194. return numerator.div( denominator );
  13195. };
  13196. /**
  13197. * TSL function for converting a logarithmic depth value to a viewZ value.
  13198. *
  13199. * @tsl
  13200. * @function
  13201. * @param {Node<float>} depth - The logarithmic depth.
  13202. * @param {Node<float>} near - The camera's near value.
  13203. * @param {Node<float>} far - The camera's far value.
  13204. * @returns {Node<float>}
  13205. */
  13206. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13207. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13208. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13209. // a negative viewZ).
  13210. const exponent = depth.mul( log( far.div( near ) ) );
  13211. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13212. };
  13213. /**
  13214. * TSL function for defining a value for the current fragment's depth.
  13215. *
  13216. * @tsl
  13217. * @function
  13218. * @param {Node<float>} value - The depth value to set.
  13219. * @returns {ViewportDepthNode<float>}
  13220. */
  13221. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13222. /**
  13223. * TSL object that represents the depth value for the current fragment.
  13224. *
  13225. * @tsl
  13226. * @type {ViewportDepthNode}
  13227. */
  13228. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13229. /**
  13230. * TSL function for converting a perspective depth value to linear depth.
  13231. *
  13232. * @tsl
  13233. * @function
  13234. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13235. * @returns {ViewportDepthNode<float>}
  13236. */
  13237. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13238. /**
  13239. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13240. *
  13241. * @tsl
  13242. * @type {ViewportDepthNode}
  13243. */
  13244. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13245. depth.assign = ( value ) => depthBase( value );
  13246. /**
  13247. * This node is used in {@link NodeMaterial} to setup the clipping
  13248. * which can happen hardware-accelerated (if supported) and optionally
  13249. * use alpha-to-coverage for anti-aliasing clipped edges.
  13250. *
  13251. * @augments Node
  13252. */
  13253. class ClippingNode extends Node {
  13254. static get type() {
  13255. return 'ClippingNode';
  13256. }
  13257. /**
  13258. * Constructs a new clipping node.
  13259. *
  13260. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13261. * the selected scope influences the behavior of the node and what type of code is generated.
  13262. */
  13263. constructor( scope = ClippingNode.DEFAULT ) {
  13264. super();
  13265. /**
  13266. * The node's scope. Similar to other nodes, the selected scope influences
  13267. * the behavior of the node and what type of code is generated.
  13268. *
  13269. * @type {('default'|'hardware'|'alphaToCoverage')}
  13270. */
  13271. this.scope = scope;
  13272. }
  13273. /**
  13274. * Setups the node depending on the selected scope.
  13275. *
  13276. * @param {NodeBuilder} builder - The current node builder.
  13277. * @return {Node} The result node.
  13278. */
  13279. setup( builder ) {
  13280. super.setup( builder );
  13281. const clippingContext = builder.clippingContext;
  13282. const { intersectionPlanes, unionPlanes } = clippingContext;
  13283. this.hardwareClipping = builder.material.hardwareClipping;
  13284. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13285. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13286. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13287. return this.setupHardwareClipping( unionPlanes, builder );
  13288. } else {
  13289. return this.setupDefault( intersectionPlanes, unionPlanes );
  13290. }
  13291. }
  13292. /**
  13293. * Setups alpha to coverage.
  13294. *
  13295. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13296. * @param {Array<Vector4>} unionPlanes - The union planes.
  13297. * @return {Node} The result node.
  13298. */
  13299. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13300. return Fn( () => {
  13301. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13302. const distanceGradient = float().toVar( 'distanceToGradient' );
  13303. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13304. const numUnionPlanes = unionPlanes.length;
  13305. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13306. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13307. Loop( numUnionPlanes, ( { i } ) => {
  13308. const plane = clippingPlanes.element( i );
  13309. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13310. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13311. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13312. } );
  13313. }
  13314. const numIntersectionPlanes = intersectionPlanes.length;
  13315. if ( numIntersectionPlanes > 0 ) {
  13316. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13317. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13318. Loop( numIntersectionPlanes, ( { i } ) => {
  13319. const plane = clippingPlanes.element( i );
  13320. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13321. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13322. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13323. } );
  13324. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13325. }
  13326. diffuseColor.a.mulAssign( clipOpacity );
  13327. diffuseColor.a.equal( 0.0 ).discard();
  13328. } )();
  13329. }
  13330. /**
  13331. * Setups the default clipping.
  13332. *
  13333. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13334. * @param {Array<Vector4>} unionPlanes - The union planes.
  13335. * @return {Node} The result node.
  13336. */
  13337. setupDefault( intersectionPlanes, unionPlanes ) {
  13338. return Fn( () => {
  13339. const numUnionPlanes = unionPlanes.length;
  13340. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13341. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13342. Loop( numUnionPlanes, ( { i } ) => {
  13343. const plane = clippingPlanes.element( i );
  13344. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13345. } );
  13346. }
  13347. const numIntersectionPlanes = intersectionPlanes.length;
  13348. if ( numIntersectionPlanes > 0 ) {
  13349. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13350. const clipped = bool( true ).toVar( 'clipped' );
  13351. Loop( numIntersectionPlanes, ( { i } ) => {
  13352. const plane = clippingPlanes.element( i );
  13353. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13354. } );
  13355. clipped.discard();
  13356. }
  13357. } )();
  13358. }
  13359. /**
  13360. * Setups hardware clipping.
  13361. *
  13362. * @param {Array<Vector4>} unionPlanes - The union planes.
  13363. * @param {NodeBuilder} builder - The current node builder.
  13364. * @return {Node} The result node.
  13365. */
  13366. setupHardwareClipping( unionPlanes, builder ) {
  13367. const numUnionPlanes = unionPlanes.length;
  13368. builder.enableHardwareClipping( numUnionPlanes );
  13369. return Fn( () => {
  13370. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13371. const hw_clip_distances = builtin( builder.getClipDistance() );
  13372. Loop( numUnionPlanes, ( { i } ) => {
  13373. const plane = clippingPlanes.element( i );
  13374. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13375. hw_clip_distances.element( i ).assign( distance );
  13376. } );
  13377. } )();
  13378. }
  13379. }
  13380. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13381. ClippingNode.DEFAULT = 'default';
  13382. ClippingNode.HARDWARE = 'hardware';
  13383. /**
  13384. * TSL function for setting up the default clipping logic.
  13385. *
  13386. * @tsl
  13387. * @function
  13388. * @returns {ClippingNode}
  13389. */
  13390. const clipping = () => nodeObject( new ClippingNode() );
  13391. /**
  13392. * TSL function for setting up alpha to coverage.
  13393. *
  13394. * @tsl
  13395. * @function
  13396. * @returns {ClippingNode}
  13397. */
  13398. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13399. /**
  13400. * TSL function for setting up hardware-based clipping.
  13401. *
  13402. * @tsl
  13403. * @function
  13404. * @returns {ClippingNode}
  13405. */
  13406. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13407. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13408. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13409. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13410. 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 ) ) ) ) ) );
  13411. } );
  13412. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13413. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13414. } );
  13415. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13416. // Find the discretized derivatives of our coordinates
  13417. const maxDeriv = max$1(
  13418. length( dFdx( position.xyz ) ),
  13419. length( dFdy( position.xyz ) )
  13420. );
  13421. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13422. // Find two nearest log-discretized noise scales
  13423. const pixScales = vec2(
  13424. exp2( floor( log2( pixScale ) ) ),
  13425. exp2( ceil( log2( pixScale ) ) )
  13426. );
  13427. // Compute alpha thresholds at our two noise scales
  13428. const alpha = vec2(
  13429. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13430. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13431. );
  13432. // Factor to interpolate lerp with
  13433. const lerpFactor = fract( log2( pixScale ) );
  13434. // Interpolate alpha threshold from noise at two scales
  13435. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13436. // Pass into CDF to compute uniformly distrib threshold
  13437. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13438. const cases = vec3(
  13439. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13440. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13441. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13442. // Find our final, uniformly distributed alpha threshold (ατ)
  13443. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13444. // Avoids ατ == 0. Could also do ατ =1-ατ
  13445. return clamp( threshold, 1.0e-6, 1.0 );
  13446. } ).setLayout( {
  13447. name: 'getAlphaHashThreshold',
  13448. type: 'float',
  13449. inputs: [
  13450. { name: 'position', type: 'vec3' }
  13451. ]
  13452. } );
  13453. /**
  13454. * An attribute node for representing vertex colors.
  13455. *
  13456. * @augments AttributeNode
  13457. */
  13458. class VertexColorNode extends AttributeNode {
  13459. static get type() {
  13460. return 'VertexColorNode';
  13461. }
  13462. /**
  13463. * Constructs a new vertex color node.
  13464. *
  13465. * @param {number} index - The attribute index.
  13466. */
  13467. constructor( index ) {
  13468. super( null, 'vec4' );
  13469. /**
  13470. * This flag can be used for type testing.
  13471. *
  13472. * @type {boolean}
  13473. * @readonly
  13474. * @default true
  13475. */
  13476. this.isVertexColorNode = true;
  13477. /**
  13478. * The attribute index to enable more than one sets of vertex colors.
  13479. *
  13480. * @type {number}
  13481. * @default 0
  13482. */
  13483. this.index = index;
  13484. }
  13485. /**
  13486. * Overwrites the default implementation by honoring the attribute index.
  13487. *
  13488. * @param {NodeBuilder} builder - The current node builder.
  13489. * @return {string} The attribute name.
  13490. */
  13491. getAttributeName( /*builder*/ ) {
  13492. const index = this.index;
  13493. return 'color' + ( index > 0 ? index : '' );
  13494. }
  13495. generate( builder ) {
  13496. const attributeName = this.getAttributeName( builder );
  13497. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13498. let result;
  13499. if ( geometryAttribute === true ) {
  13500. result = super.generate( builder );
  13501. } else {
  13502. // Vertex color fallback should be white
  13503. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13504. }
  13505. return result;
  13506. }
  13507. serialize( data ) {
  13508. super.serialize( data );
  13509. data.index = this.index;
  13510. }
  13511. deserialize( data ) {
  13512. super.deserialize( data );
  13513. this.index = data.index;
  13514. }
  13515. }
  13516. /**
  13517. * TSL function for creating a reference node.
  13518. *
  13519. * @tsl
  13520. * @function
  13521. * @param {number} [index=0] - The attribute index.
  13522. * @returns {VertexColorNode}
  13523. */
  13524. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13525. /**
  13526. * Represents a "Color Burn" blend mode.
  13527. *
  13528. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13529. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13530. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13531. *
  13532. * @tsl
  13533. * @function
  13534. * @param {Node<vec3>} base - The base color.
  13535. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13536. * @return {Node<vec3>} The result.
  13537. */
  13538. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13539. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13540. } ).setLayout( {
  13541. name: 'blendBurn',
  13542. type: 'vec3',
  13543. inputs: [
  13544. { name: 'base', type: 'vec3' },
  13545. { name: 'blend', type: 'vec3' }
  13546. ]
  13547. } );
  13548. /**
  13549. * Represents a "Color Dodge" blend mode.
  13550. *
  13551. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13552. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13553. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13554. *
  13555. * @tsl
  13556. * @function
  13557. * @param {Node<vec3>} base - The base color.
  13558. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13559. * @return {Node<vec3>} The result.
  13560. */
  13561. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13562. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13563. } ).setLayout( {
  13564. name: 'blendDodge',
  13565. type: 'vec3',
  13566. inputs: [
  13567. { name: 'base', type: 'vec3' },
  13568. { name: 'blend', type: 'vec3' }
  13569. ]
  13570. } );
  13571. /**
  13572. * Represents a "Screen" blend mode.
  13573. *
  13574. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13575. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13576. * effects.
  13577. *
  13578. * @tsl
  13579. * @function
  13580. * @param {Node<vec3>} base - The base color.
  13581. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13582. * @return {Node<vec3>} The result.
  13583. */
  13584. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13585. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13586. } ).setLayout( {
  13587. name: 'blendScreen',
  13588. type: 'vec3',
  13589. inputs: [
  13590. { name: 'base', type: 'vec3' },
  13591. { name: 'blend', type: 'vec3' }
  13592. ]
  13593. } );
  13594. /**
  13595. * Represents a "Overlay" blend mode.
  13596. *
  13597. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13598. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13599. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13600. *
  13601. * @tsl
  13602. * @function
  13603. * @param {Node<vec3>} base - The base color.
  13604. * @param {Node<vec3>} blend - The blend color
  13605. * @return {Node<vec3>} The result.
  13606. */
  13607. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13608. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13609. } ).setLayout( {
  13610. name: 'blendOverlay',
  13611. type: 'vec3',
  13612. inputs: [
  13613. { name: 'base', type: 'vec3' },
  13614. { name: 'blend', type: 'vec3' }
  13615. ]
  13616. } );
  13617. /**
  13618. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13619. * It assumes both input colors have non-premultiplied alpha.
  13620. *
  13621. * @tsl
  13622. * @function
  13623. * @param {Node<vec4>} base - The base color.
  13624. * @param {Node<vec4>} blend - The blend color
  13625. * @return {Node<vec4>} The result.
  13626. */
  13627. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13628. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13629. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13630. } ).setLayout( {
  13631. name: 'blendColor',
  13632. type: 'vec4',
  13633. inputs: [
  13634. { name: 'base', type: 'vec4' },
  13635. { name: 'blend', type: 'vec4' }
  13636. ]
  13637. } );
  13638. /**
  13639. * Premultiplies the RGB channels of a color by its alpha channel.
  13640. *
  13641. * This function is useful for converting a non-premultiplied alpha color
  13642. * into a premultiplied alpha format, where the RGB values are scaled
  13643. * by the alpha value. Premultiplied alpha is often used in graphics
  13644. * rendering for certain operations, such as compositing and image processing.
  13645. *
  13646. * @tsl
  13647. * @function
  13648. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13649. * @return {Node<vec4>} The color with premultiplied alpha.
  13650. */
  13651. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13652. return vec4( color.rgb.mul( color.a ), color.a );
  13653. }, { color: 'vec4', return: 'vec4' } );
  13654. /**
  13655. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13656. *
  13657. * This function is useful for converting a premultiplied alpha color
  13658. * back into a non-premultiplied alpha format, where the RGB values are
  13659. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13660. * rendering for certain operations, such as compositing and image processing.
  13661. *
  13662. * @tsl
  13663. * @function
  13664. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13665. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13666. */
  13667. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13668. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13669. return vec4( color.rgb.div( color.a ), color.a );
  13670. }, { color: 'vec4', return: 'vec4' } );
  13671. // Deprecated
  13672. /**
  13673. * @tsl
  13674. * @function
  13675. * @deprecated since r171. Use {@link blendBurn} instead.
  13676. *
  13677. * @param {...any} params
  13678. * @returns {Function}
  13679. */
  13680. const burn = ( ...params ) => { // @deprecated, r171
  13681. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13682. return blendBurn( params );
  13683. };
  13684. /**
  13685. * @tsl
  13686. * @function
  13687. * @deprecated since r171. Use {@link blendDodge} instead.
  13688. *
  13689. * @param {...any} params
  13690. * @returns {Function}
  13691. */
  13692. const dodge = ( ...params ) => { // @deprecated, r171
  13693. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13694. return blendDodge( params );
  13695. };
  13696. /**
  13697. * @tsl
  13698. * @function
  13699. * @deprecated since r171. Use {@link blendScreen} instead.
  13700. *
  13701. * @param {...any} params
  13702. * @returns {Function}
  13703. */
  13704. const screen = ( ...params ) => { // @deprecated, r171
  13705. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13706. return blendScreen( params );
  13707. };
  13708. /**
  13709. * @tsl
  13710. * @function
  13711. * @deprecated since r171. Use {@link blendOverlay} instead.
  13712. *
  13713. * @param {...any} params
  13714. * @returns {Function}
  13715. */
  13716. const overlay = ( ...params ) => { // @deprecated, r171
  13717. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13718. return blendOverlay( params );
  13719. };
  13720. /**
  13721. * Base class for all node materials.
  13722. *
  13723. * @augments Material
  13724. */
  13725. class NodeMaterial extends Material {
  13726. static get type() {
  13727. return 'NodeMaterial';
  13728. }
  13729. /**
  13730. * Represents the type of the node material.
  13731. *
  13732. * @type {string}
  13733. */
  13734. get type() {
  13735. return this.constructor.type;
  13736. }
  13737. set type( _value ) { /* */ }
  13738. /**
  13739. * Constructs a new node material.
  13740. */
  13741. constructor() {
  13742. super();
  13743. /**
  13744. * This flag can be used for type testing.
  13745. *
  13746. * @type {boolean}
  13747. * @readonly
  13748. * @default true
  13749. */
  13750. this.isNodeMaterial = true;
  13751. /**
  13752. * Whether this material is affected by fog or not.
  13753. *
  13754. * @type {boolean}
  13755. * @default true
  13756. */
  13757. this.fog = true;
  13758. /**
  13759. * Whether this material is affected by lights or not.
  13760. *
  13761. * @type {boolean}
  13762. * @default false
  13763. */
  13764. this.lights = false;
  13765. /**
  13766. * Whether this material uses hardware clipping or not.
  13767. * This property is managed by the engine and should not be
  13768. * modified by apps.
  13769. *
  13770. * @type {boolean}
  13771. * @default false
  13772. */
  13773. this.hardwareClipping = false;
  13774. /**
  13775. * Node materials which set their `lights` property to `true`
  13776. * are affected by all lights of the scene. Sometimes selective
  13777. * lighting is wanted which means only _some_ lights in the scene
  13778. * affect a material. This can be achieved by creating an instance
  13779. * of {@link LightsNode} with a list of selective
  13780. * lights and assign the node to this property.
  13781. *
  13782. * ```js
  13783. * const customLightsNode = lights( [ light1, light2 ] );
  13784. * material.lightsNode = customLightsNode;
  13785. * ```
  13786. *
  13787. * @type {?LightsNode}
  13788. * @default null
  13789. */
  13790. this.lightsNode = null;
  13791. /**
  13792. * The environment of node materials can be defined by an environment
  13793. * map assigned to the `envMap` property or by `Scene.environment`
  13794. * if the node material is a PBR material. This node property allows to overwrite
  13795. * the default behavior and define the environment with a custom node.
  13796. *
  13797. * ```js
  13798. * material.envNode = pmremTexture( renderTarget.texture );
  13799. * ```
  13800. *
  13801. * @type {?Node<vec3>}
  13802. * @default null
  13803. */
  13804. this.envNode = null;
  13805. /**
  13806. * The lighting of node materials might be influenced by ambient occlusion.
  13807. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13808. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13809. * the default and define the ambient occlusion with a custom node instead.
  13810. *
  13811. * If you don't want to overwrite the diffuse color but modify the existing
  13812. * values instead, use {@link materialAO}.
  13813. *
  13814. * @type {?Node<float>}
  13815. * @default null
  13816. */
  13817. this.aoNode = null;
  13818. /**
  13819. * The diffuse color of node materials is by default inferred from the
  13820. * `color` and `map` properties. This node property allows to overwrite the default
  13821. * and define the diffuse color with a node instead.
  13822. *
  13823. * ```js
  13824. * material.colorNode = color( 0xff0000 ); // define red color
  13825. * ```
  13826. *
  13827. * If you don't want to overwrite the diffuse color but modify the existing
  13828. * values instead, use {@link materialColor}.
  13829. *
  13830. * ```js
  13831. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  13832. * ```
  13833. *
  13834. * @type {?Node<vec3>}
  13835. * @default null
  13836. */
  13837. this.colorNode = null;
  13838. /**
  13839. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  13840. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  13841. * and define the normals with a node instead.
  13842. *
  13843. * If you don't want to overwrite the normals but modify the existing values instead,
  13844. * use {@link materialNormal}.
  13845. *
  13846. * @type {?Node<vec3>}
  13847. * @default null
  13848. */
  13849. this.normalNode = null;
  13850. /**
  13851. * The opacity of node materials is by default inferred from the `opacity`
  13852. * and `alphaMap` properties. This node property allows to overwrite the default
  13853. * and define the opacity with a node instead.
  13854. *
  13855. * If you don't want to overwrite the normals but modify the existing
  13856. * value instead, use {@link materialOpacity}.
  13857. *
  13858. * @type {?Node<float>}
  13859. * @default null
  13860. */
  13861. this.opacityNode = null;
  13862. /**
  13863. * This node can be used to implement a variety of filter-like effects. The idea is
  13864. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  13865. * to create an arbitrary effect and then assign the node composition to this property.
  13866. * Everything behind the object using this material will now be affected by a filter.
  13867. *
  13868. * ```js
  13869. * const material = new NodeMaterial()
  13870. * material.transparent = true;
  13871. *
  13872. * // everything behind the object will be monochromatic
  13873. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  13874. * ```
  13875. *
  13876. * Backdrop computations are part of the lighting so only lit materials can use this property.
  13877. *
  13878. * @type {?Node<vec3>}
  13879. * @default null
  13880. */
  13881. this.backdropNode = null;
  13882. /**
  13883. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  13884. *
  13885. * @type {?Node<float>}
  13886. * @default null
  13887. */
  13888. this.backdropAlphaNode = null;
  13889. /**
  13890. * The alpha test of node materials is by default inferred from the `alphaTest`
  13891. * property. This node property allows to overwrite the default and define the
  13892. * alpha test with a node instead.
  13893. *
  13894. * If you don't want to overwrite the alpha test but modify the existing
  13895. * value instead, use {@link materialAlphaTest}.
  13896. *
  13897. * @type {?Node<float>}
  13898. * @default null
  13899. */
  13900. this.alphaTestNode = null;
  13901. /**
  13902. * Discards the fragment if the mask value is `false`.
  13903. *
  13904. * @type {?Node<bool>}
  13905. * @default null
  13906. */
  13907. this.maskNode = null;
  13908. /**
  13909. * The local vertex positions are computed based on multiple factors like the
  13910. * attribute data, morphing or skinning. This node property allows to overwrite
  13911. * the default and define local vertex positions with nodes instead.
  13912. *
  13913. * If you don't want to overwrite the vertex positions but modify the existing
  13914. * values instead, use {@link positionLocal}.
  13915. *
  13916. *```js
  13917. * material.positionNode = positionLocal.add( displace );
  13918. * ```
  13919. *
  13920. * @type {?Node<vec3>}
  13921. * @default null
  13922. */
  13923. this.positionNode = null;
  13924. /**
  13925. * This node property is intended for logic which modifies geometry data once or per animation step.
  13926. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  13927. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  13928. * can be implemented.
  13929. *
  13930. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  13931. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  13932. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  13933. * eventually assigned to `geometryNode`.
  13934. *
  13935. * @type {?Function}
  13936. * @default null
  13937. */
  13938. this.geometryNode = null;
  13939. /**
  13940. * Allows to overwrite depth values in the fragment shader.
  13941. *
  13942. * @type {?Node<float>}
  13943. * @default null
  13944. */
  13945. this.depthNode = null;
  13946. /**
  13947. * Allows to overwrite the position used for shadow map rendering which
  13948. * is by default {@link positionWorld}, the vertex position
  13949. * in world space.
  13950. *
  13951. * @type {?Node<float>}
  13952. * @default null
  13953. */
  13954. this.receivedShadowPositionNode = null;
  13955. /**
  13956. * Allows to overwrite the geometry position used for shadow map projection which
  13957. * is by default {@link positionLocal}, the vertex position in local space.
  13958. *
  13959. * @type {?Node<float>}
  13960. * @default null
  13961. */
  13962. this.castShadowPositionNode = null;
  13963. /**
  13964. * This node can be used to influence how an object using this node material
  13965. * receive shadows.
  13966. *
  13967. * ```js
  13968. * const totalShadows = float( 1 ).toVar();
  13969. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  13970. * totalShadows.mulAssign( shadow );
  13971. * //return float( 1 ); // bypass received shadows
  13972. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  13973. * } );
  13974. *
  13975. * @type {?(Function|FunctionNode<vec4>)}
  13976. * @default null
  13977. */
  13978. this.receivedShadowNode = null;
  13979. /**
  13980. * This node can be used to influence how an object using this node material
  13981. * casts shadows. To apply a color to shadows, you can simply do:
  13982. *
  13983. * ```js
  13984. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  13985. * ```
  13986. *
  13987. * Which can be nice to fake colored shadows of semi-transparent objects. It
  13988. * is also common to use the property with `Fn` function so checks are performed
  13989. * per fragment.
  13990. *
  13991. * ```js
  13992. * materialCustomShadow.castShadowNode = Fn( () => {
  13993. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  13994. * return materialColor;
  13995. * } )();
  13996. * ```
  13997. *
  13998. * @type {?Node<vec4>}
  13999. * @default null
  14000. */
  14001. this.castShadowNode = null;
  14002. /**
  14003. * This node can be used to define the final output of the material.
  14004. *
  14005. * TODO: Explain the differences to `fragmentNode`.
  14006. *
  14007. * @type {?Node<vec4>}
  14008. * @default null
  14009. */
  14010. this.outputNode = null;
  14011. /**
  14012. * MRT configuration is done on renderer or pass level. This node allows to
  14013. * overwrite what values are written into MRT targets on material level. This
  14014. * can be useful for implementing selective FX features that should only affect
  14015. * specific objects.
  14016. *
  14017. * @type {?MRTNode}
  14018. * @default null
  14019. */
  14020. this.mrtNode = null;
  14021. /**
  14022. * This node property can be used if you need complete freedom in implementing
  14023. * the fragment shader. Assigning a node will replace the built-in material
  14024. * logic used in the fragment stage.
  14025. *
  14026. * @type {?Node<vec4>}
  14027. * @default null
  14028. */
  14029. this.fragmentNode = null;
  14030. /**
  14031. * This node property can be used if you need complete freedom in implementing
  14032. * the vertex shader. Assigning a node will replace the built-in material logic
  14033. * used in the vertex stage.
  14034. *
  14035. * @type {?Node<vec4>}
  14036. * @default null
  14037. */
  14038. this.vertexNode = null;
  14039. // Deprecated properties
  14040. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  14041. get: () => {
  14042. return this.receivedShadowPositionNode;
  14043. },
  14044. set: ( value ) => {
  14045. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  14046. this.receivedShadowPositionNode = value;
  14047. }
  14048. } );
  14049. }
  14050. /**
  14051. * Allows to define a custom cache key that influence the material key computation
  14052. * for render objects.
  14053. *
  14054. * @return {string} The custom cache key.
  14055. */
  14056. customProgramCacheKey() {
  14057. return this.type + getCacheKey$1( this );
  14058. }
  14059. /**
  14060. * Builds this material with the given node builder.
  14061. *
  14062. * @param {NodeBuilder} builder - The current node builder.
  14063. */
  14064. build( builder ) {
  14065. this.setup( builder );
  14066. }
  14067. /**
  14068. * Setups a node material observer with the given builder.
  14069. *
  14070. * @param {NodeBuilder} builder - The current node builder.
  14071. * @return {NodeMaterialObserver} The node material observer.
  14072. */
  14073. setupObserver( builder ) {
  14074. return new NodeMaterialObserver( builder );
  14075. }
  14076. /**
  14077. * Setups the vertex and fragment stage of this node material.
  14078. *
  14079. * @param {NodeBuilder} builder - The current node builder.
  14080. */
  14081. setup( builder ) {
  14082. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  14083. builder.context.setupPositionView = () => this.setupPositionView( builder );
  14084. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  14085. const renderer = builder.renderer;
  14086. const renderTarget = renderer.getRenderTarget();
  14087. // < VERTEX STAGE >
  14088. builder.addStack();
  14089. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  14090. const vertexNode = this.vertexNode || mvp;
  14091. builder.stack.outputNode = vertexNode;
  14092. this.setupHardwareClipping( builder );
  14093. if ( this.geometryNode !== null ) {
  14094. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  14095. }
  14096. builder.addFlow( 'vertex', builder.removeStack() );
  14097. // < FRAGMENT STAGE >
  14098. builder.addStack();
  14099. let resultNode;
  14100. const clippingNode = this.setupClipping( builder );
  14101. if ( this.depthWrite === true || this.depthTest === true ) {
  14102. // only write depth if depth buffer is configured
  14103. if ( renderTarget !== null ) {
  14104. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  14105. } else {
  14106. if ( renderer.depth === true ) this.setupDepth( builder );
  14107. }
  14108. }
  14109. if ( this.fragmentNode === null ) {
  14110. this.setupDiffuseColor( builder );
  14111. this.setupVariants( builder );
  14112. const outgoingLightNode = this.setupLighting( builder );
  14113. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  14114. // force unsigned floats - useful for RenderTargets
  14115. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  14116. resultNode = this.setupOutput( builder, basicOutput );
  14117. // OUTPUT NODE
  14118. output.assign( resultNode );
  14119. //
  14120. const isCustomOutput = this.outputNode !== null;
  14121. if ( isCustomOutput ) resultNode = this.outputNode;
  14122. // MRT
  14123. if ( renderTarget !== null ) {
  14124. const mrt = renderer.getMRT();
  14125. const materialMRT = this.mrtNode;
  14126. if ( mrt !== null ) {
  14127. if ( isCustomOutput ) output.assign( resultNode );
  14128. resultNode = mrt;
  14129. if ( materialMRT !== null ) {
  14130. resultNode = mrt.merge( materialMRT );
  14131. }
  14132. } else if ( materialMRT !== null ) {
  14133. resultNode = materialMRT;
  14134. }
  14135. }
  14136. } else {
  14137. let fragmentNode = this.fragmentNode;
  14138. if ( fragmentNode.isOutputStructNode !== true ) {
  14139. fragmentNode = vec4( fragmentNode );
  14140. }
  14141. resultNode = this.setupOutput( builder, fragmentNode );
  14142. }
  14143. builder.stack.outputNode = resultNode;
  14144. builder.addFlow( 'fragment', builder.removeStack() );
  14145. // < OBSERVER >
  14146. builder.observer = this.setupObserver( builder );
  14147. }
  14148. /**
  14149. * Setups the clipping node.
  14150. *
  14151. * @param {NodeBuilder} builder - The current node builder.
  14152. * @return {ClippingNode} The clipping node.
  14153. */
  14154. setupClipping( builder ) {
  14155. if ( builder.clippingContext === null ) return null;
  14156. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14157. let result = null;
  14158. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14159. const samples = builder.renderer.currentSamples;
  14160. if ( this.alphaToCoverage && samples > 1 ) {
  14161. // to be added to flow when the color/alpha value has been determined
  14162. result = clippingAlpha();
  14163. } else {
  14164. builder.stack.add( clipping() );
  14165. }
  14166. }
  14167. return result;
  14168. }
  14169. /**
  14170. * Setups the hardware clipping if available on the current device.
  14171. *
  14172. * @param {NodeBuilder} builder - The current node builder.
  14173. */
  14174. setupHardwareClipping( builder ) {
  14175. this.hardwareClipping = false;
  14176. if ( builder.clippingContext === null ) return;
  14177. const candidateCount = builder.clippingContext.unionPlanes.length;
  14178. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14179. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14180. builder.stack.add( hardwareClipping() );
  14181. this.hardwareClipping = true;
  14182. }
  14183. return;
  14184. }
  14185. /**
  14186. * Setups the depth of this material.
  14187. *
  14188. * @param {NodeBuilder} builder - The current node builder.
  14189. */
  14190. setupDepth( builder ) {
  14191. const { renderer, camera } = builder;
  14192. // Depth
  14193. let depthNode = this.depthNode;
  14194. if ( depthNode === null ) {
  14195. const mrt = renderer.getMRT();
  14196. if ( mrt && mrt.has( 'depth' ) ) {
  14197. depthNode = mrt.get( 'depth' );
  14198. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14199. if ( camera.isPerspectiveCamera ) {
  14200. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14201. } else {
  14202. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14203. }
  14204. }
  14205. }
  14206. if ( depthNode !== null ) {
  14207. depth.assign( depthNode ).toStack();
  14208. }
  14209. }
  14210. /**
  14211. * Setups the position node in view space. This method exists
  14212. * so derived node materials can modify the implementation e.g. sprite materials.
  14213. *
  14214. * @param {NodeBuilder} builder - The current node builder.
  14215. * @return {Node<vec3>} The position in view space.
  14216. */
  14217. setupPositionView( /*builder*/ ) {
  14218. return modelViewMatrix.mul( positionLocal ).xyz;
  14219. }
  14220. /**
  14221. * Setups the position in clip space.
  14222. *
  14223. * @param {NodeBuilder} builder - The current node builder.
  14224. * @return {Node<vec4>} The position in view space.
  14225. */
  14226. setupModelViewProjection( /*builder*/ ) {
  14227. return cameraProjectionMatrix.mul( positionView );
  14228. }
  14229. /**
  14230. * Setups the logic for the vertex stage.
  14231. *
  14232. * @param {NodeBuilder} builder - The current node builder.
  14233. * @return {Node<vec4>} The position in clip space.
  14234. */
  14235. setupVertex( builder ) {
  14236. builder.addStack();
  14237. this.setupPosition( builder );
  14238. builder.context.vertex = builder.removeStack();
  14239. return modelViewProjection;
  14240. }
  14241. /**
  14242. * Setups the computation of the position in local space.
  14243. *
  14244. * @param {NodeBuilder} builder - The current node builder.
  14245. * @return {Node<vec3>} The position in local space.
  14246. */
  14247. setupPosition( builder ) {
  14248. const { object, geometry } = builder;
  14249. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14250. morphReference( object ).toStack();
  14251. }
  14252. if ( object.isSkinnedMesh === true ) {
  14253. skinning( object ).toStack();
  14254. }
  14255. if ( this.displacementMap ) {
  14256. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14257. const displacementScale = materialReference( 'displacementScale', 'float' );
  14258. const displacementBias = materialReference( 'displacementBias', 'float' );
  14259. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14260. }
  14261. if ( object.isBatchedMesh ) {
  14262. batch( object ).toStack();
  14263. }
  14264. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14265. instancedMesh( object ).toStack();
  14266. }
  14267. if ( this.positionNode !== null ) {
  14268. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14269. }
  14270. return positionLocal;
  14271. }
  14272. /**
  14273. * Setups the computation of the material's diffuse color.
  14274. *
  14275. * @param {NodeBuilder} builder - The current node builder.
  14276. * @param {BufferGeometry} geometry - The geometry.
  14277. */
  14278. setupDiffuseColor( { object, geometry } ) {
  14279. // MASK
  14280. if ( this.maskNode !== null ) {
  14281. // Discard if the mask is `false`
  14282. bool( this.maskNode ).not().discard();
  14283. }
  14284. // COLOR
  14285. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14286. // VERTEX COLORS
  14287. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14288. colorNode = colorNode.mul( vertexColor() );
  14289. }
  14290. // INSTANCED COLORS
  14291. if ( object.instanceColor ) {
  14292. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14293. colorNode = instanceColor.mul( colorNode );
  14294. }
  14295. if ( object.isBatchedMesh && object._colorsTexture ) {
  14296. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14297. colorNode = batchColor.mul( colorNode );
  14298. }
  14299. // DIFFUSE COLOR
  14300. diffuseColor.assign( colorNode );
  14301. // OPACITY
  14302. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14303. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14304. // ALPHA TEST
  14305. let alphaTestNode = null;
  14306. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14307. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14308. if ( this.alphaToCoverage === true ) {
  14309. diffuseColor.a = smoothstep( alphaTestNode, alphaTestNode.add( fwidth( diffuseColor.a ) ), diffuseColor.a );
  14310. diffuseColor.a.lessThanEqual( 0 ).discard();
  14311. } else {
  14312. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14313. }
  14314. }
  14315. // ALPHA HASH
  14316. if ( this.alphaHash === true ) {
  14317. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14318. }
  14319. // OPAQUE
  14320. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  14321. if ( isOpaque ) {
  14322. diffuseColor.a.assign( 1.0 );
  14323. }
  14324. }
  14325. /**
  14326. * Abstract interface method that can be implemented by derived materials
  14327. * to setup material-specific node variables.
  14328. *
  14329. * @abstract
  14330. * @param {NodeBuilder} builder - The current node builder.
  14331. */
  14332. setupVariants( /*builder*/ ) {
  14333. // Interface function.
  14334. }
  14335. /**
  14336. * Setups the outgoing light node variable
  14337. *
  14338. * @return {Node<vec3>} The outgoing light node.
  14339. */
  14340. setupOutgoingLight() {
  14341. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14342. }
  14343. /**
  14344. * Setups the normal node from the material.
  14345. *
  14346. * @return {Node<vec3>} The normal node.
  14347. */
  14348. setupNormal() {
  14349. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14350. }
  14351. /**
  14352. * Setups the environment node from the material.
  14353. *
  14354. * @param {NodeBuilder} builder - The current node builder.
  14355. * @return {Node<vec4>} The environment node.
  14356. */
  14357. setupEnvironment( /*builder*/ ) {
  14358. let node = null;
  14359. if ( this.envNode ) {
  14360. node = this.envNode;
  14361. } else if ( this.envMap ) {
  14362. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14363. }
  14364. return node;
  14365. }
  14366. /**
  14367. * Setups the light map node from the material.
  14368. *
  14369. * @param {NodeBuilder} builder - The current node builder.
  14370. * @return {Node<vec3>} The light map node.
  14371. */
  14372. setupLightMap( builder ) {
  14373. let node = null;
  14374. if ( builder.material.lightMap ) {
  14375. node = new IrradianceNode( materialLightMap );
  14376. }
  14377. return node;
  14378. }
  14379. /**
  14380. * Setups the lights node based on the scene, environment and material.
  14381. *
  14382. * @param {NodeBuilder} builder - The current node builder.
  14383. * @return {LightsNode} The lights node.
  14384. */
  14385. setupLights( builder ) {
  14386. const materialLightsNode = [];
  14387. //
  14388. const envNode = this.setupEnvironment( builder );
  14389. if ( envNode && envNode.isLightingNode ) {
  14390. materialLightsNode.push( envNode );
  14391. }
  14392. const lightMapNode = this.setupLightMap( builder );
  14393. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14394. materialLightsNode.push( lightMapNode );
  14395. }
  14396. if ( this.aoNode !== null || builder.material.aoMap ) {
  14397. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14398. materialLightsNode.push( new AONode( aoNode ) );
  14399. }
  14400. let lightsN = this.lightsNode || builder.lightsNode;
  14401. if ( materialLightsNode.length > 0 ) {
  14402. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14403. }
  14404. return lightsN;
  14405. }
  14406. /**
  14407. * This method should be implemented by most derived materials
  14408. * since it defines the material's lighting model.
  14409. *
  14410. * @abstract
  14411. * @param {NodeBuilder} builder - The current node builder.
  14412. * @return {LightingModel} The lighting model.
  14413. */
  14414. setupLightingModel( /*builder*/ ) {
  14415. // Interface function.
  14416. }
  14417. /**
  14418. * Setups the outgoing light node.
  14419. *
  14420. * @param {NodeBuilder} builder - The current node builder.
  14421. * @return {Node<vec3>} The outgoing light node.
  14422. */
  14423. setupLighting( builder ) {
  14424. const { material } = builder;
  14425. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14426. // OUTGOING LIGHT
  14427. const lights = this.lights === true || this.lightsNode !== null;
  14428. const lightsNode = lights ? this.setupLights( builder ) : null;
  14429. let outgoingLightNode = this.setupOutgoingLight( builder );
  14430. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14431. const lightingModel = this.setupLightingModel( builder ) || null;
  14432. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14433. } else if ( backdropNode !== null ) {
  14434. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14435. }
  14436. // EMISSIVE
  14437. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14438. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14439. outgoingLightNode = outgoingLightNode.add( emissive );
  14440. }
  14441. return outgoingLightNode;
  14442. }
  14443. /**
  14444. * Setup the fog.
  14445. *
  14446. * @param {NodeBuilder} builder - The current node builder.
  14447. * @param {Node<vec4>} outputNode - The existing output node.
  14448. * @return {Node<vec4>} The output node.
  14449. */
  14450. setupFog( builder, outputNode ) {
  14451. const fogNode = builder.fogNode;
  14452. if ( fogNode ) {
  14453. output.assign( outputNode );
  14454. outputNode = vec4( fogNode.toVar() );
  14455. }
  14456. return outputNode;
  14457. }
  14458. /**
  14459. * Setups premultiplied alpha.
  14460. *
  14461. * @param {NodeBuilder} builder - The current node builder.
  14462. * @param {Node<vec4>} outputNode - The existing output node.
  14463. * @return {Node<vec4>} The output node.
  14464. */
  14465. setupPremultipliedAlpha( builder, outputNode ) {
  14466. return premultiplyAlpha( outputNode );
  14467. }
  14468. /**
  14469. * Setups the output node.
  14470. *
  14471. * @param {NodeBuilder} builder - The current node builder.
  14472. * @param {Node<vec4>} outputNode - The existing output node.
  14473. * @return {Node<vec4>} The output node.
  14474. */
  14475. setupOutput( builder, outputNode ) {
  14476. // FOG
  14477. if ( this.fog === true ) {
  14478. outputNode = this.setupFog( builder, outputNode );
  14479. }
  14480. // PREMULTIPLIED ALPHA
  14481. if ( this.premultipliedAlpha === true ) {
  14482. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14483. }
  14484. return outputNode;
  14485. }
  14486. /**
  14487. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14488. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14489. * defining all material properties of the classic type in the node type.
  14490. *
  14491. * @param {Material} material - The material to copy properties with their values to this node material.
  14492. */
  14493. setDefaultValues( material ) {
  14494. // This approach is to reuse the native refreshUniforms*
  14495. // and turn available the use of features like transmission and environment in core
  14496. for ( const property in material ) {
  14497. const value = material[ property ];
  14498. if ( this[ property ] === undefined ) {
  14499. this[ property ] = value;
  14500. if ( value && value.clone ) this[ property ] = value.clone();
  14501. }
  14502. }
  14503. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14504. for ( const key in descriptors ) {
  14505. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14506. descriptors[ key ].get !== undefined ) {
  14507. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14508. }
  14509. }
  14510. }
  14511. /**
  14512. * Serializes this material to JSON.
  14513. *
  14514. * @param {?(Object|string)} meta - The meta information for serialization.
  14515. * @return {Object} The serialized node.
  14516. */
  14517. toJSON( meta ) {
  14518. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14519. if ( isRoot ) {
  14520. meta = {
  14521. textures: {},
  14522. images: {},
  14523. nodes: {}
  14524. };
  14525. }
  14526. const data = Material.prototype.toJSON.call( this, meta );
  14527. const nodeChildren = getNodeChildren( this );
  14528. data.inputNodes = {};
  14529. for ( const { property, childNode } of nodeChildren ) {
  14530. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14531. }
  14532. // TODO: Copied from Object3D.toJSON
  14533. function extractFromCache( cache ) {
  14534. const values = [];
  14535. for ( const key in cache ) {
  14536. const data = cache[ key ];
  14537. delete data.metadata;
  14538. values.push( data );
  14539. }
  14540. return values;
  14541. }
  14542. if ( isRoot ) {
  14543. const textures = extractFromCache( meta.textures );
  14544. const images = extractFromCache( meta.images );
  14545. const nodes = extractFromCache( meta.nodes );
  14546. if ( textures.length > 0 ) data.textures = textures;
  14547. if ( images.length > 0 ) data.images = images;
  14548. if ( nodes.length > 0 ) data.nodes = nodes;
  14549. }
  14550. return data;
  14551. }
  14552. /**
  14553. * Copies the properties of the given node material to this instance.
  14554. *
  14555. * @param {NodeMaterial} source - The material to copy.
  14556. * @return {NodeMaterial} A reference to this node material.
  14557. */
  14558. copy( source ) {
  14559. this.lightsNode = source.lightsNode;
  14560. this.envNode = source.envNode;
  14561. this.colorNode = source.colorNode;
  14562. this.normalNode = source.normalNode;
  14563. this.opacityNode = source.opacityNode;
  14564. this.backdropNode = source.backdropNode;
  14565. this.backdropAlphaNode = source.backdropAlphaNode;
  14566. this.alphaTestNode = source.alphaTestNode;
  14567. this.maskNode = source.maskNode;
  14568. this.positionNode = source.positionNode;
  14569. this.geometryNode = source.geometryNode;
  14570. this.depthNode = source.depthNode;
  14571. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14572. this.castShadowPositionNode = source.castShadowPositionNode;
  14573. this.receivedShadowNode = source.receivedShadowNode;
  14574. this.castShadowNode = source.castShadowNode;
  14575. this.outputNode = source.outputNode;
  14576. this.mrtNode = source.mrtNode;
  14577. this.fragmentNode = source.fragmentNode;
  14578. this.vertexNode = source.vertexNode;
  14579. return super.copy( source );
  14580. }
  14581. }
  14582. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14583. /**
  14584. * Node material version of {@link LineBasicMaterial}.
  14585. *
  14586. * @augments NodeMaterial
  14587. */
  14588. class LineBasicNodeMaterial extends NodeMaterial {
  14589. static get type() {
  14590. return 'LineBasicNodeMaterial';
  14591. }
  14592. /**
  14593. * Constructs a new line basic node material.
  14594. *
  14595. * @param {Object} [parameters] - The configuration parameter.
  14596. */
  14597. constructor( parameters ) {
  14598. super();
  14599. /**
  14600. * This flag can be used for type testing.
  14601. *
  14602. * @type {boolean}
  14603. * @readonly
  14604. * @default true
  14605. */
  14606. this.isLineBasicNodeMaterial = true;
  14607. this.setDefaultValues( _defaultValues$d );
  14608. this.setValues( parameters );
  14609. }
  14610. }
  14611. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14612. /**
  14613. * Node material version of {@link LineDashedMaterial}.
  14614. *
  14615. * @augments NodeMaterial
  14616. */
  14617. class LineDashedNodeMaterial extends NodeMaterial {
  14618. static get type() {
  14619. return 'LineDashedNodeMaterial';
  14620. }
  14621. /**
  14622. * Constructs a new line dashed node material.
  14623. *
  14624. * @param {Object} [parameters] - The configuration parameter.
  14625. */
  14626. constructor( parameters ) {
  14627. super();
  14628. /**
  14629. * This flag can be used for type testing.
  14630. *
  14631. * @type {boolean}
  14632. * @readonly
  14633. * @default true
  14634. */
  14635. this.isLineDashedNodeMaterial = true;
  14636. this.setDefaultValues( _defaultValues$c );
  14637. /**
  14638. * The dash offset.
  14639. *
  14640. * @type {number}
  14641. * @default 0
  14642. */
  14643. this.dashOffset = 0;
  14644. /**
  14645. * The offset of dash materials is by default inferred from the `dashOffset`
  14646. * property. This node property allows to overwrite the default
  14647. * and define the offset with a node instead.
  14648. *
  14649. * If you don't want to overwrite the offset but modify the existing
  14650. * value instead, use {@link materialLineDashOffset}.
  14651. *
  14652. * @type {?Node<float>}
  14653. * @default null
  14654. */
  14655. this.offsetNode = null;
  14656. /**
  14657. * The scale of dash materials is by default inferred from the `scale`
  14658. * property. This node property allows to overwrite the default
  14659. * and define the scale with a node instead.
  14660. *
  14661. * If you don't want to overwrite the scale but modify the existing
  14662. * value instead, use {@link materialLineScale}.
  14663. *
  14664. * @type {?Node<float>}
  14665. * @default null
  14666. */
  14667. this.dashScaleNode = null;
  14668. /**
  14669. * The dash size of dash materials is by default inferred from the `dashSize`
  14670. * property. This node property allows to overwrite the default
  14671. * and define the dash size with a node instead.
  14672. *
  14673. * If you don't want to overwrite the dash size but modify the existing
  14674. * value instead, use {@link materialLineDashSize}.
  14675. *
  14676. * @type {?Node<float>}
  14677. * @default null
  14678. */
  14679. this.dashSizeNode = null;
  14680. /**
  14681. * The gap size of dash materials is by default inferred from the `gapSize`
  14682. * property. This node property allows to overwrite the default
  14683. * and define the gap size with a node instead.
  14684. *
  14685. * If you don't want to overwrite the gap size but modify the existing
  14686. * value instead, use {@link materialLineGapSize}.
  14687. *
  14688. * @type {?Node<float>}
  14689. * @default null
  14690. */
  14691. this.gapSizeNode = null;
  14692. this.setValues( parameters );
  14693. }
  14694. /**
  14695. * Setups the dash specific node variables.
  14696. *
  14697. * @param {NodeBuilder} builder - The current node builder.
  14698. */
  14699. setupVariants( /* builder */ ) {
  14700. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14701. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14702. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14703. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14704. dashSize.assign( dashSizeNode );
  14705. gapSize.assign( gapSizeNode );
  14706. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14707. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14708. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14709. }
  14710. }
  14711. let _sharedFramebuffer = null;
  14712. /**
  14713. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14714. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14715. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14716. *
  14717. * @augments ViewportTextureNode
  14718. */
  14719. class ViewportSharedTextureNode extends ViewportTextureNode {
  14720. static get type() {
  14721. return 'ViewportSharedTextureNode';
  14722. }
  14723. /**
  14724. * Constructs a new viewport shared texture node.
  14725. *
  14726. * @param {Node} [uvNode=screenUV] - The uv node.
  14727. * @param {?Node} [levelNode=null] - The level node.
  14728. */
  14729. constructor( uvNode = screenUV, levelNode = null ) {
  14730. if ( _sharedFramebuffer === null ) {
  14731. _sharedFramebuffer = new FramebufferTexture();
  14732. }
  14733. super( uvNode, levelNode, _sharedFramebuffer );
  14734. }
  14735. /**
  14736. * Overwritten so the method always returns the unique shared
  14737. * framebuffer texture.
  14738. *
  14739. * @return {FramebufferTexture} The shared framebuffer texture.
  14740. */
  14741. getTextureForReference() {
  14742. return _sharedFramebuffer;
  14743. }
  14744. updateReference() {
  14745. return this;
  14746. }
  14747. }
  14748. /**
  14749. * TSL function for creating a shared viewport texture node.
  14750. *
  14751. * @tsl
  14752. * @function
  14753. * @param {?Node} [uvNode=screenUV] - The uv node.
  14754. * @param {?Node} [levelNode=null] - The level node.
  14755. * @returns {ViewportSharedTextureNode}
  14756. */
  14757. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14758. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14759. /**
  14760. * This node material can be used to render lines with a size larger than one
  14761. * by representing them as instanced meshes.
  14762. *
  14763. * @augments NodeMaterial
  14764. */
  14765. class Line2NodeMaterial extends NodeMaterial {
  14766. static get type() {
  14767. return 'Line2NodeMaterial';
  14768. }
  14769. /**
  14770. * Constructs a new node material for wide line rendering.
  14771. *
  14772. * @param {Object} [parameters={}] - The configuration parameter.
  14773. */
  14774. constructor( parameters = {} ) {
  14775. super();
  14776. /**
  14777. * This flag can be used for type testing.
  14778. *
  14779. * @type {boolean}
  14780. * @readonly
  14781. * @default true
  14782. */
  14783. this.isLine2NodeMaterial = true;
  14784. this.setDefaultValues( _defaultValues$b );
  14785. /**
  14786. * Whether vertex colors should be used or not.
  14787. *
  14788. * @type {boolean}
  14789. * @default false
  14790. */
  14791. this.useColor = parameters.vertexColors;
  14792. /**
  14793. * The dash offset.
  14794. *
  14795. * @type {number}
  14796. * @default 0
  14797. */
  14798. this.dashOffset = 0;
  14799. /**
  14800. * Defines the lines color.
  14801. *
  14802. * @type {?Node<vec3>}
  14803. * @default null
  14804. */
  14805. this.lineColorNode = null;
  14806. /**
  14807. * Defines the offset.
  14808. *
  14809. * @type {?Node<float>}
  14810. * @default null
  14811. */
  14812. this.offsetNode = null;
  14813. /**
  14814. * Defines the dash scale.
  14815. *
  14816. * @type {?Node<float>}
  14817. * @default null
  14818. */
  14819. this.dashScaleNode = null;
  14820. /**
  14821. * Defines the dash size.
  14822. *
  14823. * @type {?Node<float>}
  14824. * @default null
  14825. */
  14826. this.dashSizeNode = null;
  14827. /**
  14828. * Defines the gap size.
  14829. *
  14830. * @type {?Node<float>}
  14831. * @default null
  14832. */
  14833. this.gapSizeNode = null;
  14834. /**
  14835. * Blending is set to `NoBlending` since transparency
  14836. * is not supported, yet.
  14837. *
  14838. * @type {number}
  14839. * @default 0
  14840. */
  14841. this.blending = NoBlending;
  14842. this._useDash = parameters.dashed;
  14843. this._useAlphaToCoverage = true;
  14844. this._useWorldUnits = false;
  14845. this.setValues( parameters );
  14846. }
  14847. /**
  14848. * Setups the vertex and fragment stage of this node material.
  14849. *
  14850. * @param {NodeBuilder} builder - The current node builder.
  14851. */
  14852. setup( builder ) {
  14853. const { renderer } = builder;
  14854. const useAlphaToCoverage = this._useAlphaToCoverage;
  14855. const useColor = this.useColor;
  14856. const useDash = this._useDash;
  14857. const useWorldUnits = this._useWorldUnits;
  14858. const trimSegment = Fn( ( { start, end } ) => {
  14859. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  14860. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  14861. const nearEstimate = b.mul( -0.5 ).div( a );
  14862. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  14863. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  14864. } ).setLayout( {
  14865. name: 'trimSegment',
  14866. type: 'vec4',
  14867. inputs: [
  14868. { name: 'start', type: 'vec4' },
  14869. { name: 'end', type: 'vec4' }
  14870. ]
  14871. } );
  14872. this.vertexNode = Fn( () => {
  14873. const instanceStart = attribute( 'instanceStart' );
  14874. const instanceEnd = attribute( 'instanceEnd' );
  14875. // camera space
  14876. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  14877. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  14878. if ( useDash ) {
  14879. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14880. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14881. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  14882. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  14883. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  14884. lineDistance = lineDistance.add( offsetNode );
  14885. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  14886. }
  14887. if ( useWorldUnits ) {
  14888. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  14889. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  14890. }
  14891. const aspect = viewport.z.div( viewport.w );
  14892. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  14893. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  14894. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  14895. // perhaps there is a more elegant solution -- WestLangley
  14896. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  14897. If( perspective, () => {
  14898. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  14899. end.assign( trimSegment( { start: start, end: end } ) );
  14900. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  14901. start.assign( trimSegment( { start: end, end: start } ) );
  14902. } );
  14903. } );
  14904. // clip space
  14905. const clipStart = cameraProjectionMatrix.mul( start );
  14906. const clipEnd = cameraProjectionMatrix.mul( end );
  14907. // ndc space
  14908. const ndcStart = clipStart.xyz.div( clipStart.w );
  14909. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  14910. // direction
  14911. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  14912. // account for clip-space aspect ratio
  14913. dir.x.assign( dir.x.mul( aspect ) );
  14914. dir.assign( dir.normalize() );
  14915. const clip = vec4().toVar();
  14916. if ( useWorldUnits ) {
  14917. // get the offset direction as perpendicular to the view vector
  14918. const worldDir = end.xyz.sub( start.xyz ).normalize();
  14919. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  14920. const worldUp = worldDir.cross( tmpFwd ).normalize();
  14921. const worldFwd = worldDir.cross( worldUp );
  14922. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  14923. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  14924. // height offset
  14925. const hw = materialLineWidth.mul( 0.5 );
  14926. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  14927. // don't extend the line if we're rendering dashes because we
  14928. // won't be rendering the endcaps
  14929. if ( ! useDash ) {
  14930. // cap extension
  14931. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  14932. // add width to the box
  14933. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  14934. // endcaps
  14935. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  14936. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  14937. } );
  14938. }
  14939. // project the worldpos
  14940. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  14941. // shift the depth of the projected points so the line
  14942. // segments overlap neatly
  14943. const clipPose = vec3().toVar();
  14944. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  14945. clip.z.assign( clipPose.z.mul( clip.w ) );
  14946. } else {
  14947. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  14948. // undo aspect ratio adjustment
  14949. dir.x.assign( dir.x.div( aspect ) );
  14950. offset.x.assign( offset.x.div( aspect ) );
  14951. // sign flip
  14952. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  14953. // endcaps
  14954. If( positionGeometry.y.lessThan( 0.0 ), () => {
  14955. offset.assign( offset.sub( dir ) );
  14956. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  14957. offset.assign( offset.add( dir ) );
  14958. } );
  14959. // adjust for linewidth
  14960. offset.assign( offset.mul( materialLineWidth ) );
  14961. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  14962. offset.assign( offset.div( viewport.w ) );
  14963. // select end
  14964. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  14965. // back to clip space
  14966. offset.assign( offset.mul( clip.w ) );
  14967. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  14968. }
  14969. return clip;
  14970. } )();
  14971. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  14972. const p13 = p1.sub( p3 );
  14973. const p43 = p4.sub( p3 );
  14974. const p21 = p2.sub( p1 );
  14975. const d1343 = p13.dot( p43 );
  14976. const d4321 = p43.dot( p21 );
  14977. const d1321 = p13.dot( p21 );
  14978. const d4343 = p43.dot( p43 );
  14979. const d2121 = p21.dot( p21 );
  14980. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  14981. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  14982. const mua = numer.div( denom ).clamp();
  14983. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  14984. return vec2( mua, mub );
  14985. } );
  14986. this.colorNode = Fn( () => {
  14987. const vUv = uv$1();
  14988. if ( useDash ) {
  14989. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14990. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14991. dashSize.assign( dashSizeNode );
  14992. gapSize.assign( gapSizeNode );
  14993. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  14994. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  14995. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  14996. }
  14997. const alpha = float( 1 ).toVar( 'alpha' );
  14998. if ( useWorldUnits ) {
  14999. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  15000. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  15001. // Find the closest points on the view ray and the line segment
  15002. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  15003. const lineDir = worldEnd.sub( worldStart );
  15004. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  15005. const p1 = worldStart.add( lineDir.mul( params.x ) );
  15006. const p2 = rayEnd.mul( params.y );
  15007. const delta = p1.sub( p2 );
  15008. const len = delta.length();
  15009. const norm = len.div( materialLineWidth );
  15010. if ( ! useDash ) {
  15011. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15012. const dnorm = norm.fwidth();
  15013. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  15014. } else {
  15015. norm.greaterThan( 0.5 ).discard();
  15016. }
  15017. }
  15018. } else {
  15019. // round endcaps
  15020. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  15021. const a = vUv.x;
  15022. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15023. const len2 = a.mul( a ).add( b.mul( b ) );
  15024. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  15025. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15026. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  15027. } );
  15028. } else {
  15029. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  15030. const a = vUv.x;
  15031. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  15032. const len2 = a.mul( a ).add( b.mul( b ) );
  15033. len2.greaterThan( 1.0 ).discard();
  15034. } );
  15035. }
  15036. }
  15037. let lineColorNode;
  15038. if ( this.lineColorNode ) {
  15039. lineColorNode = this.lineColorNode;
  15040. } else {
  15041. if ( useColor ) {
  15042. const instanceColorStart = attribute( 'instanceColorStart' );
  15043. const instanceColorEnd = attribute( 'instanceColorEnd' );
  15044. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  15045. lineColorNode = instanceColor.mul( materialColor );
  15046. } else {
  15047. lineColorNode = materialColor;
  15048. }
  15049. }
  15050. return vec4( lineColorNode, alpha );
  15051. } )();
  15052. if ( this.transparent ) {
  15053. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15054. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  15055. }
  15056. super.setup( builder );
  15057. }
  15058. /**
  15059. * Whether the lines should sized in world units or not.
  15060. * When set to `false` the unit is pixel.
  15061. *
  15062. * @type {boolean}
  15063. * @default false
  15064. */
  15065. get worldUnits() {
  15066. return this._useWorldUnits;
  15067. }
  15068. set worldUnits( value ) {
  15069. if ( this._useWorldUnits !== value ) {
  15070. this._useWorldUnits = value;
  15071. this.needsUpdate = true;
  15072. }
  15073. }
  15074. /**
  15075. * Whether the lines should be dashed or not.
  15076. *
  15077. * @type {boolean}
  15078. * @default false
  15079. */
  15080. get dashed() {
  15081. return this._useDash;
  15082. }
  15083. set dashed( value ) {
  15084. if ( this._useDash !== value ) {
  15085. this._useDash = value;
  15086. this.needsUpdate = true;
  15087. }
  15088. }
  15089. /**
  15090. * Whether alpha to coverage should be used or not.
  15091. *
  15092. * @type {boolean}
  15093. * @default true
  15094. */
  15095. get alphaToCoverage() {
  15096. return this._useAlphaToCoverage;
  15097. }
  15098. set alphaToCoverage( value ) {
  15099. if ( this._useAlphaToCoverage !== value ) {
  15100. this._useAlphaToCoverage = value;
  15101. this.needsUpdate = true;
  15102. }
  15103. }
  15104. }
  15105. /**
  15106. * Packs a direction vector into a color value.
  15107. *
  15108. * @tsl
  15109. * @function
  15110. * @param {Node<vec3>} node - The direction to pack.
  15111. * @return {Node<vec3>} The color.
  15112. */
  15113. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  15114. /**
  15115. * Unpacks a color value into a direction vector.
  15116. *
  15117. * @tsl
  15118. * @function
  15119. * @param {Node<vec3>} node - The color to unpack.
  15120. * @return {Node<vec3>} The direction.
  15121. */
  15122. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  15123. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  15124. /**
  15125. * Node material version of {@link MeshNormalMaterial}.
  15126. *
  15127. * @augments NodeMaterial
  15128. */
  15129. class MeshNormalNodeMaterial extends NodeMaterial {
  15130. static get type() {
  15131. return 'MeshNormalNodeMaterial';
  15132. }
  15133. /**
  15134. * Constructs a new mesh normal node material.
  15135. *
  15136. * @param {Object} [parameters] - The configuration parameter.
  15137. */
  15138. constructor( parameters ) {
  15139. super();
  15140. /**
  15141. * This flag can be used for type testing.
  15142. *
  15143. * @type {boolean}
  15144. * @readonly
  15145. * @default true
  15146. */
  15147. this.isMeshNormalNodeMaterial = true;
  15148. this.setDefaultValues( _defaultValues$a );
  15149. this.setValues( parameters );
  15150. }
  15151. /**
  15152. * Overwrites the default implementation by computing the diffuse color
  15153. * based on the normal data.
  15154. */
  15155. setupDiffuseColor() {
  15156. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15157. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15158. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15159. }
  15160. }
  15161. /**
  15162. * TSL function for creating an equirect uv node.
  15163. *
  15164. * Can be used to compute texture coordinates for projecting an
  15165. * equirectangular texture onto a mesh for using it as the scene's
  15166. * background.
  15167. *
  15168. * ```js
  15169. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15170. * ```
  15171. *
  15172. * @tsl
  15173. * @function
  15174. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15175. * @returns {Node<vec2>}
  15176. */
  15177. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15178. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15179. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15180. return vec2( u, v );
  15181. } );
  15182. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15183. /**
  15184. * This class represents a cube render target. It is a special version
  15185. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15186. *
  15187. * @augments WebGLCubeRenderTarget
  15188. */
  15189. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15190. /**
  15191. * Constructs a new cube render target.
  15192. *
  15193. * @param {number} [size=1] - The size of the render target.
  15194. * @param {RenderTarget~Options} [options] - The configuration object.
  15195. */
  15196. constructor( size = 1, options = {} ) {
  15197. super( size, options );
  15198. /**
  15199. * This flag can be used for type testing.
  15200. *
  15201. * @type {boolean}
  15202. * @readonly
  15203. * @default true
  15204. */
  15205. this.isCubeRenderTarget = true;
  15206. }
  15207. /**
  15208. * Converts the given equirectangular texture to a cube map.
  15209. *
  15210. * @param {Renderer} renderer - The renderer.
  15211. * @param {Texture} texture - The equirectangular texture.
  15212. * @return {CubeRenderTarget} A reference to this cube render target.
  15213. */
  15214. fromEquirectangularTexture( renderer, texture$1 ) {
  15215. const currentMinFilter = texture$1.minFilter;
  15216. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15217. texture$1.generateMipmaps = true;
  15218. this.texture.type = texture$1.type;
  15219. this.texture.colorSpace = texture$1.colorSpace;
  15220. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15221. this.texture.minFilter = texture$1.minFilter;
  15222. this.texture.magFilter = texture$1.magFilter;
  15223. const geometry = new BoxGeometry( 5, 5, 5 );
  15224. const uvNode = equirectUV( positionWorldDirection );
  15225. const material = new NodeMaterial();
  15226. material.colorNode = texture( texture$1, uvNode, 0 );
  15227. material.side = BackSide;
  15228. material.blending = NoBlending;
  15229. const mesh = new Mesh( geometry, material );
  15230. const scene = new Scene();
  15231. scene.add( mesh );
  15232. // Avoid blurred poles
  15233. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15234. const camera = new CubeCamera( 1, 10, this );
  15235. const currentMRT = renderer.getMRT();
  15236. renderer.setMRT( null );
  15237. camera.update( renderer, scene );
  15238. renderer.setMRT( currentMRT );
  15239. texture$1.minFilter = currentMinFilter;
  15240. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15241. mesh.geometry.dispose();
  15242. mesh.material.dispose();
  15243. return this;
  15244. }
  15245. }
  15246. const _cache$1 = new WeakMap();
  15247. /**
  15248. * This node can be used to automatically convert environment maps in the
  15249. * equirectangular format into the cube map format.
  15250. *
  15251. * @augments TempNode
  15252. */
  15253. class CubeMapNode extends TempNode {
  15254. static get type() {
  15255. return 'CubeMapNode';
  15256. }
  15257. /**
  15258. * Constructs a new cube map node.
  15259. *
  15260. * @param {Node} envNode - The node representing the environment map.
  15261. */
  15262. constructor( envNode ) {
  15263. super( 'vec3' );
  15264. /**
  15265. * The node representing the environment map.
  15266. *
  15267. * @type {Node}
  15268. */
  15269. this.envNode = envNode;
  15270. /**
  15271. * A reference to the internal cube texture.
  15272. *
  15273. * @private
  15274. * @type {?CubeTexture}
  15275. * @default null
  15276. */
  15277. this._cubeTexture = null;
  15278. /**
  15279. * A reference to the internal cube texture node.
  15280. *
  15281. * @private
  15282. * @type {CubeTextureNode}
  15283. */
  15284. this._cubeTextureNode = cubeTexture( null );
  15285. const defaultTexture = new CubeTexture();
  15286. defaultTexture.isRenderTargetTexture = true;
  15287. /**
  15288. * A default cube texture that acts as a placeholder.
  15289. * It is used when the conversion from equirectangular to cube
  15290. * map has not finished yet for a given texture.
  15291. *
  15292. * @private
  15293. * @type {CubeTexture}
  15294. */
  15295. this._defaultTexture = defaultTexture;
  15296. /**
  15297. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15298. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15299. *
  15300. * @type {string}
  15301. * @default 'render'
  15302. */
  15303. this.updateBeforeType = NodeUpdateType.RENDER;
  15304. }
  15305. updateBefore( frame ) {
  15306. const { renderer, material } = frame;
  15307. const envNode = this.envNode;
  15308. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15309. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15310. if ( texture && texture.isTexture ) {
  15311. const mapping = texture.mapping;
  15312. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15313. // check for converted cubemap map
  15314. if ( _cache$1.has( texture ) ) {
  15315. const cubeMap = _cache$1.get( texture );
  15316. mapTextureMapping( cubeMap, texture.mapping );
  15317. this._cubeTexture = cubeMap;
  15318. } else {
  15319. // create cube map from equirectangular map
  15320. const image = texture.image;
  15321. if ( isEquirectangularMapReady$1( image ) ) {
  15322. const renderTarget = new CubeRenderTarget( image.height );
  15323. renderTarget.fromEquirectangularTexture( renderer, texture );
  15324. mapTextureMapping( renderTarget.texture, texture.mapping );
  15325. this._cubeTexture = renderTarget.texture;
  15326. _cache$1.set( texture, renderTarget.texture );
  15327. texture.addEventListener( 'dispose', onTextureDispose );
  15328. } else {
  15329. // default cube texture as fallback when equirectangular texture is not yet loaded
  15330. this._cubeTexture = this._defaultTexture;
  15331. }
  15332. }
  15333. //
  15334. this._cubeTextureNode.value = this._cubeTexture;
  15335. } else {
  15336. // envNode already refers to a cube map
  15337. this._cubeTextureNode = this.envNode;
  15338. }
  15339. }
  15340. }
  15341. }
  15342. setup( builder ) {
  15343. this.updateBefore( builder );
  15344. return this._cubeTextureNode;
  15345. }
  15346. }
  15347. /**
  15348. * Returns true if the given equirectangular image has been fully loaded
  15349. * and is ready for further processing.
  15350. *
  15351. * @private
  15352. * @param {Image} image - The equirectangular image to check.
  15353. * @return {boolean} Whether the image is ready or not.
  15354. */
  15355. function isEquirectangularMapReady$1( image ) {
  15356. if ( image === null || image === undefined ) return false;
  15357. return image.height > 0;
  15358. }
  15359. /**
  15360. * This function is executed when `dispose()` is called on the equirectangular
  15361. * texture. In this case, the generated cube map with its render target
  15362. * is deleted as well.
  15363. *
  15364. * @private
  15365. * @param {Object} event - The event object.
  15366. */
  15367. function onTextureDispose( event ) {
  15368. const texture = event.target;
  15369. texture.removeEventListener( 'dispose', onTextureDispose );
  15370. const renderTarget = _cache$1.get( texture );
  15371. if ( renderTarget !== undefined ) {
  15372. _cache$1.delete( texture );
  15373. renderTarget.dispose();
  15374. }
  15375. }
  15376. /**
  15377. * This function makes sure the generated cube map uses the correct
  15378. * texture mapping that corresponds to the equirectangular original.
  15379. *
  15380. * @private
  15381. * @param {Texture} texture - The cube texture.
  15382. * @param {number} mapping - The original texture mapping.
  15383. */
  15384. function mapTextureMapping( texture, mapping ) {
  15385. if ( mapping === EquirectangularReflectionMapping ) {
  15386. texture.mapping = CubeReflectionMapping;
  15387. } else if ( mapping === EquirectangularRefractionMapping ) {
  15388. texture.mapping = CubeRefractionMapping;
  15389. }
  15390. }
  15391. /**
  15392. * TSL function for creating a cube map node.
  15393. *
  15394. * @tsl
  15395. * @function
  15396. * @param {Node} envNode - The node representing the environment map.
  15397. * @returns {CubeMapNode}
  15398. */
  15399. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15400. /**
  15401. * Represents a basic model for Image-based lighting (IBL). The environment
  15402. * is defined via environment maps in the equirectangular or cube map format.
  15403. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15404. * or {@link MeshPhongNodeMaterial}.
  15405. *
  15406. * @augments LightingNode
  15407. */
  15408. class BasicEnvironmentNode extends LightingNode {
  15409. static get type() {
  15410. return 'BasicEnvironmentNode';
  15411. }
  15412. /**
  15413. * Constructs a new basic environment node.
  15414. *
  15415. * @param {Node} [envNode=null] - A node representing the environment.
  15416. */
  15417. constructor( envNode = null ) {
  15418. super();
  15419. /**
  15420. * A node representing the environment.
  15421. *
  15422. * @type {Node}
  15423. * @default null
  15424. */
  15425. this.envNode = envNode;
  15426. }
  15427. setup( builder ) {
  15428. // environment property is used in the finish() method of BasicLightingModel
  15429. builder.context.environment = cubeMapNode( this.envNode );
  15430. }
  15431. }
  15432. /**
  15433. * A specific version of {@link IrradianceNode} that is only relevant
  15434. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15435. * requires a special scaling factor for the light map.
  15436. *
  15437. * @augments LightingNode
  15438. */
  15439. class BasicLightMapNode extends LightingNode {
  15440. static get type() {
  15441. return 'BasicLightMapNode';
  15442. }
  15443. /**
  15444. * Constructs a new basic light map node.
  15445. *
  15446. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15447. */
  15448. constructor( lightMapNode = null ) {
  15449. super();
  15450. /**
  15451. * The light map node.
  15452. *
  15453. * @type {?Node<vec3>}
  15454. */
  15455. this.lightMapNode = lightMapNode;
  15456. }
  15457. setup( builder ) {
  15458. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15459. const RECIPROCAL_PI = float( 1 / Math.PI );
  15460. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15461. }
  15462. }
  15463. /**
  15464. * Abstract class for implementing lighting models. The module defines
  15465. * multiple methods that concrete lighting models can implement. These
  15466. * methods are executed at different points during the light evaluation
  15467. * process.
  15468. */
  15469. class LightingModel {
  15470. /**
  15471. * This method is intended for setting up lighting model and context data
  15472. * which are later used in the evaluation process.
  15473. *
  15474. * @abstract
  15475. * @param {NodeBuilder} builder - The current node builder.
  15476. */
  15477. start( builder ) {
  15478. // lights ( direct )
  15479. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15480. // indirect
  15481. this.indirect( builder );
  15482. }
  15483. /**
  15484. * This method is intended for executing final tasks like final updates
  15485. * to the outgoing light.
  15486. *
  15487. * @abstract
  15488. * @param {NodeBuilder} builder - The current node builder.
  15489. */
  15490. finish( /*builder*/ ) { }
  15491. /**
  15492. * This method is intended for implementing the direct light term and
  15493. * executed during the build process of directional, point and spot light nodes.
  15494. *
  15495. * @abstract
  15496. * @param {Object} lightData - The light data.
  15497. * @param {NodeBuilder} builder - The current node builder.
  15498. */
  15499. direct( /*lightData, builder*/ ) { }
  15500. /**
  15501. * This method is intended for implementing the direct light term for
  15502. * rect area light nodes.
  15503. *
  15504. * @abstract
  15505. * @param {Object} lightData - The light data.
  15506. * @param {NodeBuilder} builder - The current node builder.
  15507. */
  15508. directRectArea( /*lightData, builder*/ ) {}
  15509. /**
  15510. * This method is intended for implementing the indirect light term.
  15511. *
  15512. * @abstract
  15513. * @param {NodeBuilder} builder - The current node builder.
  15514. */
  15515. indirect( /*builder*/ ) { }
  15516. /**
  15517. * This method is intended for implementing the ambient occlusion term.
  15518. * Unlike other methods, this method must be called manually by the lighting
  15519. * model in its indirect term.
  15520. *
  15521. * @abstract
  15522. * @param {NodeBuilder} builder - The current node builder.
  15523. */
  15524. ambientOcclusion( /*input, stack, builder*/ ) { }
  15525. }
  15526. /**
  15527. * Represents the lighting model for unlit materials. The only light contribution
  15528. * is baked indirect lighting modulated with ambient occlusion and the material's
  15529. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15530. *
  15531. * @augments LightingModel
  15532. */
  15533. class BasicLightingModel extends LightingModel {
  15534. /**
  15535. * Constructs a new basic lighting model.
  15536. */
  15537. constructor() {
  15538. super();
  15539. }
  15540. /**
  15541. * Implements the baked indirect lighting with its modulation.
  15542. *
  15543. * @param {NodeBuilder} builder - The current node builder.
  15544. */
  15545. indirect( { context } ) {
  15546. const ambientOcclusion = context.ambientOcclusion;
  15547. const reflectedLight = context.reflectedLight;
  15548. const irradianceLightMap = context.irradianceLightMap;
  15549. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15550. // accumulation (baked indirect lighting only)
  15551. if ( irradianceLightMap ) {
  15552. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15553. } else {
  15554. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15555. }
  15556. // modulation
  15557. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15558. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15559. }
  15560. /**
  15561. * Implements the environment mapping.
  15562. *
  15563. * @param {NodeBuilder} builder - The current node builder.
  15564. */
  15565. finish( builder ) {
  15566. const { material, context } = builder;
  15567. const outgoingLight = context.outgoingLight;
  15568. const envNode = builder.context.environment;
  15569. if ( envNode ) {
  15570. switch ( material.combine ) {
  15571. case MultiplyOperation:
  15572. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15573. break;
  15574. case MixOperation:
  15575. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15576. break;
  15577. case AddOperation:
  15578. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15579. break;
  15580. default:
  15581. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  15582. break;
  15583. }
  15584. }
  15585. }
  15586. }
  15587. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15588. /**
  15589. * Node material version of {@link MeshBasicMaterial}.
  15590. *
  15591. * @augments NodeMaterial
  15592. */
  15593. class MeshBasicNodeMaterial extends NodeMaterial {
  15594. static get type() {
  15595. return 'MeshBasicNodeMaterial';
  15596. }
  15597. /**
  15598. * Constructs a new mesh basic node material.
  15599. *
  15600. * @param {Object} [parameters] - The configuration parameter.
  15601. */
  15602. constructor( parameters ) {
  15603. super();
  15604. /**
  15605. * This flag can be used for type testing.
  15606. *
  15607. * @type {boolean}
  15608. * @readonly
  15609. * @default true
  15610. */
  15611. this.isMeshBasicNodeMaterial = true;
  15612. /**
  15613. * Although the basic material is by definition unlit, we set
  15614. * this property to `true` since we use a lighting model to compute
  15615. * the outgoing light of the fragment shader.
  15616. *
  15617. * @type {boolean}
  15618. * @default true
  15619. */
  15620. this.lights = true;
  15621. this.setDefaultValues( _defaultValues$9 );
  15622. this.setValues( parameters );
  15623. }
  15624. /**
  15625. * Basic materials are not affected by normal and bump maps so we
  15626. * return by default {@link normalViewGeometry}.
  15627. *
  15628. * @return {Node<vec3>} The normal node.
  15629. */
  15630. setupNormal() {
  15631. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15632. }
  15633. /**
  15634. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15635. * to implement the default environment mapping.
  15636. *
  15637. * @param {NodeBuilder} builder - The current node builder.
  15638. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15639. */
  15640. setupEnvironment( builder ) {
  15641. const envNode = super.setupEnvironment( builder );
  15642. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15643. }
  15644. /**
  15645. * This method must be overwritten since light maps are evaluated
  15646. * with a special scaling factor for basic materials.
  15647. *
  15648. * @param {NodeBuilder} builder - The current node builder.
  15649. * @return {?BasicLightMapNode<vec3>} The light map node.
  15650. */
  15651. setupLightMap( builder ) {
  15652. let node = null;
  15653. if ( builder.material.lightMap ) {
  15654. node = new BasicLightMapNode( materialLightMap );
  15655. }
  15656. return node;
  15657. }
  15658. /**
  15659. * The material overwrites this method because `lights` is set to `true` but
  15660. * we still want to return the diffuse color as the outgoing light.
  15661. *
  15662. * @return {Node<vec3>} The outgoing light node.
  15663. */
  15664. setupOutgoingLight() {
  15665. return diffuseColor.rgb;
  15666. }
  15667. /**
  15668. * Setups the lighting model.
  15669. *
  15670. * @return {BasicLightingModel} The lighting model.
  15671. */
  15672. setupLightingModel() {
  15673. return new BasicLightingModel();
  15674. }
  15675. }
  15676. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15677. // Original approximation by Christophe Schlick '94
  15678. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15679. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15680. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15681. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15682. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15683. } ); // validated
  15684. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15685. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15686. } ); // validated
  15687. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15688. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15689. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15690. } );
  15691. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15692. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15693. const dotNH = normalView.dot( halfDir ).clamp();
  15694. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15695. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15696. const G = G_BlinnPhong_Implicit();
  15697. const D = D_BlinnPhong( { dotNH } );
  15698. return F.mul( G ).mul( D );
  15699. } );
  15700. /**
  15701. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15702. *
  15703. * @augments BasicLightingModel
  15704. */
  15705. class PhongLightingModel extends BasicLightingModel {
  15706. /**
  15707. * Constructs a new phong lighting model.
  15708. *
  15709. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15710. */
  15711. constructor( specular = true ) {
  15712. super();
  15713. /**
  15714. * Whether specular is supported or not. Set this to `false` if you are
  15715. * looking for a Lambert-like material meaning a material for non-shiny
  15716. * surfaces, without specular highlights.
  15717. *
  15718. * @type {boolean}
  15719. * @default true
  15720. */
  15721. this.specular = specular;
  15722. }
  15723. /**
  15724. * Implements the direct lighting. The specular portion is optional an can be controlled
  15725. * with the {@link PhongLightingModel#specular} flag.
  15726. *
  15727. * @param {Object} lightData - The light data.
  15728. */
  15729. direct( { lightDirection, lightColor, reflectedLight } ) {
  15730. const dotNL = normalView.dot( lightDirection ).clamp();
  15731. const irradiance = dotNL.mul( lightColor );
  15732. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15733. if ( this.specular === true ) {
  15734. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15735. }
  15736. }
  15737. /**
  15738. * Implements the indirect lighting.
  15739. *
  15740. * @param {NodeBuilder} builder - The current node builder.
  15741. */
  15742. indirect( builder ) {
  15743. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15744. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15745. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15746. }
  15747. }
  15748. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15749. /**
  15750. * Node material version of {@link MeshLambertMaterial}.
  15751. *
  15752. * @augments NodeMaterial
  15753. */
  15754. class MeshLambertNodeMaterial extends NodeMaterial {
  15755. static get type() {
  15756. return 'MeshLambertNodeMaterial';
  15757. }
  15758. /**
  15759. * Constructs a new mesh lambert node material.
  15760. *
  15761. * @param {Object} [parameters] - The configuration parameter.
  15762. */
  15763. constructor( parameters ) {
  15764. super();
  15765. /**
  15766. * This flag can be used for type testing.
  15767. *
  15768. * @type {boolean}
  15769. * @readonly
  15770. * @default true
  15771. */
  15772. this.isMeshLambertNodeMaterial = true;
  15773. /**
  15774. * Set to `true` because lambert materials react on lights.
  15775. *
  15776. * @type {boolean}
  15777. * @default true
  15778. */
  15779. this.lights = true;
  15780. this.setDefaultValues( _defaultValues$8 );
  15781. this.setValues( parameters );
  15782. }
  15783. /**
  15784. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15785. * to implement the default environment mapping.
  15786. *
  15787. * @param {NodeBuilder} builder - The current node builder.
  15788. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15789. */
  15790. setupEnvironment( builder ) {
  15791. const envNode = super.setupEnvironment( builder );
  15792. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15793. }
  15794. /**
  15795. * Setups the lighting model.
  15796. *
  15797. * @return {PhongLightingModel} The lighting model.
  15798. */
  15799. setupLightingModel( /*builder*/ ) {
  15800. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15801. }
  15802. }
  15803. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15804. /**
  15805. * Node material version of {@link MeshPhongMaterial}.
  15806. *
  15807. * @augments NodeMaterial
  15808. */
  15809. class MeshPhongNodeMaterial extends NodeMaterial {
  15810. static get type() {
  15811. return 'MeshPhongNodeMaterial';
  15812. }
  15813. /**
  15814. * Constructs a new mesh lambert node material.
  15815. *
  15816. * @param {Object} [parameters] - The configuration parameter.
  15817. */
  15818. constructor( parameters ) {
  15819. super();
  15820. /**
  15821. * This flag can be used for type testing.
  15822. *
  15823. * @type {boolean}
  15824. * @readonly
  15825. * @default true
  15826. */
  15827. this.isMeshPhongNodeMaterial = true;
  15828. /**
  15829. * Set to `true` because phong materials react on lights.
  15830. *
  15831. * @type {boolean}
  15832. * @default true
  15833. */
  15834. this.lights = true;
  15835. /**
  15836. * The shininess of phong materials is by default inferred from the `shininess`
  15837. * property. This node property allows to overwrite the default
  15838. * and define the shininess with a node instead.
  15839. *
  15840. * If you don't want to overwrite the shininess but modify the existing
  15841. * value instead, use {@link materialShininess}.
  15842. *
  15843. * @type {?Node<float>}
  15844. * @default null
  15845. */
  15846. this.shininessNode = null;
  15847. /**
  15848. * The specular color of phong materials is by default inferred from the
  15849. * `specular` property. This node property allows to overwrite the default
  15850. * and define the specular color with a node instead.
  15851. *
  15852. * If you don't want to overwrite the specular color but modify the existing
  15853. * value instead, use {@link materialSpecular}.
  15854. *
  15855. * @type {?Node<vec3>}
  15856. * @default null
  15857. */
  15858. this.specularNode = null;
  15859. this.setDefaultValues( _defaultValues$7 );
  15860. this.setValues( parameters );
  15861. }
  15862. /**
  15863. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15864. * to implement the default environment mapping.
  15865. *
  15866. * @param {NodeBuilder} builder - The current node builder.
  15867. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15868. */
  15869. setupEnvironment( builder ) {
  15870. const envNode = super.setupEnvironment( builder );
  15871. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15872. }
  15873. /**
  15874. * Setups the lighting model.
  15875. *
  15876. * @return {PhongLightingModel} The lighting model.
  15877. */
  15878. setupLightingModel( /*builder*/ ) {
  15879. return new PhongLightingModel();
  15880. }
  15881. /**
  15882. * Setups the phong specific node variables.
  15883. *
  15884. * @param {NodeBuilder} builder - The current node builder.
  15885. */
  15886. setupVariants( /*builder*/ ) {
  15887. // SHININESS
  15888. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15889. shininess.assign( shininessNode );
  15890. // SPECULAR COLOR
  15891. const specularNode = this.specularNode || materialSpecular;
  15892. specularColor.assign( specularNode );
  15893. }
  15894. copy( source ) {
  15895. this.shininessNode = source.shininessNode;
  15896. this.specularNode = source.specularNode;
  15897. return super.copy( source );
  15898. }
  15899. }
  15900. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  15901. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  15902. return float( 0 );
  15903. }
  15904. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  15905. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  15906. return geometryRoughness;
  15907. } );
  15908. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  15909. const { roughness } = inputs;
  15910. const geometryRoughness = getGeometryRoughness();
  15911. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  15912. roughnessFactor = roughnessFactor.add( geometryRoughness );
  15913. roughnessFactor = roughnessFactor.min( 1.0 );
  15914. return roughnessFactor;
  15915. } );
  15916. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  15917. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15918. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  15919. const a2 = alpha.pow2();
  15920. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  15921. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  15922. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  15923. } ).setLayout( {
  15924. name: 'V_GGX_SmithCorrelated',
  15925. type: 'float',
  15926. inputs: [
  15927. { name: 'alpha', type: 'float' },
  15928. { name: 'dotNL', type: 'float' },
  15929. { name: 'dotNV', type: 'float' }
  15930. ]
  15931. } ); // validated
  15932. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15933. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  15934. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  15935. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  15936. const v = div( 0.5, gv.add( gl ) );
  15937. return v.saturate();
  15938. } ).setLayout( {
  15939. name: 'V_GGX_SmithCorrelated_Anisotropic',
  15940. type: 'float',
  15941. inputs: [
  15942. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15943. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15944. { name: 'dotTV', type: 'float', qualifier: 'in' },
  15945. { name: 'dotBV', type: 'float', qualifier: 'in' },
  15946. { name: 'dotTL', type: 'float', qualifier: 'in' },
  15947. { name: 'dotBL', type: 'float', qualifier: 'in' },
  15948. { name: 'dotNV', type: 'float', qualifier: 'in' },
  15949. { name: 'dotNL', type: 'float', qualifier: 'in' }
  15950. ]
  15951. } );
  15952. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  15953. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  15954. // alpha is "roughness squared" in Disney’s reparameterization
  15955. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  15956. const a2 = alpha.pow2();
  15957. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  15958. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  15959. } ).setLayout( {
  15960. name: 'D_GGX',
  15961. type: 'float',
  15962. inputs: [
  15963. { name: 'alpha', type: 'float' },
  15964. { name: 'dotNH', type: 'float' }
  15965. ]
  15966. } ); // validated
  15967. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  15968. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15969. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  15970. const a2 = alphaT.mul( alphaB );
  15971. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  15972. const v2 = v.dot( v );
  15973. const w2 = a2.div( v2 );
  15974. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  15975. } ).setLayout( {
  15976. name: 'D_GGX_Anisotropic',
  15977. type: 'float',
  15978. inputs: [
  15979. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15980. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15981. { name: 'dotNH', type: 'float', qualifier: 'in' },
  15982. { name: 'dotTH', type: 'float', qualifier: 'in' },
  15983. { name: 'dotBH', type: 'float', qualifier: 'in' }
  15984. ]
  15985. } );
  15986. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  15987. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  15988. const alpha = roughness.pow2(); // UE4's roughness
  15989. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15990. const dotNL = normalView$1.dot( lightDirection ).clamp();
  15991. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15992. const dotNH = normalView$1.dot( halfDir ).clamp();
  15993. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15994. let F = F_Schlick( { f0, f90, dotVH } );
  15995. let V, D;
  15996. if ( defined( USE_IRIDESCENCE ) ) {
  15997. F = iridescence.mix( F, f );
  15998. }
  15999. if ( defined( USE_ANISOTROPY ) ) {
  16000. const dotTL = anisotropyT.dot( lightDirection );
  16001. const dotTV = anisotropyT.dot( positionViewDirection );
  16002. const dotTH = anisotropyT.dot( halfDir );
  16003. const dotBL = anisotropyB.dot( lightDirection );
  16004. const dotBV = anisotropyB.dot( positionViewDirection );
  16005. const dotBH = anisotropyB.dot( halfDir );
  16006. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  16007. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  16008. } else {
  16009. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  16010. D = D_GGX( { alpha, dotNH } );
  16011. }
  16012. return F.mul( V ).mul( D );
  16013. } ); // validated
  16014. // Analytical approximation of the DFG LUT, one half of the
  16015. // split-sum approximation used in indirect specular lighting.
  16016. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  16017. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  16018. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  16019. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  16020. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  16021. const r = roughness.mul( c0 ).add( c1 );
  16022. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  16023. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  16024. return fab;
  16025. } ).setLayout( {
  16026. name: 'DFGApprox',
  16027. type: 'vec2',
  16028. inputs: [
  16029. { name: 'roughness', type: 'float' },
  16030. { name: 'dotNV', type: 'vec3' }
  16031. ]
  16032. } );
  16033. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  16034. const { dotNV, specularColor, specularF90, roughness } = inputs;
  16035. const fab = DFGApprox( { dotNV, roughness } );
  16036. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16037. } );
  16038. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  16039. const x = dotVH.oneMinus().saturate();
  16040. const x2 = x.mul( x );
  16041. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  16042. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  16043. } ).setLayout( {
  16044. name: 'Schlick_to_F0',
  16045. type: 'vec3',
  16046. inputs: [
  16047. { name: 'f', type: 'vec3' },
  16048. { name: 'f90', type: 'float' },
  16049. { name: 'dotVH', type: 'float' }
  16050. ]
  16051. } );
  16052. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16053. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  16054. const alpha = roughness.pow2();
  16055. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  16056. const invAlpha = float( 1.0 ).div( alpha );
  16057. const cos2h = dotNH.pow2();
  16058. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  16059. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  16060. } ).setLayout( {
  16061. name: 'D_Charlie',
  16062. type: 'float',
  16063. inputs: [
  16064. { name: 'roughness', type: 'float' },
  16065. { name: 'dotNH', type: 'float' }
  16066. ]
  16067. } );
  16068. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  16069. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  16070. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  16071. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  16072. } ).setLayout( {
  16073. name: 'V_Neubelt',
  16074. type: 'float',
  16075. inputs: [
  16076. { name: 'dotNV', type: 'float' },
  16077. { name: 'dotNL', type: 'float' }
  16078. ]
  16079. } );
  16080. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  16081. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  16082. const dotNL = normalView.dot( lightDirection ).clamp();
  16083. const dotNV = normalView.dot( positionViewDirection ).clamp();
  16084. const dotNH = normalView.dot( halfDir ).clamp();
  16085. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  16086. const V = V_Neubelt( { dotNV, dotNL } );
  16087. return sheen.mul( D ).mul( V );
  16088. } );
  16089. // Rect Area Light
  16090. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  16091. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  16092. // code: https://github.com/selfshadow/ltc_code/
  16093. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  16094. const LUT_SIZE = 64.0;
  16095. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  16096. const LUT_BIAS = 0.5 / LUT_SIZE;
  16097. const dotNV = N.dot( V ).saturate();
  16098. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  16099. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  16100. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  16101. return uv;
  16102. } ).setLayout( {
  16103. name: 'LTC_Uv',
  16104. type: 'vec2',
  16105. inputs: [
  16106. { name: 'N', type: 'vec3' },
  16107. { name: 'V', type: 'vec3' },
  16108. { name: 'roughness', type: 'float' }
  16109. ]
  16110. } );
  16111. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  16112. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  16113. // An approximation of the form factor of a horizon-clipped rectangle.
  16114. const l = f.length();
  16115. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  16116. } ).setLayout( {
  16117. name: 'LTC_ClippedSphereFormFactor',
  16118. type: 'float',
  16119. inputs: [
  16120. { name: 'f', type: 'vec3' }
  16121. ]
  16122. } );
  16123. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  16124. const x = v1.dot( v2 );
  16125. const y = x.abs().toVar();
  16126. // rational polynomial approximation to theta / sin( theta ) / 2PI
  16127. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  16128. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  16129. const v = a.div( b );
  16130. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  16131. return v1.cross( v2 ).mul( theta_sintheta );
  16132. } ).setLayout( {
  16133. name: 'LTC_EdgeVectorFormFactor',
  16134. type: 'vec3',
  16135. inputs: [
  16136. { name: 'v1', type: 'vec3' },
  16137. { name: 'v2', type: 'vec3' }
  16138. ]
  16139. } );
  16140. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  16141. // bail if point is on back side of plane of light
  16142. // assumes ccw winding order of light vertices
  16143. const v1 = p1.sub( p0 ).toVar();
  16144. const v2 = p3.sub( p0 ).toVar();
  16145. const lightNormal = v1.cross( v2 );
  16146. const result = vec3().toVar();
  16147. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16148. // construct orthonormal basis around N
  16149. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16150. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16151. // compute transform
  16152. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16153. // transform rect
  16154. // & project rect onto sphere
  16155. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16156. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16157. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16158. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16159. // calculate vector form factor
  16160. const vectorFormFactor = vec3( 0 ).toVar();
  16161. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16162. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16163. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16164. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16165. // adjust for horizon clipping
  16166. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16167. } );
  16168. return result;
  16169. } ).setLayout( {
  16170. name: 'LTC_Evaluate',
  16171. type: 'vec3',
  16172. inputs: [
  16173. { name: 'N', type: 'vec3' },
  16174. { name: 'V', type: 'vec3' },
  16175. { name: 'P', type: 'vec3' },
  16176. { name: 'mInv', type: 'mat3' },
  16177. { name: 'p0', type: 'vec3' },
  16178. { name: 'p1', type: 'vec3' },
  16179. { name: 'p2', type: 'vec3' },
  16180. { name: 'p3', type: 'vec3' }
  16181. ]
  16182. } );
  16183. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16184. // bail if point is on back side of plane of light
  16185. // assumes ccw winding order of light vertices
  16186. const v1 = p1.sub( p0 ).toVar();
  16187. const v2 = p3.sub( p0 ).toVar();
  16188. const lightNormal = v1.cross( v2 );
  16189. const result = vec3().toVar();
  16190. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16191. // transform rect
  16192. // & project rect onto sphere
  16193. const coords0 = p0.sub( P ).normalize().toVar();
  16194. const coords1 = p1.sub( P ).normalize().toVar();
  16195. const coords2 = p2.sub( P ).normalize().toVar();
  16196. const coords3 = p3.sub( P ).normalize().toVar();
  16197. // calculate vector form factor
  16198. const vectorFormFactor = vec3( 0 ).toVar();
  16199. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16200. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16201. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16202. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16203. // adjust for horizon clipping
  16204. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16205. } );
  16206. return result;
  16207. } ).setLayout( {
  16208. name: 'LTC_Evaluate',
  16209. type: 'vec3',
  16210. inputs: [
  16211. { name: 'P', type: 'vec3' },
  16212. { name: 'p0', type: 'vec3' },
  16213. { name: 'p1', type: 'vec3' },
  16214. { name: 'p2', type: 'vec3' },
  16215. { name: 'p3', type: 'vec3' }
  16216. ]
  16217. } );
  16218. // Mipped Bicubic Texture Filtering by N8
  16219. // https://www.shadertoy.com/view/Dl2SDW
  16220. const bC = 1.0 / 6.0;
  16221. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16222. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16223. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16224. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16225. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16226. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16227. // h0 and h1 are the two offset functions
  16228. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16229. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16230. const bicubic = ( textureNode, texelSize, lod ) => {
  16231. const uv = textureNode.uvNode;
  16232. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16233. const iuv = floor( uvScaled );
  16234. const fuv = fract( uvScaled );
  16235. const g0x = g0( fuv.x );
  16236. const g1x = g1( fuv.x );
  16237. const h0x = h0( fuv.x );
  16238. const h1x = h1( fuv.x );
  16239. const h0y = h0( fuv.y );
  16240. const h1y = h1( fuv.y );
  16241. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16242. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16243. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16244. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16245. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16246. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16247. return a.add( b );
  16248. };
  16249. /**
  16250. * Applies mipped bicubic texture filtering to the given texture node.
  16251. *
  16252. * @tsl
  16253. * @function
  16254. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16255. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16256. * @return {Node} The filtered texture sample.
  16257. */
  16258. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16259. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16260. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16261. const fLodSizeInv = div( 1.0, fLodSize );
  16262. const cLodSizeInv = div( 1.0, cLodSize );
  16263. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16264. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16265. return fract( lodNode ).mix( fSample, cSample );
  16266. } );
  16267. /**
  16268. * Applies mipped bicubic texture filtering to the given texture node.
  16269. *
  16270. * @tsl
  16271. * @function
  16272. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16273. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16274. * @return {Node} The filtered texture sample.
  16275. */
  16276. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16277. const lod = strength.mul( maxMipLevel( textureNode ) );
  16278. return textureBicubicLevel( textureNode, lod );
  16279. } );
  16280. //
  16281. // Transmission
  16282. //
  16283. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16284. // Direction of refracted light.
  16285. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16286. // Compute rotation-independent scaling of the model matrix.
  16287. const modelScale = vec3(
  16288. length( modelMatrix[ 0 ].xyz ),
  16289. length( modelMatrix[ 1 ].xyz ),
  16290. length( modelMatrix[ 2 ].xyz )
  16291. );
  16292. // The thickness is specified in local space.
  16293. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16294. } ).setLayout( {
  16295. name: 'getVolumeTransmissionRay',
  16296. type: 'vec3',
  16297. inputs: [
  16298. { name: 'n', type: 'vec3' },
  16299. { name: 'v', type: 'vec3' },
  16300. { name: 'thickness', type: 'float' },
  16301. { name: 'ior', type: 'float' },
  16302. { name: 'modelMatrix', type: 'mat4' }
  16303. ]
  16304. } );
  16305. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16306. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16307. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16308. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16309. } ).setLayout( {
  16310. name: 'applyIorToRoughness',
  16311. type: 'float',
  16312. inputs: [
  16313. { name: 'roughness', type: 'float' },
  16314. { name: 'ior', type: 'float' }
  16315. ]
  16316. } );
  16317. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16318. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16319. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16320. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16321. const transmissionSample = vTexture.sample( fragCoord );
  16322. //const transmissionSample = viewportMipTexture( fragCoord );
  16323. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16324. return textureBicubicLevel( transmissionSample, lod );
  16325. } );
  16326. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16327. If( attenuationDistance.notEqual( 0 ), () => {
  16328. // Compute light attenuation using Beer's law.
  16329. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16330. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16331. return transmittance;
  16332. } );
  16333. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16334. return vec3( 1.0 );
  16335. } ).setLayout( {
  16336. name: 'volumeAttenuation',
  16337. type: 'vec3',
  16338. inputs: [
  16339. { name: 'transmissionDistance', type: 'float' },
  16340. { name: 'attenuationColor', type: 'vec3' },
  16341. { name: 'attenuationDistance', type: 'float' }
  16342. ]
  16343. } );
  16344. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16345. let transmittedLight, transmittance;
  16346. if ( dispersion ) {
  16347. transmittedLight = vec4().toVar();
  16348. transmittance = vec3().toVar();
  16349. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16350. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16351. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16352. const ior = iors.element( i );
  16353. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16354. const refractedRayExit = position.add( transmissionRay );
  16355. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16356. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16357. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16358. refractionCoords.addAssign( 1.0 );
  16359. refractionCoords.divAssign( 2.0 );
  16360. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16361. // Sample framebuffer to get pixel the refracted ray hits.
  16362. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16363. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16364. transmittedLight.a.addAssign( transmissionSample.a );
  16365. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16366. } );
  16367. transmittedLight.a.divAssign( 3.0 );
  16368. } else {
  16369. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16370. const refractedRayExit = position.add( transmissionRay );
  16371. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16372. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16373. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16374. refractionCoords.addAssign( 1.0 );
  16375. refractionCoords.divAssign( 2.0 );
  16376. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16377. // Sample framebuffer to get pixel the refracted ray hits.
  16378. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16379. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16380. }
  16381. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16382. const dotNV = n.dot( v ).clamp();
  16383. // Get the specular component.
  16384. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16385. dotNV,
  16386. specularColor,
  16387. specularF90,
  16388. roughness
  16389. } ) );
  16390. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16391. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16392. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16393. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16394. } );
  16395. //
  16396. // Iridescence
  16397. //
  16398. // XYZ to linear-sRGB color space
  16399. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16400. 3.2404542, -0.969266, 0.0556434,
  16401. -1.5371385, 1.8760108, -0.2040259,
  16402. -0.4985314, 0.0415560, 1.0572252
  16403. );
  16404. // Assume air interface for top
  16405. // Note: We don't handle the case fresnel0 == 1
  16406. const Fresnel0ToIor = ( fresnel0 ) => {
  16407. const sqrtF0 = fresnel0.sqrt();
  16408. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16409. };
  16410. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16411. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16412. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16413. };
  16414. // Fresnel equations for dielectric/dielectric interfaces.
  16415. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16416. // Evaluation XYZ sensitivity curves in Fourier space
  16417. const evalSensitivity = ( OPD, shift ) => {
  16418. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16419. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16420. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16421. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16422. 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() );
  16423. 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() );
  16424. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16425. const rgb = XYZ_TO_REC709.mul( xyz );
  16426. return rgb;
  16427. };
  16428. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16429. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16430. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16431. // Evaluate the cosTheta on the base layer (Snell law)
  16432. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16433. // Handle TIR:
  16434. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16435. If( cosTheta2Sq.lessThan( 0 ), () => {
  16436. return vec3( 1.0 );
  16437. } );
  16438. const cosTheta2 = cosTheta2Sq.sqrt();
  16439. // First interface
  16440. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16441. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16442. //const R21 = R12;
  16443. const T121 = R12.oneMinus();
  16444. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16445. const phi21 = float( Math.PI ).sub( phi12 );
  16446. // Second interface
  16447. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16448. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16449. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16450. const phi23 = vec3(
  16451. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16452. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16453. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16454. );
  16455. // Phase shift
  16456. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16457. const phi = vec3( phi21 ).add( phi23 );
  16458. // Compound terms
  16459. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16460. const r123 = R123.sqrt();
  16461. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16462. // Reflectance term for m = 0 (DC term amplitude)
  16463. const C0 = R12.add( Rs );
  16464. const I = C0.toVar();
  16465. // Reflectance term for m > 0 (pairs of diracs)
  16466. const Cm = Rs.sub( T121 ).toVar();
  16467. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16468. Cm.mulAssign( r123 );
  16469. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16470. I.addAssign( Cm.mul( Sm ) );
  16471. } );
  16472. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16473. return I.max( vec3( 0.0 ) );
  16474. } ).setLayout( {
  16475. name: 'evalIridescence',
  16476. type: 'vec3',
  16477. inputs: [
  16478. { name: 'outsideIOR', type: 'float' },
  16479. { name: 'eta2', type: 'float' },
  16480. { name: 'cosTheta1', type: 'float' },
  16481. { name: 'thinFilmThickness', type: 'float' },
  16482. { name: 'baseF0', type: 'vec3' }
  16483. ]
  16484. } );
  16485. //
  16486. // Sheen
  16487. //
  16488. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16489. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16490. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16491. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16492. const dotNV = normal.dot( viewDir ).saturate();
  16493. const r2 = roughness.pow2();
  16494. const a = select(
  16495. roughness.lessThan( 0.25 ),
  16496. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16497. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16498. );
  16499. const b = select(
  16500. roughness.lessThan( 0.25 ),
  16501. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16502. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16503. );
  16504. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16505. return DG.mul( 1.0 / Math.PI ).saturate();
  16506. } );
  16507. const clearcoatF0 = vec3( 0.04 );
  16508. const clearcoatF90 = float( 1 );
  16509. /**
  16510. * Represents the lighting model for a PBR material.
  16511. *
  16512. * @augments LightingModel
  16513. */
  16514. class PhysicalLightingModel extends LightingModel {
  16515. /**
  16516. * Constructs a new physical lighting model.
  16517. *
  16518. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16519. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16520. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16521. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16522. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16523. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16524. */
  16525. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16526. super();
  16527. /**
  16528. * Whether clearcoat is supported or not.
  16529. *
  16530. * @type {boolean}
  16531. * @default false
  16532. */
  16533. this.clearcoat = clearcoat;
  16534. /**
  16535. * Whether sheen is supported or not.
  16536. *
  16537. * @type {boolean}
  16538. * @default false
  16539. */
  16540. this.sheen = sheen;
  16541. /**
  16542. * Whether iridescence is supported or not.
  16543. *
  16544. * @type {boolean}
  16545. * @default false
  16546. */
  16547. this.iridescence = iridescence;
  16548. /**
  16549. * Whether anisotropy is supported or not.
  16550. *
  16551. * @type {boolean}
  16552. * @default false
  16553. */
  16554. this.anisotropy = anisotropy;
  16555. /**
  16556. * Whether transmission is supported or not.
  16557. *
  16558. * @type {boolean}
  16559. * @default false
  16560. */
  16561. this.transmission = transmission;
  16562. /**
  16563. * Whether dispersion is supported or not.
  16564. *
  16565. * @type {boolean}
  16566. * @default false
  16567. */
  16568. this.dispersion = dispersion;
  16569. /**
  16570. * The clear coat radiance.
  16571. *
  16572. * @type {?Node}
  16573. * @default null
  16574. */
  16575. this.clearcoatRadiance = null;
  16576. /**
  16577. * The clear coat specular direct.
  16578. *
  16579. * @type {?Node}
  16580. * @default null
  16581. */
  16582. this.clearcoatSpecularDirect = null;
  16583. /**
  16584. * The clear coat specular indirect.
  16585. *
  16586. * @type {?Node}
  16587. * @default null
  16588. */
  16589. this.clearcoatSpecularIndirect = null;
  16590. /**
  16591. * The sheen specular direct.
  16592. *
  16593. * @type {?Node}
  16594. * @default null
  16595. */
  16596. this.sheenSpecularDirect = null;
  16597. /**
  16598. * The sheen specular indirect.
  16599. *
  16600. * @type {?Node}
  16601. * @default null
  16602. */
  16603. this.sheenSpecularIndirect = null;
  16604. /**
  16605. * The iridescence Fresnel.
  16606. *
  16607. * @type {?Node}
  16608. * @default null
  16609. */
  16610. this.iridescenceFresnel = null;
  16611. /**
  16612. * The iridescence F0.
  16613. *
  16614. * @type {?Node}
  16615. * @default null
  16616. */
  16617. this.iridescenceF0 = null;
  16618. }
  16619. /**
  16620. * Depending on what features are requested, the method prepares certain node variables
  16621. * which are later used for lighting computations.
  16622. *
  16623. * @param {NodeBuilder} builder - The current node builder.
  16624. */
  16625. start( builder ) {
  16626. if ( this.clearcoat === true ) {
  16627. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16628. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16629. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16630. }
  16631. if ( this.sheen === true ) {
  16632. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16633. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16634. }
  16635. if ( this.iridescence === true ) {
  16636. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16637. this.iridescenceFresnel = evalIridescence( {
  16638. outsideIOR: float( 1.0 ),
  16639. eta2: iridescenceIOR,
  16640. cosTheta1: dotNVi,
  16641. thinFilmThickness: iridescenceThickness,
  16642. baseF0: specularColor
  16643. } );
  16644. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16645. }
  16646. if ( this.transmission === true ) {
  16647. const position = positionWorld;
  16648. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16649. const n = normalWorld;
  16650. const context = builder.context;
  16651. context.backdrop = getIBLVolumeRefraction(
  16652. n,
  16653. v,
  16654. roughness,
  16655. diffuseColor,
  16656. specularColor,
  16657. specularF90, // specularF90
  16658. position, // positionWorld
  16659. modelWorldMatrix, // modelMatrix
  16660. cameraViewMatrix, // viewMatrix
  16661. cameraProjectionMatrix, // projMatrix
  16662. ior,
  16663. thickness,
  16664. attenuationColor,
  16665. attenuationDistance,
  16666. this.dispersion ? dispersion : null
  16667. );
  16668. context.backdropAlpha = transmission;
  16669. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16670. }
  16671. super.start( builder );
  16672. }
  16673. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16674. // Approximates multi-scattering in order to preserve energy.
  16675. // http://www.jcgt.org/published/0008/01/03/
  16676. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16677. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16678. const fab = DFGApprox( { roughness, dotNV } );
  16679. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16680. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16681. const Ess = fab.x.add( fab.y );
  16682. const Ems = Ess.oneMinus();
  16683. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16684. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16685. singleScatter.addAssign( FssEss );
  16686. multiScatter.addAssign( Fms.mul( Ems ) );
  16687. }
  16688. /**
  16689. * Implements the direct light.
  16690. *
  16691. * @param {Object} lightData - The light data.
  16692. * @param {NodeBuilder} builder - The current node builder.
  16693. */
  16694. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16695. const dotNL = normalView.dot( lightDirection ).clamp();
  16696. const irradiance = dotNL.mul( lightColor );
  16697. if ( this.sheen === true ) {
  16698. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16699. }
  16700. if ( this.clearcoat === true ) {
  16701. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16702. const ccIrradiance = dotNLcc.mul( lightColor );
  16703. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16704. }
  16705. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16706. 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 } ) ) );
  16707. }
  16708. /**
  16709. * This method is intended for implementing the direct light term for
  16710. * rect area light nodes.
  16711. *
  16712. * @param {Object} input - The input data.
  16713. * @param {NodeBuilder} builder - The current node builder.
  16714. */
  16715. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16716. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16717. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16718. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16719. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16720. const N = normalView;
  16721. const V = positionViewDirection;
  16722. const P = positionView.toVar();
  16723. const uv = LTC_Uv( { N, V, roughness } );
  16724. const t1 = ltc_1.sample( uv ).toVar();
  16725. const t2 = ltc_2.sample( uv ).toVar();
  16726. const mInv = mat3(
  16727. vec3( t1.x, 0, t1.y ),
  16728. vec3( 0, 1, 0 ),
  16729. vec3( t1.z, 0, t1.w )
  16730. ).toVar();
  16731. // LTC Fresnel Approximation by Stephen Hill
  16732. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16733. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16734. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16735. 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 } ) ) );
  16736. }
  16737. /**
  16738. * Implements the indirect lighting.
  16739. *
  16740. * @param {NodeBuilder} builder - The current node builder.
  16741. */
  16742. indirect( builder ) {
  16743. this.indirectDiffuse( builder );
  16744. this.indirectSpecular( builder );
  16745. this.ambientOcclusion( builder );
  16746. }
  16747. /**
  16748. * Implements the indirect diffuse term.
  16749. *
  16750. * @param {NodeBuilder} builder - The current node builder.
  16751. */
  16752. indirectDiffuse( builder ) {
  16753. const { irradiance, reflectedLight } = builder.context;
  16754. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16755. }
  16756. /**
  16757. * Implements the indirect specular term.
  16758. *
  16759. * @param {NodeBuilder} builder - The current node builder.
  16760. */
  16761. indirectSpecular( builder ) {
  16762. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16763. if ( this.sheen === true ) {
  16764. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16765. sheen,
  16766. IBLSheenBRDF( {
  16767. normal: normalView,
  16768. viewDir: positionViewDirection,
  16769. roughness: sheenRoughness
  16770. } )
  16771. ) );
  16772. }
  16773. if ( this.clearcoat === true ) {
  16774. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16775. const clearcoatEnv = EnvironmentBRDF( {
  16776. dotNV: dotNVcc,
  16777. specularColor: clearcoatF0,
  16778. specularF90: clearcoatF90,
  16779. roughness: clearcoatRoughness
  16780. } );
  16781. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16782. }
  16783. // Both indirect specular and indirect diffuse light accumulate here
  16784. const singleScattering = vec3().toVar( 'singleScattering' );
  16785. const multiScattering = vec3().toVar( 'multiScattering' );
  16786. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16787. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16788. const totalScattering = singleScattering.add( multiScattering );
  16789. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16790. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16791. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16792. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16793. }
  16794. /**
  16795. * Implements the ambient occlusion term.
  16796. *
  16797. * @param {NodeBuilder} builder - The current node builder.
  16798. */
  16799. ambientOcclusion( builder ) {
  16800. const { ambientOcclusion, reflectedLight } = builder.context;
  16801. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16802. const aoNV = dotNV.add( ambientOcclusion );
  16803. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16804. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16805. if ( this.clearcoat === true ) {
  16806. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16807. }
  16808. if ( this.sheen === true ) {
  16809. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16810. }
  16811. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16812. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16813. }
  16814. /**
  16815. * Used for final lighting accumulations depending on the requested features.
  16816. *
  16817. * @param {NodeBuilder} builder - The current node builder.
  16818. */
  16819. finish( { context } ) {
  16820. const { outgoingLight } = context;
  16821. if ( this.clearcoat === true ) {
  16822. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16823. const Fcc = F_Schlick( {
  16824. dotVH: dotNVcc,
  16825. f0: clearcoatF0,
  16826. f90: clearcoatF90
  16827. } );
  16828. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  16829. outgoingLight.assign( clearcoatLight );
  16830. }
  16831. if ( this.sheen === true ) {
  16832. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  16833. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  16834. outgoingLight.assign( sheenLight );
  16835. }
  16836. }
  16837. }
  16838. // These defines must match with PMREMGenerator
  16839. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  16840. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  16841. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  16842. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  16843. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  16844. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  16845. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  16846. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  16847. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  16848. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  16849. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  16850. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  16851. // These shader functions convert between the UV coordinates of a single face of
  16852. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  16853. // sampling a textureCube (not generally normalized ).
  16854. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  16855. const absDirection = vec3( abs( direction ) ).toVar();
  16856. const face = float( -1 ).toVar();
  16857. If( absDirection.x.greaterThan( absDirection.z ), () => {
  16858. If( absDirection.x.greaterThan( absDirection.y ), () => {
  16859. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  16860. } ).Else( () => {
  16861. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16862. } );
  16863. } ).Else( () => {
  16864. If( absDirection.z.greaterThan( absDirection.y ), () => {
  16865. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  16866. } ).Else( () => {
  16867. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16868. } );
  16869. } );
  16870. return face;
  16871. } ).setLayout( {
  16872. name: 'getFace',
  16873. type: 'float',
  16874. inputs: [
  16875. { name: 'direction', type: 'vec3' }
  16876. ]
  16877. } );
  16878. // RH coordinate system; PMREM face-indexing convention
  16879. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  16880. const uv = vec2().toVar();
  16881. If( face.equal( 0.0 ), () => {
  16882. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  16883. } ).ElseIf( face.equal( 1.0 ), () => {
  16884. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  16885. } ).ElseIf( face.equal( 2.0 ), () => {
  16886. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  16887. } ).ElseIf( face.equal( 3.0 ), () => {
  16888. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  16889. } ).ElseIf( face.equal( 4.0 ), () => {
  16890. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  16891. } ).Else( () => {
  16892. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  16893. } );
  16894. return mul( 0.5, uv.add( 1.0 ) );
  16895. } ).setLayout( {
  16896. name: 'getUV',
  16897. type: 'vec2',
  16898. inputs: [
  16899. { name: 'direction', type: 'vec3' },
  16900. { name: 'face', type: 'float' }
  16901. ]
  16902. } );
  16903. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  16904. const mip = float( 0.0 ).toVar();
  16905. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  16906. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  16907. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  16908. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  16909. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  16910. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  16911. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  16912. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  16913. } ).Else( () => {
  16914. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  16915. } );
  16916. return mip;
  16917. } ).setLayout( {
  16918. name: 'roughnessToMip',
  16919. type: 'float',
  16920. inputs: [
  16921. { name: 'roughness', type: 'float' }
  16922. ]
  16923. } );
  16924. // RH coordinate system; PMREM face-indexing convention
  16925. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  16926. const uv = uv_immutable.toVar();
  16927. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  16928. const direction = vec3( uv, 1.0 ).toVar();
  16929. If( face.equal( 0.0 ), () => {
  16930. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  16931. } ).ElseIf( face.equal( 1.0 ), () => {
  16932. direction.assign( direction.xzy );
  16933. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  16934. } ).ElseIf( face.equal( 2.0 ), () => {
  16935. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  16936. } ).ElseIf( face.equal( 3.0 ), () => {
  16937. direction.assign( direction.zyx );
  16938. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  16939. } ).ElseIf( face.equal( 4.0 ), () => {
  16940. direction.assign( direction.xzy );
  16941. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  16942. } ).ElseIf( face.equal( 5.0 ), () => {
  16943. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  16944. } );
  16945. return direction;
  16946. } ).setLayout( {
  16947. name: 'getDirection',
  16948. type: 'vec3',
  16949. inputs: [
  16950. { name: 'uv', type: 'vec2' },
  16951. { name: 'face', type: 'float' }
  16952. ]
  16953. } );
  16954. //
  16955. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16956. const roughness = float( roughness_immutable );
  16957. const sampleDir = vec3( sampleDir_immutable );
  16958. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  16959. const mipF = fract( mip );
  16960. const mipInt = floor( mip );
  16961. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16962. If( mipF.notEqual( 0.0 ), () => {
  16963. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16964. color0.assign( mix( color0, color1, mipF ) );
  16965. } );
  16966. return color0;
  16967. } );
  16968. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16969. const mipInt = float( mipInt_immutable ).toVar();
  16970. const direction = vec3( direction_immutable );
  16971. const face = float( getFace( direction ) ).toVar();
  16972. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  16973. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  16974. const faceSize = float( exp2( mipInt ) ).toVar();
  16975. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  16976. If( face.greaterThan( 2.0 ), () => {
  16977. uv.y.addAssign( faceSize );
  16978. face.subAssign( 3.0 );
  16979. } );
  16980. uv.x.addAssign( face.mul( faceSize ) );
  16981. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  16982. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  16983. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  16984. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  16985. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  16986. } );
  16987. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16988. const cosTheta = cos( theta );
  16989. // Rodrigues' axis-angle rotation
  16990. const sampleDirection = outputDirection.mul( cosTheta )
  16991. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  16992. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  16993. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  16994. } );
  16995. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16996. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  16997. If( axis.equal( vec3( 0.0 ) ), () => {
  16998. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  16999. } );
  17000. axis.assign( normalize( axis ) );
  17001. const gl_FragColor = vec3().toVar();
  17002. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17003. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  17004. If( i.greaterThanEqual( samples ), () => {
  17005. Break();
  17006. } );
  17007. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  17008. 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 } ) ) );
  17009. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  17010. } );
  17011. return vec4( gl_FragColor, 1 );
  17012. } );
  17013. const LOD_MIN = 4;
  17014. // The standard deviations (radians) associated with the extra mips. These are
  17015. // chosen to approximate a Trowbridge-Reitz distribution function times the
  17016. // geometric shadowing function. These sigma values squared must match the
  17017. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  17018. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  17019. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  17020. // samples and exit early, but not recompile the shader.
  17021. const MAX_SAMPLES = 20;
  17022. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  17023. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  17024. const _clearColor$2 = /*@__PURE__*/ new Color();
  17025. let _oldTarget = null;
  17026. let _oldActiveCubeFace = 0;
  17027. let _oldActiveMipmapLevel = 0;
  17028. // Golden Ratio
  17029. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  17030. const INV_PHI = 1 / PHI;
  17031. // Vertices of a dodecahedron (except the opposites, which represent the
  17032. // same axis), used as axis directions evenly spread on a sphere.
  17033. const _axisDirections = [
  17034. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  17035. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  17036. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  17037. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  17038. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  17039. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  17040. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  17041. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  17042. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  17043. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  17044. ];
  17045. const _origin = /*@__PURE__*/ new Vector3();
  17046. // maps blur materials to their uniforms dictionary
  17047. const _uniformsMap = new WeakMap();
  17048. // WebGPU Face indices
  17049. const _faceLib = [
  17050. 3, 1, 5,
  17051. 0, 4, 2
  17052. ];
  17053. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  17054. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  17055. /**
  17056. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  17057. * (PMREM) from a cubeMap environment texture. This allows different levels of
  17058. * blur to be quickly accessed based on material roughness. It is packed into a
  17059. * special CubeUV format that allows us to perform custom interpolation so that
  17060. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  17061. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  17062. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  17063. * higher roughness levels. In this way we maintain resolution to smoothly
  17064. * interpolate diffuse lighting while limiting sampling computation.
  17065. *
  17066. * Paper: Fast, Accurate Image-Based Lighting:
  17067. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  17068. */
  17069. class PMREMGenerator {
  17070. /**
  17071. * Constructs a new PMREM generator.
  17072. *
  17073. * @param {Renderer} renderer - The renderer.
  17074. */
  17075. constructor( renderer ) {
  17076. this._renderer = renderer;
  17077. this._pingPongRenderTarget = null;
  17078. this._lodMax = 0;
  17079. this._cubeSize = 0;
  17080. this._lodPlanes = [];
  17081. this._sizeLods = [];
  17082. this._sigmas = [];
  17083. this._lodMeshes = [];
  17084. this._blurMaterial = null;
  17085. this._cubemapMaterial = null;
  17086. this._equirectMaterial = null;
  17087. this._backgroundBox = null;
  17088. }
  17089. get _hasInitialized() {
  17090. return this._renderer.hasInitialized();
  17091. }
  17092. /**
  17093. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17094. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17095. * in radians to be applied to the scene before PMREM generation. Optional near
  17096. * and far planes ensure the scene is rendered in its entirety.
  17097. *
  17098. * @param {Scene} scene - The scene to be captured.
  17099. * @param {number} [sigma=0] - The blur radius in radians.
  17100. * @param {number} [near=0.1] - The near plane distance.
  17101. * @param {number} [far=100] - The far plane distance.
  17102. * @param {Object} [options={}] - The configuration options.
  17103. * @param {number} [options.size=256] - The texture size of the PMREM.
  17104. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  17105. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17106. * @return {RenderTarget} The resulting PMREM.
  17107. * @see {@link PMREMGenerator#fromSceneAsync}
  17108. */
  17109. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17110. const {
  17111. size = 256,
  17112. position = _origin,
  17113. renderTarget = null,
  17114. } = options;
  17115. this._setSize( size );
  17116. if ( this._hasInitialized === false ) {
  17117. warn( 'PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  17118. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17119. options.renderTarget = cubeUVRenderTarget;
  17120. this.fromSceneAsync( scene, sigma, near, far, options );
  17121. return cubeUVRenderTarget;
  17122. }
  17123. _oldTarget = this._renderer.getRenderTarget();
  17124. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17125. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17126. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17127. cubeUVRenderTarget.depthBuffer = true;
  17128. this._init( cubeUVRenderTarget );
  17129. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  17130. if ( sigma > 0 ) {
  17131. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  17132. }
  17133. this._applyPMREM( cubeUVRenderTarget );
  17134. this._cleanup( cubeUVRenderTarget );
  17135. return cubeUVRenderTarget;
  17136. }
  17137. /**
  17138. * Generates a PMREM from a supplied Scene, which can be faster than using an
  17139. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  17140. * in radians to be applied to the scene before PMREM generation. Optional near
  17141. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  17142. * is placed at the origin).
  17143. *
  17144. * @param {Scene} scene - The scene to be captured.
  17145. * @param {number} [sigma=0] - The blur radius in radians.
  17146. * @param {number} [near=0.1] - The near plane distance.
  17147. * @param {number} [far=100] - The far plane distance.
  17148. * @param {Object} [options={}] - The configuration options.
  17149. * @param {number} [options.size=256] - The texture size of the PMREM.
  17150. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17151. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17152. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17153. * @see {@link PMREMGenerator#fromScene}
  17154. */
  17155. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17156. if ( this._hasInitialized === false ) await this._renderer.init();
  17157. return this.fromScene( scene, sigma, near, far, options );
  17158. }
  17159. /**
  17160. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17161. * or HDR. The ideal input image size is 1k (1024 x 512),
  17162. * as this matches best with the 256 x 256 cubemap output.
  17163. *
  17164. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17165. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17166. * @return {RenderTarget} The resulting PMREM.
  17167. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17168. */
  17169. fromEquirectangular( equirectangular, renderTarget = null ) {
  17170. if ( this._hasInitialized === false ) {
  17171. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  17172. this._setSizeFromTexture( equirectangular );
  17173. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17174. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17175. return cubeUVRenderTarget;
  17176. }
  17177. return this._fromTexture( equirectangular, renderTarget );
  17178. }
  17179. /**
  17180. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17181. * or HDR. The ideal input image size is 1k (1024 x 512),
  17182. * as this matches best with the 256 x 256 cubemap output.
  17183. *
  17184. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17185. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17186. * @return {Promise<RenderTarget>} The resulting PMREM.
  17187. * @see {@link PMREMGenerator#fromEquirectangular}
  17188. */
  17189. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17190. if ( this._hasInitialized === false ) await this._renderer.init();
  17191. return this._fromTexture( equirectangular, renderTarget );
  17192. }
  17193. /**
  17194. * Generates a PMREM from an cubemap texture, which can be either LDR
  17195. * or HDR. The ideal input cube size is 256 x 256,
  17196. * as this matches best with the 256 x 256 cubemap output.
  17197. *
  17198. * @param {Texture} cubemap - The cubemap texture to be converted.
  17199. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17200. * @return {RenderTarget} The resulting PMREM.
  17201. * @see {@link PMREMGenerator#fromCubemapAsync}
  17202. */
  17203. fromCubemap( cubemap, renderTarget = null ) {
  17204. if ( this._hasInitialized === false ) {
  17205. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17206. this._setSizeFromTexture( cubemap );
  17207. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17208. this.fromCubemapAsync( cubemap, renderTarget );
  17209. return cubeUVRenderTarget;
  17210. }
  17211. return this._fromTexture( cubemap, renderTarget );
  17212. }
  17213. /**
  17214. * Generates a PMREM from an cubemap texture, which can be either LDR
  17215. * or HDR. The ideal input cube size is 256 x 256,
  17216. * with the 256 x 256 cubemap output.
  17217. *
  17218. * @param {Texture} cubemap - The cubemap texture to be converted.
  17219. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17220. * @return {Promise<RenderTarget>} The resulting PMREM.
  17221. * @see {@link PMREMGenerator#fromCubemap}
  17222. */
  17223. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17224. if ( this._hasInitialized === false ) await this._renderer.init();
  17225. return this._fromTexture( cubemap, renderTarget );
  17226. }
  17227. /**
  17228. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17229. * your texture's network fetch for increased concurrency.
  17230. *
  17231. * @returns {Promise}
  17232. */
  17233. async compileCubemapShader() {
  17234. if ( this._cubemapMaterial === null ) {
  17235. this._cubemapMaterial = _getCubemapMaterial();
  17236. await this._compileMaterial( this._cubemapMaterial );
  17237. }
  17238. }
  17239. /**
  17240. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17241. * your texture's network fetch for increased concurrency.
  17242. *
  17243. * @returns {Promise}
  17244. */
  17245. async compileEquirectangularShader() {
  17246. if ( this._equirectMaterial === null ) {
  17247. this._equirectMaterial = _getEquirectMaterial();
  17248. await this._compileMaterial( this._equirectMaterial );
  17249. }
  17250. }
  17251. /**
  17252. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17253. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17254. * one of them will cause any others to also become unusable.
  17255. */
  17256. dispose() {
  17257. this._dispose();
  17258. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17259. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17260. if ( this._backgroundBox !== null ) {
  17261. this._backgroundBox.geometry.dispose();
  17262. this._backgroundBox.material.dispose();
  17263. }
  17264. }
  17265. // private interface
  17266. _setSizeFromTexture( texture ) {
  17267. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17268. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17269. } else { // Equirectangular
  17270. this._setSize( texture.image.width / 4 );
  17271. }
  17272. }
  17273. _setSize( cubeSize ) {
  17274. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17275. this._cubeSize = Math.pow( 2, this._lodMax );
  17276. }
  17277. _dispose() {
  17278. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17279. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17280. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  17281. this._lodPlanes[ i ].dispose();
  17282. }
  17283. }
  17284. _cleanup( outputTarget ) {
  17285. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17286. outputTarget.scissorTest = false;
  17287. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17288. }
  17289. _fromTexture( texture, renderTarget ) {
  17290. this._setSizeFromTexture( texture );
  17291. _oldTarget = this._renderer.getRenderTarget();
  17292. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17293. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17294. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17295. this._init( cubeUVRenderTarget );
  17296. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17297. this._applyPMREM( cubeUVRenderTarget );
  17298. this._cleanup( cubeUVRenderTarget );
  17299. return cubeUVRenderTarget;
  17300. }
  17301. _allocateTarget() {
  17302. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17303. const height = 4 * this._cubeSize;
  17304. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17305. return cubeUVRenderTarget;
  17306. }
  17307. _init( renderTarget ) {
  17308. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17309. if ( this._pingPongRenderTarget !== null ) {
  17310. this._dispose();
  17311. }
  17312. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17313. const { _lodMax } = this;
  17314. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  17315. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17316. }
  17317. }
  17318. async _compileMaterial( material ) {
  17319. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  17320. await this._renderer.compile( tmpMesh, _flatCamera );
  17321. }
  17322. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17323. const cubeCamera = _cubeCamera;
  17324. cubeCamera.near = near;
  17325. cubeCamera.far = far;
  17326. // px, py, pz, nx, ny, nz
  17327. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17328. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17329. const renderer = this._renderer;
  17330. const originalAutoClear = renderer.autoClear;
  17331. renderer.getClearColor( _clearColor$2 );
  17332. renderer.autoClear = false;
  17333. let backgroundBox = this._backgroundBox;
  17334. if ( backgroundBox === null ) {
  17335. const backgroundMaterial = new MeshBasicMaterial( {
  17336. name: 'PMREM.Background',
  17337. side: BackSide,
  17338. depthWrite: false,
  17339. depthTest: false
  17340. } );
  17341. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  17342. }
  17343. let useSolidColor = false;
  17344. const background = scene.background;
  17345. if ( background ) {
  17346. if ( background.isColor ) {
  17347. backgroundBox.material.color.copy( background );
  17348. scene.background = null;
  17349. useSolidColor = true;
  17350. }
  17351. } else {
  17352. backgroundBox.material.color.copy( _clearColor$2 );
  17353. useSolidColor = true;
  17354. }
  17355. renderer.setRenderTarget( cubeUVRenderTarget );
  17356. renderer.clear();
  17357. if ( useSolidColor ) {
  17358. renderer.render( backgroundBox, cubeCamera );
  17359. }
  17360. for ( let i = 0; i < 6; i ++ ) {
  17361. const col = i % 3;
  17362. if ( col === 0 ) {
  17363. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17364. cubeCamera.position.set( position.x, position.y, position.z );
  17365. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17366. } else if ( col === 1 ) {
  17367. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17368. cubeCamera.position.set( position.x, position.y, position.z );
  17369. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17370. } else {
  17371. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17372. cubeCamera.position.set( position.x, position.y, position.z );
  17373. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17374. }
  17375. const size = this._cubeSize;
  17376. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17377. renderer.render( scene, cubeCamera );
  17378. }
  17379. renderer.autoClear = originalAutoClear;
  17380. scene.background = background;
  17381. }
  17382. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17383. const renderer = this._renderer;
  17384. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17385. if ( isCubeTexture ) {
  17386. if ( this._cubemapMaterial === null ) {
  17387. this._cubemapMaterial = _getCubemapMaterial( texture );
  17388. }
  17389. } else {
  17390. if ( this._equirectMaterial === null ) {
  17391. this._equirectMaterial = _getEquirectMaterial( texture );
  17392. }
  17393. }
  17394. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17395. material.fragmentNode.value = texture;
  17396. const mesh = this._lodMeshes[ 0 ];
  17397. mesh.material = material;
  17398. const size = this._cubeSize;
  17399. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17400. renderer.setRenderTarget( cubeUVRenderTarget );
  17401. renderer.render( mesh, _flatCamera );
  17402. }
  17403. _applyPMREM( cubeUVRenderTarget ) {
  17404. const renderer = this._renderer;
  17405. const autoClear = renderer.autoClear;
  17406. renderer.autoClear = false;
  17407. const n = this._lodPlanes.length;
  17408. for ( let i = 1; i < n; i ++ ) {
  17409. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  17410. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  17411. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  17412. }
  17413. renderer.autoClear = autoClear;
  17414. }
  17415. /**
  17416. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17417. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17418. * the blur latitudinally (around the poles), and then longitudinally (towards
  17419. * the poles) to approximate the orthogonally-separable blur. It is least
  17420. * accurate at the poles, but still does a decent job.
  17421. *
  17422. * @private
  17423. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17424. * @param {number} lodIn - The input level-of-detail.
  17425. * @param {number} lodOut - The output level-of-detail.
  17426. * @param {number} sigma - The blur radius in radians.
  17427. * @param {Vector3} [poleAxis] - The pole axis.
  17428. */
  17429. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17430. const pingPongRenderTarget = this._pingPongRenderTarget;
  17431. this._halfBlur(
  17432. cubeUVRenderTarget,
  17433. pingPongRenderTarget,
  17434. lodIn,
  17435. lodOut,
  17436. sigma,
  17437. 'latitudinal',
  17438. poleAxis );
  17439. this._halfBlur(
  17440. pingPongRenderTarget,
  17441. cubeUVRenderTarget,
  17442. lodOut,
  17443. lodOut,
  17444. sigma,
  17445. 'longitudinal',
  17446. poleAxis );
  17447. }
  17448. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17449. const renderer = this._renderer;
  17450. const blurMaterial = this._blurMaterial;
  17451. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17452. error( 'blur direction must be either latitudinal or longitudinal!' );
  17453. }
  17454. // Number of standard deviations at which to cut off the discrete approximation.
  17455. const STANDARD_DEVIATIONS = 3;
  17456. const blurMesh = this._lodMeshes[ lodOut ];
  17457. blurMesh.material = blurMaterial;
  17458. const blurUniforms = _uniformsMap.get( blurMaterial );
  17459. const pixels = this._sizeLods[ lodIn ] - 1;
  17460. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17461. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17462. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17463. if ( samples > MAX_SAMPLES ) {
  17464. warn( `sigmaRadians, ${
  17465. sigmaRadians}, is too large and will clip, as it requested ${
  17466. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17467. }
  17468. const weights = [];
  17469. let sum = 0;
  17470. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17471. const x = i / sigmaPixels;
  17472. const weight = Math.exp( - x * x / 2 );
  17473. weights.push( weight );
  17474. if ( i === 0 ) {
  17475. sum += weight;
  17476. } else if ( i < samples ) {
  17477. sum += 2 * weight;
  17478. }
  17479. }
  17480. for ( let i = 0; i < weights.length; i ++ ) {
  17481. weights[ i ] = weights[ i ] / sum;
  17482. }
  17483. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17484. blurUniforms.envMap.value = targetIn.texture;
  17485. blurUniforms.samples.value = samples;
  17486. blurUniforms.weights.array = weights;
  17487. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17488. if ( poleAxis ) {
  17489. blurUniforms.poleAxis.value = poleAxis;
  17490. }
  17491. const { _lodMax } = this;
  17492. blurUniforms.dTheta.value = radiansPerPixel;
  17493. blurUniforms.mipInt.value = _lodMax - lodIn;
  17494. const outputSize = this._sizeLods[ lodOut ];
  17495. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17496. const y = 4 * ( this._cubeSize - outputSize );
  17497. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17498. renderer.setRenderTarget( targetOut );
  17499. renderer.render( blurMesh, _flatCamera );
  17500. }
  17501. }
  17502. function _createPlanes( lodMax ) {
  17503. const lodPlanes = [];
  17504. const sizeLods = [];
  17505. const sigmas = [];
  17506. const lodMeshes = [];
  17507. let lod = lodMax;
  17508. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17509. for ( let i = 0; i < totalLods; i ++ ) {
  17510. const sizeLod = Math.pow( 2, lod );
  17511. sizeLods.push( sizeLod );
  17512. let sigma = 1.0 / sizeLod;
  17513. if ( i > lodMax - LOD_MIN ) {
  17514. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17515. } else if ( i === 0 ) {
  17516. sigma = 0;
  17517. }
  17518. sigmas.push( sigma );
  17519. const texelSize = 1.0 / ( sizeLod - 2 );
  17520. const min = - texelSize;
  17521. const max = 1 + texelSize;
  17522. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17523. const cubeFaces = 6;
  17524. const vertices = 6;
  17525. const positionSize = 3;
  17526. const uvSize = 2;
  17527. const faceIndexSize = 1;
  17528. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17529. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17530. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17531. for ( let face = 0; face < cubeFaces; face ++ ) {
  17532. const x = ( face % 3 ) * 2 / 3 - 1;
  17533. const y = face > 2 ? 0 : -1;
  17534. const coordinates = [
  17535. x, y, 0,
  17536. x + 2 / 3, y, 0,
  17537. x + 2 / 3, y + 1, 0,
  17538. x, y, 0,
  17539. x + 2 / 3, y + 1, 0,
  17540. x, y + 1, 0
  17541. ];
  17542. const faceIdx = _faceLib[ face ];
  17543. position.set( coordinates, positionSize * vertices * faceIdx );
  17544. uv.set( uv1, uvSize * vertices * faceIdx );
  17545. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17546. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17547. }
  17548. const planes = new BufferGeometry();
  17549. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17550. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17551. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17552. lodPlanes.push( planes );
  17553. lodMeshes.push( new Mesh( planes, null ) );
  17554. if ( lod > LOD_MIN ) {
  17555. lod --;
  17556. }
  17557. }
  17558. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17559. }
  17560. function _createRenderTarget( width, height ) {
  17561. const params = {
  17562. magFilter: LinearFilter,
  17563. minFilter: LinearFilter,
  17564. generateMipmaps: false,
  17565. type: HalfFloatType,
  17566. format: RGBAFormat,
  17567. colorSpace: LinearSRGBColorSpace,
  17568. //depthBuffer: false
  17569. };
  17570. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17571. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17572. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17573. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17574. cubeUVRenderTarget.scissorTest = true;
  17575. return cubeUVRenderTarget;
  17576. }
  17577. function _setViewport( target, x, y, width, height ) {
  17578. target.viewport.set( x, y, width, height );
  17579. target.scissor.set( x, y, width, height );
  17580. }
  17581. function _getMaterial( type ) {
  17582. const material = new NodeMaterial();
  17583. material.depthTest = false;
  17584. material.depthWrite = false;
  17585. material.blending = NoBlending;
  17586. material.name = `PMREM_${ type }`;
  17587. return material;
  17588. }
  17589. function _getBlurShader( lodMax, width, height ) {
  17590. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17591. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17592. const dTheta = uniform( 0 );
  17593. const n = float( MAX_SAMPLES );
  17594. const latitudinal = uniform( 0 ); // false, bool
  17595. const samples = uniform( 1 ); // int
  17596. const envMap = texture( null );
  17597. const mipInt = uniform( 0 ); // int
  17598. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17599. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17600. const CUBEUV_MAX_MIP = float( lodMax );
  17601. const materialUniforms = {
  17602. n,
  17603. latitudinal,
  17604. weights,
  17605. poleAxis,
  17606. outputDirection: _outputDirection,
  17607. dTheta,
  17608. samples,
  17609. envMap,
  17610. mipInt,
  17611. CUBEUV_TEXEL_WIDTH,
  17612. CUBEUV_TEXEL_HEIGHT,
  17613. CUBEUV_MAX_MIP
  17614. };
  17615. const material = _getMaterial( 'blur' );
  17616. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17617. _uniformsMap.set( material, materialUniforms );
  17618. return material;
  17619. }
  17620. function _getCubemapMaterial( envTexture ) {
  17621. const material = _getMaterial( 'cubemap' );
  17622. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17623. return material;
  17624. }
  17625. function _getEquirectMaterial( envTexture ) {
  17626. const material = _getMaterial( 'equirect' );
  17627. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17628. return material;
  17629. }
  17630. const _cache = new WeakMap();
  17631. /**
  17632. * Generates the cubeUV size based on the given image height.
  17633. *
  17634. * @private
  17635. * @param {number} imageHeight - The image height.
  17636. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17637. */
  17638. function _generateCubeUVSize( imageHeight ) {
  17639. const maxMip = Math.log2( imageHeight ) - 2;
  17640. const texelHeight = 1.0 / imageHeight;
  17641. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17642. return { texelWidth, texelHeight, maxMip };
  17643. }
  17644. /**
  17645. * Generates a PMREM from the given texture.
  17646. *
  17647. * @private
  17648. * @param {Texture} texture - The texture to create the PMREM for.
  17649. * @param {Renderer} renderer - The renderer.
  17650. * @param {PMREMGenerator} generator - The PMREM generator.
  17651. * @return {?Texture} The PMREM.
  17652. */
  17653. function _getPMREMFromTexture( texture, renderer, generator ) {
  17654. const cache = _getCache( renderer );
  17655. let cacheTexture = cache.get( texture );
  17656. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17657. if ( pmremVersion !== texture.pmremVersion ) {
  17658. const image = texture.image;
  17659. if ( texture.isCubeTexture ) {
  17660. if ( isCubeMapReady( image ) ) {
  17661. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17662. } else {
  17663. return null;
  17664. }
  17665. } else {
  17666. if ( isEquirectangularMapReady( image ) ) {
  17667. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17668. } else {
  17669. return null;
  17670. }
  17671. }
  17672. cacheTexture.pmremVersion = texture.pmremVersion;
  17673. cache.set( texture, cacheTexture );
  17674. }
  17675. return cacheTexture.texture;
  17676. }
  17677. /**
  17678. * Returns a cache that stores generated PMREMs for the respective textures.
  17679. * A cache must be maintained per renderer since PMREMs are render target textures
  17680. * which can't be shared across render contexts.
  17681. *
  17682. * @private
  17683. * @param {Renderer} renderer - The renderer.
  17684. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17685. */
  17686. function _getCache( renderer ) {
  17687. let rendererCache = _cache.get( renderer );
  17688. if ( rendererCache === undefined ) {
  17689. rendererCache = new WeakMap();
  17690. _cache.set( renderer, rendererCache );
  17691. }
  17692. return rendererCache;
  17693. }
  17694. /**
  17695. * This node represents a PMREM which is a special type of preprocessed
  17696. * environment map intended for PBR materials.
  17697. *
  17698. * ```js
  17699. * const material = new MeshStandardNodeMaterial();
  17700. * material.envNode = pmremTexture( envMap );
  17701. * ```
  17702. *
  17703. * @augments TempNode
  17704. */
  17705. class PMREMNode extends TempNode {
  17706. static get type() {
  17707. return 'PMREMNode';
  17708. }
  17709. /**
  17710. * Constructs a new function overloading node.
  17711. *
  17712. * @param {Texture} value - The input texture.
  17713. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17714. * @param {Node<float>} [levelNode=null] - The level node.
  17715. */
  17716. constructor( value, uvNode = null, levelNode = null ) {
  17717. super( 'vec3' );
  17718. /**
  17719. * Reference to the input texture.
  17720. *
  17721. * @private
  17722. * @type {Texture}
  17723. */
  17724. this._value = value;
  17725. /**
  17726. * Reference to the generated PMREM.
  17727. *
  17728. * @private
  17729. * @type {Texture | null}
  17730. * @default null
  17731. */
  17732. this._pmrem = null;
  17733. /**
  17734. * The uv node.
  17735. *
  17736. * @type {Node<vec2>}
  17737. */
  17738. this.uvNode = uvNode;
  17739. /**
  17740. * The level node.
  17741. *
  17742. * @type {Node<float>}
  17743. */
  17744. this.levelNode = levelNode;
  17745. /**
  17746. * Reference to a PMREM generator.
  17747. *
  17748. * @private
  17749. * @type {?PMREMGenerator}
  17750. * @default null
  17751. */
  17752. this._generator = null;
  17753. const defaultTexture = new Texture();
  17754. defaultTexture.isRenderTargetTexture = true;
  17755. /**
  17756. * The texture node holding the generated PMREM.
  17757. *
  17758. * @private
  17759. * @type {TextureNode}
  17760. */
  17761. this._texture = texture( defaultTexture );
  17762. /**
  17763. * A uniform representing the PMREM's width.
  17764. *
  17765. * @private
  17766. * @type {UniformNode<float>}
  17767. */
  17768. this._width = uniform( 0 );
  17769. /**
  17770. * A uniform representing the PMREM's height.
  17771. *
  17772. * @private
  17773. * @type {UniformNode<float>}
  17774. */
  17775. this._height = uniform( 0 );
  17776. /**
  17777. * A uniform representing the PMREM's max Mip.
  17778. *
  17779. * @private
  17780. * @type {UniformNode<float>}
  17781. */
  17782. this._maxMip = uniform( 0 );
  17783. /**
  17784. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17785. *
  17786. * @type {string}
  17787. * @default 'render'
  17788. */
  17789. this.updateBeforeType = NodeUpdateType.RENDER;
  17790. }
  17791. set value( value ) {
  17792. this._value = value;
  17793. this._pmrem = null;
  17794. }
  17795. /**
  17796. * The node's texture value.
  17797. *
  17798. * @type {Texture}
  17799. */
  17800. get value() {
  17801. return this._value;
  17802. }
  17803. /**
  17804. * Uses the given PMREM texture to update internal values.
  17805. *
  17806. * @param {Texture} texture - The PMREM texture.
  17807. */
  17808. updateFromTexture( texture ) {
  17809. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17810. this._texture.value = texture;
  17811. this._width.value = cubeUVSize.texelWidth;
  17812. this._height.value = cubeUVSize.texelHeight;
  17813. this._maxMip.value = cubeUVSize.maxMip;
  17814. }
  17815. updateBefore( frame ) {
  17816. let pmrem = this._pmrem;
  17817. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17818. const texture = this._value;
  17819. if ( pmremVersion !== texture.pmremVersion ) {
  17820. if ( texture.isPMREMTexture === true ) {
  17821. pmrem = texture;
  17822. } else {
  17823. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17824. }
  17825. if ( pmrem !== null ) {
  17826. this._pmrem = pmrem;
  17827. this.updateFromTexture( pmrem );
  17828. }
  17829. }
  17830. }
  17831. setup( builder ) {
  17832. if ( this._generator === null ) {
  17833. this._generator = new PMREMGenerator( builder.renderer );
  17834. }
  17835. this.updateBefore( builder );
  17836. //
  17837. let uvNode = this.uvNode;
  17838. if ( uvNode === null && builder.context.getUV ) {
  17839. uvNode = builder.context.getUV( this );
  17840. }
  17841. //
  17842. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  17843. //
  17844. let levelNode = this.levelNode;
  17845. if ( levelNode === null && builder.context.getTextureLevel ) {
  17846. levelNode = builder.context.getTextureLevel( this );
  17847. }
  17848. //
  17849. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  17850. }
  17851. dispose() {
  17852. super.dispose();
  17853. if ( this._generator !== null ) this._generator.dispose();
  17854. }
  17855. }
  17856. /**
  17857. * Returns `true` if the given cube map image has been fully loaded.
  17858. *
  17859. * @private
  17860. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  17861. * @return {boolean} Whether the given cube map is ready or not.
  17862. */
  17863. function isCubeMapReady( image ) {
  17864. if ( image === null || image === undefined ) return false;
  17865. let count = 0;
  17866. const length = 6;
  17867. for ( let i = 0; i < length; i ++ ) {
  17868. if ( image[ i ] !== undefined ) count ++;
  17869. }
  17870. return count === length;
  17871. }
  17872. /**
  17873. * Returns `true` if the given equirectangular image has been fully loaded.
  17874. *
  17875. * @private
  17876. * @param {(Image|Object)} image - The equirectangular image.
  17877. * @return {boolean} Whether the given cube map is ready or not.
  17878. */
  17879. function isEquirectangularMapReady( image ) {
  17880. if ( image === null || image === undefined ) return false;
  17881. return image.height > 0;
  17882. }
  17883. /**
  17884. * TSL function for creating a PMREM node.
  17885. *
  17886. * @tsl
  17887. * @function
  17888. * @param {Texture} value - The input texture.
  17889. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  17890. * @param {?Node<float>} [levelNode=null] - The level node.
  17891. * @returns {PMREMNode}
  17892. */
  17893. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  17894. const _envNodeCache = new WeakMap();
  17895. /**
  17896. * Represents a physical model for Image-based lighting (IBL). The environment
  17897. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  17898. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  17899. *
  17900. * @augments LightingNode
  17901. */
  17902. class EnvironmentNode extends LightingNode {
  17903. static get type() {
  17904. return 'EnvironmentNode';
  17905. }
  17906. /**
  17907. * Constructs a new environment node.
  17908. *
  17909. * @param {Node} [envNode=null] - A node representing the environment.
  17910. */
  17911. constructor( envNode = null ) {
  17912. super();
  17913. /**
  17914. * A node representing the environment.
  17915. *
  17916. * @type {?Node}
  17917. * @default null
  17918. */
  17919. this.envNode = envNode;
  17920. }
  17921. setup( builder ) {
  17922. const { material } = builder;
  17923. let envNode = this.envNode;
  17924. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  17925. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  17926. let cacheEnvNode = _envNodeCache.get( value );
  17927. if ( cacheEnvNode === undefined ) {
  17928. cacheEnvNode = pmremTexture( value );
  17929. _envNodeCache.set( value, cacheEnvNode );
  17930. }
  17931. envNode = cacheEnvNode;
  17932. }
  17933. //
  17934. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  17935. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  17936. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  17937. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  17938. const isolateRadiance = isolate( radiance );
  17939. const isolateIrradiance = isolate( irradiance );
  17940. //
  17941. builder.context.radiance.addAssign( isolateRadiance );
  17942. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  17943. //
  17944. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  17945. if ( clearcoatRadiance ) {
  17946. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  17947. const isolateClearcoatRadiance = isolate( clearcoatRadianceContext );
  17948. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  17949. }
  17950. }
  17951. }
  17952. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  17953. let reflectVec = null;
  17954. return {
  17955. getUV: () => {
  17956. if ( reflectVec === null ) {
  17957. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  17958. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  17959. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  17960. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  17961. }
  17962. return reflectVec;
  17963. },
  17964. getTextureLevel: () => {
  17965. return roughnessNode;
  17966. }
  17967. };
  17968. };
  17969. const createIrradianceContext = ( normalWorldNode ) => {
  17970. return {
  17971. getUV: () => {
  17972. return normalWorldNode;
  17973. },
  17974. getTextureLevel: () => {
  17975. return float( 1.0 );
  17976. }
  17977. };
  17978. };
  17979. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  17980. /**
  17981. * Node material version of {@link MeshStandardMaterial}.
  17982. *
  17983. * @augments NodeMaterial
  17984. */
  17985. class MeshStandardNodeMaterial extends NodeMaterial {
  17986. static get type() {
  17987. return 'MeshStandardNodeMaterial';
  17988. }
  17989. /**
  17990. * Constructs a new mesh standard node material.
  17991. *
  17992. * @param {Object} [parameters] - The configuration parameter.
  17993. */
  17994. constructor( parameters ) {
  17995. super();
  17996. /**
  17997. * This flag can be used for type testing.
  17998. *
  17999. * @type {boolean}
  18000. * @readonly
  18001. * @default true
  18002. */
  18003. this.isMeshStandardNodeMaterial = true;
  18004. /**
  18005. * Set to `true` because standard materials react on lights.
  18006. *
  18007. * @type {boolean}
  18008. * @default true
  18009. */
  18010. this.lights = true;
  18011. /**
  18012. * The emissive color of standard materials is by default inferred from the `emissive`,
  18013. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  18014. * overwrite the default and define the emissive color with a node instead.
  18015. *
  18016. * If you don't want to overwrite the emissive color but modify the existing
  18017. * value instead, use {@link materialEmissive}.
  18018. *
  18019. * @type {?Node<vec3>}
  18020. * @default null
  18021. */
  18022. this.emissiveNode = null;
  18023. /**
  18024. * The metalness of standard materials is by default inferred from the `metalness`,
  18025. * and `metalnessMap` properties. This node property allows to
  18026. * overwrite the default and define the metalness with a node instead.
  18027. *
  18028. * If you don't want to overwrite the metalness but modify the existing
  18029. * value instead, use {@link materialMetalness}.
  18030. *
  18031. * @type {?Node<float>}
  18032. * @default null
  18033. */
  18034. this.metalnessNode = null;
  18035. /**
  18036. * The roughness of standard materials is by default inferred from the `roughness`,
  18037. * and `roughnessMap` properties. This node property allows to
  18038. * overwrite the default and define the roughness with a node instead.
  18039. *
  18040. * If you don't want to overwrite the roughness but modify the existing
  18041. * value instead, use {@link materialRoughness}.
  18042. *
  18043. * @type {?Node<float>}
  18044. * @default null
  18045. */
  18046. this.roughnessNode = null;
  18047. this.setDefaultValues( _defaultValues$6 );
  18048. this.setValues( parameters );
  18049. }
  18050. /**
  18051. * Overwritten since this type of material uses {@link EnvironmentNode}
  18052. * to implement the PBR (PMREM based) environment mapping. Besides, the
  18053. * method honors `Scene.environment`.
  18054. *
  18055. * @param {NodeBuilder} builder - The current node builder.
  18056. * @return {?EnvironmentNode<vec3>} The environment node.
  18057. */
  18058. setupEnvironment( builder ) {
  18059. let envNode = super.setupEnvironment( builder );
  18060. if ( envNode === null && builder.environmentNode ) {
  18061. envNode = builder.environmentNode;
  18062. }
  18063. return envNode ? new EnvironmentNode( envNode ) : null;
  18064. }
  18065. /**
  18066. * Setups the lighting model.
  18067. *
  18068. * @return {PhysicalLightingModel} The lighting model.
  18069. */
  18070. setupLightingModel( /*builder*/ ) {
  18071. return new PhysicalLightingModel();
  18072. }
  18073. /**
  18074. * Setups the specular related node variables.
  18075. */
  18076. setupSpecular() {
  18077. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  18078. specularColor.assign( specularColorNode );
  18079. specularF90.assign( 1.0 );
  18080. }
  18081. /**
  18082. * Setups the standard specific node variables.
  18083. *
  18084. * @param {NodeBuilder} builder - The current node builder.
  18085. */
  18086. setupVariants() {
  18087. // METALNESS
  18088. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  18089. metalness.assign( metalnessNode );
  18090. // ROUGHNESS
  18091. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  18092. roughnessNode = getRoughness( { roughness: roughnessNode } );
  18093. roughness.assign( roughnessNode );
  18094. // SPECULAR COLOR
  18095. this.setupSpecular();
  18096. // DIFFUSE COLOR
  18097. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  18098. }
  18099. copy( source ) {
  18100. this.emissiveNode = source.emissiveNode;
  18101. this.metalnessNode = source.metalnessNode;
  18102. this.roughnessNode = source.roughnessNode;
  18103. return super.copy( source );
  18104. }
  18105. }
  18106. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  18107. /**
  18108. * Node material version of {@link MeshPhysicalMaterial}.
  18109. *
  18110. * @augments MeshStandardNodeMaterial
  18111. */
  18112. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  18113. static get type() {
  18114. return 'MeshPhysicalNodeMaterial';
  18115. }
  18116. /**
  18117. * Constructs a new mesh physical node material.
  18118. *
  18119. * @param {Object} [parameters] - The configuration parameter.
  18120. */
  18121. constructor( parameters ) {
  18122. super();
  18123. /**
  18124. * This flag can be used for type testing.
  18125. *
  18126. * @type {boolean}
  18127. * @readonly
  18128. * @default true
  18129. */
  18130. this.isMeshPhysicalNodeMaterial = true;
  18131. /**
  18132. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  18133. * and `clearcoatMap` properties. This node property allows to overwrite the default
  18134. * and define the clearcoat with a node instead.
  18135. *
  18136. * If you don't want to overwrite the clearcoat but modify the existing
  18137. * value instead, use {@link materialClearcoat}.
  18138. *
  18139. * @type {?Node<float>}
  18140. * @default null
  18141. */
  18142. this.clearcoatNode = null;
  18143. /**
  18144. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  18145. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  18146. * and define the clearcoat roughness with a node instead.
  18147. *
  18148. * If you don't want to overwrite the clearcoat roughness but modify the existing
  18149. * value instead, use {@link materialClearcoatRoughness}.
  18150. *
  18151. * @type {?Node<float>}
  18152. * @default null
  18153. */
  18154. this.clearcoatRoughnessNode = null;
  18155. /**
  18156. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18157. * property. This node property allows to overwrite the default
  18158. * and define the clearcoat normal with a node instead.
  18159. *
  18160. * If you don't want to overwrite the clearcoat normal but modify the existing
  18161. * value instead, use {@link materialClearcoatNormal}.
  18162. *
  18163. * @type {?Node<vec3>}
  18164. * @default null
  18165. */
  18166. this.clearcoatNormalNode = null;
  18167. /**
  18168. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18169. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18170. * and define the sheen with a node instead.
  18171. *
  18172. * If you don't want to overwrite the sheen but modify the existing
  18173. * value instead, use {@link materialSheen}.
  18174. *
  18175. * @type {?Node<vec3>}
  18176. * @default null
  18177. */
  18178. this.sheenNode = null;
  18179. /**
  18180. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18181. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18182. * and define the sheen roughness with a node instead.
  18183. *
  18184. * If you don't want to overwrite the sheen roughness but modify the existing
  18185. * value instead, use {@link materialSheenRoughness}.
  18186. *
  18187. * @type {?Node<float>}
  18188. * @default null
  18189. */
  18190. this.sheenRoughnessNode = null;
  18191. /**
  18192. * The iridescence of physical materials is by default inferred from the `iridescence`
  18193. * property. This node property allows to overwrite the default
  18194. * and define the iridescence with a node instead.
  18195. *
  18196. * If you don't want to overwrite the iridescence but modify the existing
  18197. * value instead, use {@link materialIridescence}.
  18198. *
  18199. * @type {?Node<float>}
  18200. * @default null
  18201. */
  18202. this.iridescenceNode = null;
  18203. /**
  18204. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18205. * property. This node property allows to overwrite the default
  18206. * and define the iridescence IOR with a node instead.
  18207. *
  18208. * If you don't want to overwrite the iridescence IOR but modify the existing
  18209. * value instead, use {@link materialIridescenceIOR}.
  18210. *
  18211. * @type {?Node<float>}
  18212. * @default null
  18213. */
  18214. this.iridescenceIORNode = null;
  18215. /**
  18216. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18217. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18218. * and define the iridescence thickness with a node instead.
  18219. *
  18220. * If you don't want to overwrite the iridescence thickness but modify the existing
  18221. * value instead, use {@link materialIridescenceThickness}.
  18222. *
  18223. * @type {?Node<float>}
  18224. * @default null
  18225. */
  18226. this.iridescenceThicknessNode = null;
  18227. /**
  18228. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18229. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18230. * and define the specular intensity with a node instead.
  18231. *
  18232. * If you don't want to overwrite the specular intensity but modify the existing
  18233. * value instead, use {@link materialSpecularIntensity}.
  18234. *
  18235. * @type {?Node<float>}
  18236. * @default null
  18237. */
  18238. this.specularIntensityNode = null;
  18239. /**
  18240. * The specular color of physical materials is by default inferred from the `specularColor`
  18241. * and `specularColorMap` properties. This node property allows to overwrite the default
  18242. * and define the specular color with a node instead.
  18243. *
  18244. * If you don't want to overwrite the specular color but modify the existing
  18245. * value instead, use {@link materialSpecularColor}.
  18246. *
  18247. * @type {?Node<vec3>}
  18248. * @default null
  18249. */
  18250. this.specularColorNode = null;
  18251. /**
  18252. * The ior of physical materials is by default inferred from the `ior`
  18253. * property. This node property allows to overwrite the default
  18254. * and define the ior with a node instead.
  18255. *
  18256. * If you don't want to overwrite the ior but modify the existing
  18257. * value instead, use {@link materialIOR}.
  18258. *
  18259. * @type {?Node<float>}
  18260. * @default null
  18261. */
  18262. this.iorNode = null;
  18263. /**
  18264. * The transmission of physical materials is by default inferred from the `transmission` and
  18265. * `transmissionMap` properties. This node property allows to overwrite the default
  18266. * and define the transmission with a node instead.
  18267. *
  18268. * If you don't want to overwrite the transmission but modify the existing
  18269. * value instead, use {@link materialTransmission}.
  18270. *
  18271. * @type {?Node<float>}
  18272. * @default null
  18273. */
  18274. this.transmissionNode = null;
  18275. /**
  18276. * The thickness of physical materials is by default inferred from the `thickness` and
  18277. * `thicknessMap` properties. This node property allows to overwrite the default
  18278. * and define the thickness with a node instead.
  18279. *
  18280. * If you don't want to overwrite the thickness but modify the existing
  18281. * value instead, use {@link materialThickness}.
  18282. *
  18283. * @type {?Node<float>}
  18284. * @default null
  18285. */
  18286. this.thicknessNode = null;
  18287. /**
  18288. * The attenuation distance of physical materials is by default inferred from the
  18289. * `attenuationDistance` property. This node property allows to overwrite the default
  18290. * and define the attenuation distance with a node instead.
  18291. *
  18292. * If you don't want to overwrite the attenuation distance but modify the existing
  18293. * value instead, use {@link materialAttenuationDistance}.
  18294. *
  18295. * @type {?Node<float>}
  18296. * @default null
  18297. */
  18298. this.attenuationDistanceNode = null;
  18299. /**
  18300. * The attenuation color of physical materials is by default inferred from the
  18301. * `attenuationColor` property. This node property allows to overwrite the default
  18302. * and define the attenuation color with a node instead.
  18303. *
  18304. * If you don't want to overwrite the attenuation color but modify the existing
  18305. * value instead, use {@link materialAttenuationColor}.
  18306. *
  18307. * @type {?Node<vec3>}
  18308. * @default null
  18309. */
  18310. this.attenuationColorNode = null;
  18311. /**
  18312. * The dispersion of physical materials is by default inferred from the
  18313. * `dispersion` property. This node property allows to overwrite the default
  18314. * and define the dispersion with a node instead.
  18315. *
  18316. * If you don't want to overwrite the dispersion but modify the existing
  18317. * value instead, use {@link materialDispersion}.
  18318. *
  18319. * @type {?Node<float>}
  18320. * @default null
  18321. */
  18322. this.dispersionNode = null;
  18323. /**
  18324. * The anisotropy of physical materials is by default inferred from the
  18325. * `anisotropy` property. This node property allows to overwrite the default
  18326. * and define the anisotropy with a node instead.
  18327. *
  18328. * If you don't want to overwrite the anisotropy but modify the existing
  18329. * value instead, use {@link materialAnisotropy}.
  18330. *
  18331. * @type {?Node<float>}
  18332. * @default null
  18333. */
  18334. this.anisotropyNode = null;
  18335. this.setDefaultValues( _defaultValues$5 );
  18336. this.setValues( parameters );
  18337. }
  18338. /**
  18339. * Whether the lighting model should use clearcoat or not.
  18340. *
  18341. * @type {boolean}
  18342. * @default true
  18343. */
  18344. get useClearcoat() {
  18345. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18346. }
  18347. /**
  18348. * Whether the lighting model should use iridescence or not.
  18349. *
  18350. * @type {boolean}
  18351. * @default true
  18352. */
  18353. get useIridescence() {
  18354. return this.iridescence > 0 || this.iridescenceNode !== null;
  18355. }
  18356. /**
  18357. * Whether the lighting model should use sheen or not.
  18358. *
  18359. * @type {boolean}
  18360. * @default true
  18361. */
  18362. get useSheen() {
  18363. return this.sheen > 0 || this.sheenNode !== null;
  18364. }
  18365. /**
  18366. * Whether the lighting model should use anisotropy or not.
  18367. *
  18368. * @type {boolean}
  18369. * @default true
  18370. */
  18371. get useAnisotropy() {
  18372. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18373. }
  18374. /**
  18375. * Whether the lighting model should use transmission or not.
  18376. *
  18377. * @type {boolean}
  18378. * @default true
  18379. */
  18380. get useTransmission() {
  18381. return this.transmission > 0 || this.transmissionNode !== null;
  18382. }
  18383. /**
  18384. * Whether the lighting model should use dispersion or not.
  18385. *
  18386. * @type {boolean}
  18387. * @default true
  18388. */
  18389. get useDispersion() {
  18390. return this.dispersion > 0 || this.dispersionNode !== null;
  18391. }
  18392. /**
  18393. * Setups the specular related node variables.
  18394. */
  18395. setupSpecular() {
  18396. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18397. ior.assign( iorNode );
  18398. 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 ) );
  18399. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18400. }
  18401. /**
  18402. * Setups the lighting model.
  18403. *
  18404. * @return {PhysicalLightingModel} The lighting model.
  18405. */
  18406. setupLightingModel( /*builder*/ ) {
  18407. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18408. }
  18409. /**
  18410. * Setups the physical specific node variables.
  18411. *
  18412. * @param {NodeBuilder} builder - The current node builder.
  18413. */
  18414. setupVariants( builder ) {
  18415. super.setupVariants( builder );
  18416. // CLEARCOAT
  18417. if ( this.useClearcoat ) {
  18418. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18419. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18420. clearcoat.assign( clearcoatNode );
  18421. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18422. }
  18423. // SHEEN
  18424. if ( this.useSheen ) {
  18425. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18426. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18427. sheen.assign( sheenNode );
  18428. sheenRoughness.assign( sheenRoughnessNode );
  18429. }
  18430. // IRIDESCENCE
  18431. if ( this.useIridescence ) {
  18432. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18433. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18434. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18435. iridescence.assign( iridescenceNode );
  18436. iridescenceIOR.assign( iridescenceIORNode );
  18437. iridescenceThickness.assign( iridescenceThicknessNode );
  18438. }
  18439. // ANISOTROPY
  18440. if ( this.useAnisotropy ) {
  18441. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18442. anisotropy.assign( anisotropyV.length() );
  18443. If( anisotropy.equal( 0.0 ), () => {
  18444. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18445. } ).Else( () => {
  18446. anisotropyV.divAssign( vec2( anisotropy ) );
  18447. anisotropy.assign( anisotropy.saturate() );
  18448. } );
  18449. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18450. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18451. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18452. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18453. }
  18454. // TRANSMISSION
  18455. if ( this.useTransmission ) {
  18456. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  18457. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  18458. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  18459. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  18460. transmission.assign( transmissionNode );
  18461. thickness.assign( thicknessNode );
  18462. attenuationDistance.assign( attenuationDistanceNode );
  18463. attenuationColor.assign( attenuationColorNode );
  18464. if ( this.useDispersion ) {
  18465. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  18466. dispersion.assign( dispersionNode );
  18467. }
  18468. }
  18469. }
  18470. /**
  18471. * Setups the clearcoat normal node.
  18472. *
  18473. * @return {Node<vec3>} The clearcoat normal.
  18474. */
  18475. setupClearcoatNormal() {
  18476. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  18477. }
  18478. setup( builder ) {
  18479. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18480. super.setup( builder );
  18481. }
  18482. copy( source ) {
  18483. this.clearcoatNode = source.clearcoatNode;
  18484. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18485. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18486. this.sheenNode = source.sheenNode;
  18487. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18488. this.iridescenceNode = source.iridescenceNode;
  18489. this.iridescenceIORNode = source.iridescenceIORNode;
  18490. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18491. this.specularIntensityNode = source.specularIntensityNode;
  18492. this.specularColorNode = source.specularColorNode;
  18493. this.transmissionNode = source.transmissionNode;
  18494. this.thicknessNode = source.thicknessNode;
  18495. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18496. this.attenuationColorNode = source.attenuationColorNode;
  18497. this.dispersionNode = source.dispersionNode;
  18498. this.anisotropyNode = source.anisotropyNode;
  18499. return super.copy( source );
  18500. }
  18501. }
  18502. /**
  18503. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18504. *
  18505. * @augments PhysicalLightingModel
  18506. */
  18507. class SSSLightingModel extends PhysicalLightingModel {
  18508. /**
  18509. * Constructs a new physical lighting model.
  18510. *
  18511. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18512. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18513. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18514. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18515. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18516. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18517. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18518. */
  18519. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18520. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18521. /**
  18522. * Whether the lighting model should use SSS or not.
  18523. *
  18524. * @type {boolean}
  18525. * @default false
  18526. */
  18527. this.useSSS = sss;
  18528. }
  18529. /**
  18530. * Extends the default implementation with a SSS term.
  18531. *
  18532. * 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/}
  18533. *
  18534. * @param {Object} input - The input data.
  18535. * @param {NodeBuilder} builder - The current node builder.
  18536. */
  18537. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18538. if ( this.useSSS === true ) {
  18539. const material = builder.material;
  18540. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18541. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18542. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18543. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18544. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18545. }
  18546. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18547. }
  18548. }
  18549. /**
  18550. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18551. * that implements a Subsurface scattering (SSS) term.
  18552. *
  18553. * @augments MeshPhysicalNodeMaterial
  18554. */
  18555. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18556. static get type() {
  18557. return 'MeshSSSNodeMaterial';
  18558. }
  18559. /**
  18560. * Constructs a new mesh SSS node material.
  18561. *
  18562. * @param {Object} [parameters] - The configuration parameter.
  18563. */
  18564. constructor( parameters ) {
  18565. super( parameters );
  18566. /**
  18567. * Represents the thickness color.
  18568. *
  18569. * @type {?Node<vec3>}
  18570. * @default null
  18571. */
  18572. this.thicknessColorNode = null;
  18573. /**
  18574. * Represents the distortion factor.
  18575. *
  18576. * @type {?Node<float>}
  18577. */
  18578. this.thicknessDistortionNode = float( 0.1 );
  18579. /**
  18580. * Represents the thickness ambient factor.
  18581. *
  18582. * @type {?Node<float>}
  18583. */
  18584. this.thicknessAmbientNode = float( 0.0 );
  18585. /**
  18586. * Represents the thickness attenuation.
  18587. *
  18588. * @type {?Node<float>}
  18589. */
  18590. this.thicknessAttenuationNode = float( .1 );
  18591. /**
  18592. * Represents the thickness power.
  18593. *
  18594. * @type {?Node<float>}
  18595. */
  18596. this.thicknessPowerNode = float( 2.0 );
  18597. /**
  18598. * Represents the thickness scale.
  18599. *
  18600. * @type {?Node<float>}
  18601. */
  18602. this.thicknessScaleNode = float( 10.0 );
  18603. }
  18604. /**
  18605. * Whether the lighting model should use SSS or not.
  18606. *
  18607. * @type {boolean}
  18608. * @default true
  18609. */
  18610. get useSSS() {
  18611. return this.thicknessColorNode !== null;
  18612. }
  18613. /**
  18614. * Setups the lighting model.
  18615. *
  18616. * @return {SSSLightingModel} The lighting model.
  18617. */
  18618. setupLightingModel( /*builder*/ ) {
  18619. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18620. }
  18621. copy( source ) {
  18622. this.thicknessColorNode = source.thicknessColorNode;
  18623. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18624. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18625. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18626. this.thicknessPowerNode = source.thicknessPowerNode;
  18627. this.thicknessScaleNode = source.thicknessScaleNode;
  18628. return super.copy( source );
  18629. }
  18630. }
  18631. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18632. // dotNL will be from -1.0 to 1.0
  18633. const dotNL = normal.dot( lightDirection );
  18634. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18635. if ( builder.material.gradientMap ) {
  18636. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18637. return vec3( gradientMap.r );
  18638. } else {
  18639. const fw = coord.fwidth().mul( 0.5 );
  18640. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18641. }
  18642. } );
  18643. /**
  18644. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18645. *
  18646. * @augments LightingModel
  18647. */
  18648. class ToonLightingModel extends LightingModel {
  18649. /**
  18650. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18651. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18652. *
  18653. * @param {Object} lightData - The light data.
  18654. * @param {NodeBuilder} builder - The current node builder.
  18655. */
  18656. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18657. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18658. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18659. }
  18660. /**
  18661. * Implements the indirect lighting.
  18662. *
  18663. * @param {NodeBuilder} builder - The current node builder.
  18664. */
  18665. indirect( builder ) {
  18666. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18667. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18668. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18669. }
  18670. }
  18671. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18672. /**
  18673. * Node material version of {@link MeshToonMaterial}.
  18674. *
  18675. * @augments NodeMaterial
  18676. */
  18677. class MeshToonNodeMaterial extends NodeMaterial {
  18678. static get type() {
  18679. return 'MeshToonNodeMaterial';
  18680. }
  18681. /**
  18682. * Constructs a new mesh toon node material.
  18683. *
  18684. * @param {Object} [parameters] - The configuration parameter.
  18685. */
  18686. constructor( parameters ) {
  18687. super();
  18688. /**
  18689. * This flag can be used for type testing.
  18690. *
  18691. * @type {boolean}
  18692. * @readonly
  18693. * @default true
  18694. */
  18695. this.isMeshToonNodeMaterial = true;
  18696. /**
  18697. * Set to `true` because toon materials react on lights.
  18698. *
  18699. * @type {boolean}
  18700. * @default true
  18701. */
  18702. this.lights = true;
  18703. this.setDefaultValues( _defaultValues$4 );
  18704. this.setValues( parameters );
  18705. }
  18706. /**
  18707. * Setups the lighting model.
  18708. *
  18709. * @return {ToonLightingModel} The lighting model.
  18710. */
  18711. setupLightingModel( /*builder*/ ) {
  18712. return new ToonLightingModel();
  18713. }
  18714. }
  18715. /**
  18716. * TSL function for creating a matcap uv node.
  18717. *
  18718. * Can be used to compute texture coordinates for projecting a
  18719. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18720. *
  18721. * @tsl
  18722. * @function
  18723. * @returns {Node<vec2>} The matcap UV coordinates.
  18724. */
  18725. const matcapUV = /*@__PURE__*/ Fn( () => {
  18726. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18727. const y = positionViewDirection.cross( x );
  18728. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18729. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18730. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18731. /**
  18732. * Node material version of {@link MeshMatcapMaterial}.
  18733. *
  18734. * @augments NodeMaterial
  18735. */
  18736. class MeshMatcapNodeMaterial extends NodeMaterial {
  18737. static get type() {
  18738. return 'MeshMatcapNodeMaterial';
  18739. }
  18740. /**
  18741. * Constructs a new mesh normal node material.
  18742. *
  18743. * @param {Object} [parameters] - The configuration parameter.
  18744. */
  18745. constructor( parameters ) {
  18746. super();
  18747. /**
  18748. * This flag can be used for type testing.
  18749. *
  18750. * @type {boolean}
  18751. * @readonly
  18752. * @default true
  18753. */
  18754. this.isMeshMatcapNodeMaterial = true;
  18755. this.setDefaultValues( _defaultValues$3 );
  18756. this.setValues( parameters );
  18757. }
  18758. /**
  18759. * Setups the matcap specific node variables.
  18760. *
  18761. * @param {NodeBuilder} builder - The current node builder.
  18762. */
  18763. setupVariants( builder ) {
  18764. const uv = matcapUV;
  18765. let matcapColor;
  18766. if ( builder.material.matcap ) {
  18767. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18768. } else {
  18769. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18770. }
  18771. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18772. }
  18773. }
  18774. /**
  18775. * Applies a rotation to the given position node.
  18776. *
  18777. * @augments TempNode
  18778. */
  18779. class RotateNode extends TempNode {
  18780. static get type() {
  18781. return 'RotateNode';
  18782. }
  18783. /**
  18784. * Constructs a new rotate node.
  18785. *
  18786. * @param {Node} positionNode - The position node.
  18787. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18788. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18789. */
  18790. constructor( positionNode, rotationNode ) {
  18791. super();
  18792. /**
  18793. * The position node.
  18794. *
  18795. * @type {Node}
  18796. */
  18797. this.positionNode = positionNode;
  18798. /**
  18799. * Represents the rotation that is applied to the position node.
  18800. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18801. *
  18802. * @type {Node}
  18803. */
  18804. this.rotationNode = rotationNode;
  18805. }
  18806. /**
  18807. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18808. *
  18809. * @param {NodeBuilder} builder - The current node builder.
  18810. * @return {string} The node's type.
  18811. */
  18812. getNodeType( builder ) {
  18813. return this.positionNode.getNodeType( builder );
  18814. }
  18815. setup( builder ) {
  18816. const { rotationNode, positionNode } = this;
  18817. const nodeType = this.getNodeType( builder );
  18818. if ( nodeType === 'vec2' ) {
  18819. const cosAngle = rotationNode.cos();
  18820. const sinAngle = rotationNode.sin();
  18821. const rotationMatrix = mat2(
  18822. cosAngle, sinAngle,
  18823. sinAngle.negate(), cosAngle
  18824. );
  18825. return rotationMatrix.mul( positionNode );
  18826. } else {
  18827. const rotation = rotationNode;
  18828. 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 ) );
  18829. 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 ) );
  18830. 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 ) );
  18831. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  18832. }
  18833. }
  18834. }
  18835. /**
  18836. * TSL function for creating a rotate node.
  18837. *
  18838. * @tsl
  18839. * @function
  18840. * @param {Node} positionNode - The position node.
  18841. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18842. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18843. * @returns {RotateNode}
  18844. */
  18845. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  18846. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  18847. /**
  18848. * Node material version of {@link SpriteMaterial}.
  18849. *
  18850. * @augments NodeMaterial
  18851. */
  18852. class SpriteNodeMaterial extends NodeMaterial {
  18853. static get type() {
  18854. return 'SpriteNodeMaterial';
  18855. }
  18856. /**
  18857. * Constructs a new sprite node material.
  18858. *
  18859. * @param {Object} [parameters] - The configuration parameter.
  18860. */
  18861. constructor( parameters ) {
  18862. super();
  18863. /**
  18864. * This flag can be used for type testing.
  18865. *
  18866. * @type {boolean}
  18867. * @readonly
  18868. * @default true
  18869. */
  18870. this.isSpriteNodeMaterial = true;
  18871. this._useSizeAttenuation = true;
  18872. /**
  18873. * This property makes it possible to define the position of the sprite with a
  18874. * node. That can be useful when the material is used with instanced rendering
  18875. * and node data are defined with an instanced attribute node:
  18876. * ```js
  18877. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  18878. * material.positionNode = instancedBufferAttribute( positionAttribute );
  18879. * ```
  18880. * Another possibility is to compute the instanced data with a compute shader:
  18881. * ```js
  18882. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  18883. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18884. * ```
  18885. *
  18886. * @type {?Node<vec2>}
  18887. * @default null
  18888. */
  18889. this.positionNode = null;
  18890. /**
  18891. * The rotation of sprite materials is by default inferred from the `rotation`,
  18892. * property. This node property allows to overwrite the default and define
  18893. * the rotation with a node instead.
  18894. *
  18895. * If you don't want to overwrite the rotation but modify the existing
  18896. * value instead, use {@link materialRotation}.
  18897. *
  18898. * @type {?Node<float>}
  18899. * @default null
  18900. */
  18901. this.rotationNode = null;
  18902. /**
  18903. * This node property provides an additional way to scale sprites next to
  18904. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  18905. * is multiplied with the scale value of this node in the vertex shader.
  18906. *
  18907. * @type {?Node<vec2>}
  18908. * @default null
  18909. */
  18910. this.scaleNode = null;
  18911. /**
  18912. * In Sprites, the transparent property is enabled by default.
  18913. *
  18914. * @type {boolean}
  18915. * @default true
  18916. */
  18917. this.transparent = true;
  18918. this.setDefaultValues( _defaultValues$2 );
  18919. this.setValues( parameters );
  18920. }
  18921. /**
  18922. * Setups the position node in view space. This method implements
  18923. * the sprite specific vertex shader.
  18924. *
  18925. * @param {NodeBuilder} builder - The current node builder.
  18926. * @return {Node<vec3>} The position in view space.
  18927. */
  18928. setupPositionView( builder ) {
  18929. const { object, camera } = builder;
  18930. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  18931. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  18932. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  18933. if ( scaleNode !== null ) {
  18934. scale = scale.mul( vec2( scaleNode ) );
  18935. }
  18936. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  18937. scale = scale.mul( mvPosition.z.negate() );
  18938. }
  18939. let alignedPosition = positionGeometry.xy;
  18940. if ( object.center && object.center.isVector2 === true ) {
  18941. const center = reference$1( 'center', 'vec2', object );
  18942. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  18943. }
  18944. alignedPosition = alignedPosition.mul( scale );
  18945. const rotation = float( rotationNode || materialRotation );
  18946. const rotatedPosition = rotate( alignedPosition, rotation );
  18947. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  18948. }
  18949. copy( source ) {
  18950. this.positionNode = source.positionNode;
  18951. this.rotationNode = source.rotationNode;
  18952. this.scaleNode = source.scaleNode;
  18953. return super.copy( source );
  18954. }
  18955. /**
  18956. * Whether to use size attenuation or not.
  18957. *
  18958. * @type {boolean}
  18959. * @default true
  18960. */
  18961. get sizeAttenuation() {
  18962. return this._useSizeAttenuation;
  18963. }
  18964. set sizeAttenuation( value ) {
  18965. if ( this._useSizeAttenuation !== value ) {
  18966. this._useSizeAttenuation = value;
  18967. this.needsUpdate = true;
  18968. }
  18969. }
  18970. }
  18971. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  18972. const _size$4 = /*@__PURE__*/ new Vector2();
  18973. /**
  18974. * Node material version of {@link PointsMaterial}.
  18975. *
  18976. * This material can be used in two ways:
  18977. *
  18978. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  18979. * with a pixel size of `1`, it's not possible to define a size.
  18980. *
  18981. * ```js
  18982. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  18983. * ```
  18984. *
  18985. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  18986. * see {@link PointsNodeMaterial#sizeNode}.
  18987. *
  18988. * ```js
  18989. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  18990. * ```
  18991. *
  18992. * @augments SpriteNodeMaterial
  18993. */
  18994. class PointsNodeMaterial extends SpriteNodeMaterial {
  18995. static get type() {
  18996. return 'PointsNodeMaterial';
  18997. }
  18998. /**
  18999. * Constructs a new points node material.
  19000. *
  19001. * @param {Object} [parameters] - The configuration parameter.
  19002. */
  19003. constructor( parameters ) {
  19004. super();
  19005. /**
  19006. * This node property provides an additional way to set the point size.
  19007. *
  19008. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  19009. * this node has no effect when the material is used with {@link Points} and a WebGPU
  19010. * backend. If an application wants to render points with a size larger than 1 pixel,
  19011. * the material should be used with {@link Sprite} and instancing.
  19012. *
  19013. * @type {?Node<vec2>}
  19014. * @default null
  19015. */
  19016. this.sizeNode = null;
  19017. /**
  19018. * This flag can be used for type testing.
  19019. *
  19020. * @type {boolean}
  19021. * @readonly
  19022. * @default true
  19023. */
  19024. this.isPointsNodeMaterial = true;
  19025. this.setDefaultValues( _defaultValues$1 );
  19026. this.setValues( parameters );
  19027. }
  19028. setupPositionView() {
  19029. const { positionNode } = this;
  19030. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  19031. }
  19032. setupVertexSprite( builder ) {
  19033. const { material, camera } = builder;
  19034. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  19035. let mvp = super.setupVertex( builder );
  19036. // skip further processing if the material is not a node material
  19037. if ( material.isNodeMaterial !== true ) {
  19038. return mvp;
  19039. }
  19040. // point size
  19041. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  19042. pointSize = pointSize.mul( screenDPR );
  19043. // size attenuation
  19044. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  19045. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  19046. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  19047. }
  19048. // scale
  19049. if ( scaleNode && scaleNode.isNode ) {
  19050. pointSize = pointSize.mul( vec2( scaleNode ) );
  19051. }
  19052. // compute offset
  19053. let offset = positionGeometry.xy;
  19054. // apply rotation
  19055. if ( rotationNode && rotationNode.isNode ) {
  19056. const rotation = float( rotationNode );
  19057. offset = rotate( offset, rotation );
  19058. }
  19059. // account for point size
  19060. offset = offset.mul( pointSize );
  19061. // scale by viewport size
  19062. offset = offset.div( viewportSize.div( 2 ) );
  19063. // compensate for the perspective divide
  19064. offset = offset.mul( mvp.w );
  19065. // add offset
  19066. mvp = mvp.add( vec4( offset, 0, 0 ) );
  19067. return mvp;
  19068. }
  19069. setupVertex( builder ) {
  19070. if ( builder.object.isPoints ) {
  19071. return super.setupVertex( builder );
  19072. } else {
  19073. return this.setupVertexSprite( builder );
  19074. }
  19075. }
  19076. /**
  19077. * Whether alpha to coverage should be used or not.
  19078. *
  19079. * @type {boolean}
  19080. * @default true
  19081. */
  19082. get alphaToCoverage() {
  19083. return this._useAlphaToCoverage;
  19084. }
  19085. set alphaToCoverage( value ) {
  19086. if ( this._useAlphaToCoverage !== value ) {
  19087. this._useAlphaToCoverage = value;
  19088. this.needsUpdate = true;
  19089. }
  19090. }
  19091. }
  19092. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  19093. const size = renderer.getSize( _size$4 ); // logical units
  19094. this.value = 0.5 * size.y;
  19095. } );
  19096. /**
  19097. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  19098. *
  19099. * @augments LightingModel
  19100. */
  19101. class ShadowMaskModel extends LightingModel {
  19102. /**
  19103. * Constructs a new shadow mask model.
  19104. */
  19105. constructor() {
  19106. super();
  19107. /**
  19108. * The shadow mask node.
  19109. *
  19110. * @type {Node}
  19111. */
  19112. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  19113. }
  19114. /**
  19115. * Only used to save the shadow mask.
  19116. *
  19117. * @param {Object} input - The input data.
  19118. */
  19119. direct( { lightNode } ) {
  19120. if ( lightNode.shadowNode !== null ) {
  19121. this.shadowNode.mulAssign( lightNode.shadowNode );
  19122. }
  19123. }
  19124. /**
  19125. * Uses the shadow mask to produce the final color.
  19126. *
  19127. * @param {NodeBuilder} builder - The current node builder.
  19128. */
  19129. finish( { context } ) {
  19130. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  19131. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  19132. }
  19133. }
  19134. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  19135. /**
  19136. * Node material version of {@link ShadowMaterial}.
  19137. *
  19138. * @augments NodeMaterial
  19139. */
  19140. class ShadowNodeMaterial extends NodeMaterial {
  19141. static get type() {
  19142. return 'ShadowNodeMaterial';
  19143. }
  19144. /**
  19145. * Constructs a new shadow node material.
  19146. *
  19147. * @param {Object} [parameters] - The configuration parameter.
  19148. */
  19149. constructor( parameters ) {
  19150. super();
  19151. /**
  19152. * This flag can be used for type testing.
  19153. *
  19154. * @type {boolean}
  19155. * @readonly
  19156. * @default true
  19157. */
  19158. this.isShadowNodeMaterial = true;
  19159. /**
  19160. * Set to `true` because so it's possible to implement
  19161. * the shadow mask effect.
  19162. *
  19163. * @type {boolean}
  19164. * @default true
  19165. */
  19166. this.lights = true;
  19167. /**
  19168. * Overwritten since shadow materials are transparent
  19169. * by default.
  19170. *
  19171. * @type {boolean}
  19172. * @default true
  19173. */
  19174. this.transparent = true;
  19175. this.setDefaultValues( _defaultValues );
  19176. this.setValues( parameters );
  19177. }
  19178. /**
  19179. * Setups the lighting model.
  19180. *
  19181. * @return {ShadowMaskModel} The lighting model.
  19182. */
  19183. setupLightingModel( /*builder*/ ) {
  19184. return new ShadowMaskModel();
  19185. }
  19186. }
  19187. const scatteringDensity = property( 'vec3' );
  19188. const linearDepthRay = property( 'vec3' );
  19189. const outgoingRayLight = property( 'vec3' );
  19190. /**
  19191. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19192. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19193. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19194. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19195. *
  19196. * @augments LightingModel
  19197. */
  19198. class VolumetricLightingModel extends LightingModel {
  19199. constructor() {
  19200. super();
  19201. }
  19202. start( builder ) {
  19203. const { material, context } = builder;
  19204. const startPos = property( 'vec3' );
  19205. const endPos = property( 'vec3' );
  19206. // This approach dynamically changes the direction of the ray,
  19207. // 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.
  19208. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19209. startPos.assign( cameraPosition );
  19210. endPos.assign( positionWorld );
  19211. } ).Else( () => {
  19212. startPos.assign( positionWorld );
  19213. endPos.assign( cameraPosition );
  19214. } );
  19215. //
  19216. const viewVector = endPos.sub( startPos );
  19217. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19218. const stepSize = viewVector.length().div( steps ).toVar();
  19219. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19220. const distTravelled = float( 0.0 ).toVar();
  19221. const transmittance = vec3( 1 ).toVar();
  19222. if ( material.offsetNode ) {
  19223. // reduce banding
  19224. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19225. }
  19226. Loop( steps, () => {
  19227. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19228. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19229. if ( material.depthNode !== null ) {
  19230. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19231. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19232. }
  19233. context.positionWorld = positionRay;
  19234. context.shadowPositionWorld = positionRay;
  19235. context.positionView = positionViewRay;
  19236. scatteringDensity.assign( 0 );
  19237. let scatteringNode;
  19238. if ( material.scatteringNode ) {
  19239. scatteringNode = material.scatteringNode( {
  19240. positionRay
  19241. } );
  19242. }
  19243. super.start( builder );
  19244. if ( scatteringNode ) {
  19245. scatteringDensity.mulAssign( scatteringNode );
  19246. }
  19247. // beer's law
  19248. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19249. transmittance.mulAssign( falloff );
  19250. // move along the ray
  19251. distTravelled.addAssign( stepSize );
  19252. } );
  19253. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19254. }
  19255. scatteringLight( lightColor, builder ) {
  19256. const sceneDepthNode = builder.context.sceneDepthNode;
  19257. if ( sceneDepthNode ) {
  19258. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19259. scatteringDensity.addAssign( lightColor );
  19260. } );
  19261. } else {
  19262. scatteringDensity.addAssign( lightColor );
  19263. }
  19264. }
  19265. direct( { lightNode, lightColor }, builder ) {
  19266. // Ignore lights with infinite distance
  19267. if ( lightNode.light.distance === undefined ) return;
  19268. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19269. const directLight = lightColor.xyz.toVar();
  19270. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19271. this.scatteringLight( directLight, builder );
  19272. }
  19273. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19274. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19275. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19276. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19277. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19278. const P = builder.context.positionView;
  19279. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19280. this.scatteringLight( directLight, builder );
  19281. }
  19282. finish( builder ) {
  19283. builder.context.outgoingLight.assign( outgoingRayLight );
  19284. }
  19285. }
  19286. /**
  19287. * Volume node material.
  19288. *
  19289. * @augments NodeMaterial
  19290. */
  19291. class VolumeNodeMaterial extends NodeMaterial {
  19292. static get type() {
  19293. return 'VolumeNodeMaterial';
  19294. }
  19295. /**
  19296. * Constructs a new volume node material.
  19297. *
  19298. * @param {Object} [parameters] - The configuration parameter.
  19299. */
  19300. constructor( parameters ) {
  19301. super();
  19302. /**
  19303. * This flag can be used for type testing.
  19304. *
  19305. * @type {boolean}
  19306. * @readonly
  19307. * @default true
  19308. */
  19309. this.isVolumeNodeMaterial = true;
  19310. /**
  19311. * Number of steps used for raymarching.
  19312. *
  19313. * @type {number}
  19314. * @default 25
  19315. */
  19316. this.steps = 25;
  19317. /**
  19318. * Offsets the distance a ray has been traveled through a volume.
  19319. * Can be used to implement dithering to reduce banding.
  19320. *
  19321. * @type {Node<float>}
  19322. * @default null
  19323. */
  19324. this.offsetNode = null;
  19325. /**
  19326. * Node used for scattering calculations.
  19327. *
  19328. * @type {Function|FunctionNode<vec4>}
  19329. * @default null
  19330. */
  19331. this.scatteringNode = null;
  19332. this.lights = true;
  19333. this.transparent = true;
  19334. this.side = BackSide;
  19335. this.depthTest = false;
  19336. this.depthWrite = false;
  19337. this.setValues( parameters );
  19338. }
  19339. setupLightingModel() {
  19340. return new VolumetricLightingModel();
  19341. }
  19342. }
  19343. /**
  19344. * This module manages the internal animation loop of the renderer.
  19345. *
  19346. * @private
  19347. */
  19348. class Animation {
  19349. /**
  19350. * Constructs a new animation loop management component.
  19351. *
  19352. * @param {Renderer} renderer - A reference to the main renderer.
  19353. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19354. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19355. */
  19356. constructor( renderer, nodes, info ) {
  19357. /**
  19358. * A reference to the main renderer.
  19359. *
  19360. * @type {Renderer}
  19361. */
  19362. this.renderer = renderer;
  19363. /**
  19364. * Renderer component for managing nodes related logic.
  19365. *
  19366. * @type {Nodes}
  19367. */
  19368. this.nodes = nodes;
  19369. /**
  19370. * Renderer component for managing metrics and monitoring data.
  19371. *
  19372. * @type {Info}
  19373. */
  19374. this.info = info;
  19375. /**
  19376. * A reference to the context from `requestAnimationFrame()` can
  19377. * be called (usually `window`).
  19378. *
  19379. * @type {?(Window|XRSession)}
  19380. */
  19381. this._context = typeof self !== 'undefined' ? self : null;
  19382. /**
  19383. * The user-defined animation loop.
  19384. *
  19385. * @type {?Function}
  19386. * @default null
  19387. */
  19388. this._animationLoop = null;
  19389. /**
  19390. * The requestId which is returned from the `requestAnimationFrame()` call.
  19391. * Can be used to cancel the stop the animation loop.
  19392. *
  19393. * @type {?number}
  19394. * @default null
  19395. */
  19396. this._requestId = null;
  19397. }
  19398. /**
  19399. * Starts the internal animation loop.
  19400. */
  19401. start() {
  19402. const update = ( time, xrFrame ) => {
  19403. this._requestId = this._context.requestAnimationFrame( update );
  19404. if ( this.info.autoReset === true ) this.info.reset();
  19405. this.nodes.nodeFrame.update();
  19406. this.info.frame = this.nodes.nodeFrame.frameId;
  19407. this.renderer._inspector.begin();
  19408. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19409. this.renderer._inspector.finish();
  19410. };
  19411. update();
  19412. }
  19413. /**
  19414. * Stops the internal animation loop.
  19415. */
  19416. stop() {
  19417. this._context.cancelAnimationFrame( this._requestId );
  19418. this._requestId = null;
  19419. }
  19420. /**
  19421. * Returns the user-level animation loop.
  19422. *
  19423. * @return {?Function} The animation loop.
  19424. */
  19425. getAnimationLoop() {
  19426. return this._animationLoop;
  19427. }
  19428. /**
  19429. * Defines the user-level animation loop.
  19430. *
  19431. * @param {?Function} callback - The animation loop.
  19432. */
  19433. setAnimationLoop( callback ) {
  19434. this._animationLoop = callback;
  19435. }
  19436. /**
  19437. * Returns the animation context.
  19438. *
  19439. * @return {Window|XRSession} The animation context.
  19440. */
  19441. getContext() {
  19442. return this._context;
  19443. }
  19444. /**
  19445. * Defines the context in which `requestAnimationFrame()` is executed.
  19446. *
  19447. * @param {Window|XRSession} context - The context to set.
  19448. */
  19449. setContext( context ) {
  19450. this._context = context;
  19451. }
  19452. /**
  19453. * Frees all internal resources and stops the animation loop.
  19454. */
  19455. dispose() {
  19456. this.stop();
  19457. }
  19458. }
  19459. /**
  19460. * Data structure for the renderer. It allows defining values
  19461. * with chained, hierarchical keys. Keys are meant to be
  19462. * objects since the module internally works with Weak Maps
  19463. * for performance reasons.
  19464. *
  19465. * @private
  19466. */
  19467. class ChainMap {
  19468. /**
  19469. * Constructs a new Chain Map.
  19470. */
  19471. constructor() {
  19472. /**
  19473. * The root Weak Map.
  19474. *
  19475. * @type {WeakMap<Object, WeakMap>}
  19476. */
  19477. this.weakMap = new WeakMap();
  19478. }
  19479. /**
  19480. * Returns the value for the given array of keys.
  19481. *
  19482. * @param {Array<Object>} keys - List of keys.
  19483. * @return {any} The value. Returns `undefined` if no value was found.
  19484. */
  19485. get( keys ) {
  19486. let map = this.weakMap;
  19487. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19488. map = map.get( keys[ i ] );
  19489. if ( map === undefined ) return undefined;
  19490. }
  19491. return map.get( keys[ keys.length - 1 ] );
  19492. }
  19493. /**
  19494. * Sets the value for the given keys.
  19495. *
  19496. * @param {Array<Object>} keys - List of keys.
  19497. * @param {any} value - The value to set.
  19498. * @return {ChainMap} A reference to this Chain Map.
  19499. */
  19500. set( keys, value ) {
  19501. let map = this.weakMap;
  19502. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19503. const key = keys[ i ];
  19504. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  19505. map = map.get( key );
  19506. }
  19507. map.set( keys[ keys.length - 1 ], value );
  19508. return this;
  19509. }
  19510. /**
  19511. * Deletes a value for the given keys.
  19512. *
  19513. * @param {Array<Object>} keys - The keys.
  19514. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19515. */
  19516. delete( keys ) {
  19517. let map = this.weakMap;
  19518. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19519. map = map.get( keys[ i ] );
  19520. if ( map === undefined ) return false;
  19521. }
  19522. return map.delete( keys[ keys.length - 1 ] );
  19523. }
  19524. }
  19525. let _id$9 = 0;
  19526. function getKeys( obj ) {
  19527. const keys = Object.keys( obj );
  19528. let proto = Object.getPrototypeOf( obj );
  19529. while ( proto ) {
  19530. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19531. for ( const key in descriptors ) {
  19532. if ( descriptors[ key ] !== undefined ) {
  19533. const descriptor = descriptors[ key ];
  19534. if ( descriptor && typeof descriptor.get === 'function' ) {
  19535. keys.push( key );
  19536. }
  19537. }
  19538. }
  19539. proto = Object.getPrototypeOf( proto );
  19540. }
  19541. return keys;
  19542. }
  19543. /**
  19544. * A render object is the renderer's representation of single entity that gets drawn
  19545. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19546. * scene since render objects also depend from the used material, the current render context
  19547. * and the current scene's lighting.
  19548. *
  19549. * In general, the basic process of the renderer is:
  19550. *
  19551. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19552. * - Process the render lists by calling one or more render commands for each render item.
  19553. * - For each render command, request a render object and perform the draw.
  19554. *
  19555. * The module provides an interface to get data required for the draw command like the actual
  19556. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19557. * creating render objects should only be done when necessary.
  19558. *
  19559. * @private
  19560. */
  19561. class RenderObject {
  19562. /**
  19563. * Constructs a new render object.
  19564. *
  19565. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19566. * @param {Geometries} geometries - Renderer component for managing geometries.
  19567. * @param {Renderer} renderer - The renderer.
  19568. * @param {Object3D} object - The 3D object.
  19569. * @param {Material} material - The 3D object's material.
  19570. * @param {Scene} scene - The scene the 3D object belongs to.
  19571. * @param {Camera} camera - The camera the object should be rendered with.
  19572. * @param {LightsNode} lightsNode - The lights node.
  19573. * @param {RenderContext} renderContext - The render context.
  19574. * @param {ClippingContext} clippingContext - The clipping context.
  19575. */
  19576. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19577. this.id = _id$9 ++;
  19578. /**
  19579. * Renderer component for managing nodes related logic.
  19580. *
  19581. * @type {Nodes}
  19582. * @private
  19583. */
  19584. this._nodes = nodes;
  19585. /**
  19586. * Renderer component for managing geometries.
  19587. *
  19588. * @type {Geometries}
  19589. * @private
  19590. */
  19591. this._geometries = geometries;
  19592. /**
  19593. * The renderer.
  19594. *
  19595. * @type {Renderer}
  19596. */
  19597. this.renderer = renderer;
  19598. /**
  19599. * The 3D object.
  19600. *
  19601. * @type {Object3D}
  19602. */
  19603. this.object = object;
  19604. /**
  19605. * The 3D object's material.
  19606. *
  19607. * @type {Material}
  19608. */
  19609. this.material = material;
  19610. /**
  19611. * The scene the 3D object belongs to.
  19612. *
  19613. * @type {Scene}
  19614. */
  19615. this.scene = scene;
  19616. /**
  19617. * The camera the 3D object should be rendered with.
  19618. *
  19619. * @type {Camera}
  19620. */
  19621. this.camera = camera;
  19622. /**
  19623. * The lights node.
  19624. *
  19625. * @type {LightsNode}
  19626. */
  19627. this.lightsNode = lightsNode;
  19628. /**
  19629. * The render context.
  19630. *
  19631. * @type {RenderContext}
  19632. */
  19633. this.context = renderContext;
  19634. /**
  19635. * The 3D object's geometry.
  19636. *
  19637. * @type {BufferGeometry}
  19638. */
  19639. this.geometry = object.geometry;
  19640. /**
  19641. * The render object's version.
  19642. *
  19643. * @type {number}
  19644. */
  19645. this.version = material.version;
  19646. /**
  19647. * The draw range of the geometry.
  19648. *
  19649. * @type {?Object}
  19650. * @default null
  19651. */
  19652. this.drawRange = null;
  19653. /**
  19654. * An array holding the buffer attributes
  19655. * of the render object. This entails attribute
  19656. * definitions on geometry and node level.
  19657. *
  19658. * @type {?Array<BufferAttribute>}
  19659. * @default null
  19660. */
  19661. this.attributes = null;
  19662. /**
  19663. * An object holding the version of the
  19664. * attributes. The keys are the attribute names
  19665. * and the values are the attribute versions.
  19666. *
  19667. * @type {?Object<string, number>}
  19668. * @default null
  19669. */
  19670. this.attributesId = null;
  19671. /**
  19672. * A reference to a render pipeline the render
  19673. * object is processed with.
  19674. *
  19675. * @type {RenderPipeline}
  19676. * @default null
  19677. */
  19678. this.pipeline = null;
  19679. /**
  19680. * Only relevant for objects using
  19681. * multiple materials. This represents a group entry
  19682. * from the respective `BufferGeometry`.
  19683. *
  19684. * @type {?{start: number, count: number}}
  19685. * @default null
  19686. */
  19687. this.group = null;
  19688. /**
  19689. * An array holding the vertex buffers which can
  19690. * be buffer attributes but also interleaved buffers.
  19691. *
  19692. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19693. * @default null
  19694. */
  19695. this.vertexBuffers = null;
  19696. /**
  19697. * The parameters for the draw command.
  19698. *
  19699. * @type {?Object}
  19700. * @default null
  19701. */
  19702. this.drawParams = null;
  19703. /**
  19704. * If this render object is used inside a render bundle,
  19705. * this property points to the respective bundle group.
  19706. *
  19707. * @type {?BundleGroup}
  19708. * @default null
  19709. */
  19710. this.bundle = null;
  19711. /**
  19712. * The clipping context.
  19713. *
  19714. * @type {ClippingContext}
  19715. */
  19716. this.clippingContext = clippingContext;
  19717. /**
  19718. * The clipping context's cache key.
  19719. *
  19720. * @type {string}
  19721. */
  19722. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19723. /**
  19724. * The initial node cache key.
  19725. *
  19726. * @type {number}
  19727. */
  19728. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19729. /**
  19730. * The initial cache key.
  19731. *
  19732. * @type {number}
  19733. */
  19734. this.initialCacheKey = this.getCacheKey();
  19735. /**
  19736. * The node builder state.
  19737. *
  19738. * @type {?NodeBuilderState}
  19739. * @private
  19740. * @default null
  19741. */
  19742. this._nodeBuilderState = null;
  19743. /**
  19744. * An array of bindings.
  19745. *
  19746. * @type {?Array<BindGroup>}
  19747. * @private
  19748. * @default null
  19749. */
  19750. this._bindings = null;
  19751. /**
  19752. * Reference to the node material observer.
  19753. *
  19754. * @type {?NodeMaterialObserver}
  19755. * @private
  19756. * @default null
  19757. */
  19758. this._monitor = null;
  19759. /**
  19760. * An event listener which is defined by `RenderObjects`. It performs
  19761. * clean up tasks when `dispose()` on this render object.
  19762. *
  19763. * @method
  19764. */
  19765. this.onDispose = null;
  19766. /**
  19767. * This flag can be used for type testing.
  19768. *
  19769. * @type {boolean}
  19770. * @readonly
  19771. * @default true
  19772. */
  19773. this.isRenderObject = true;
  19774. /**
  19775. * An event listener which is executed when `dispose()` is called on
  19776. * the material of this render object.
  19777. *
  19778. * @method
  19779. */
  19780. this.onMaterialDispose = () => {
  19781. this.dispose();
  19782. };
  19783. /**
  19784. * An event listener which is executed when `dispose()` is called on
  19785. * the geometry of this render object.
  19786. *
  19787. * @method
  19788. */
  19789. this.onGeometryDispose = () => {
  19790. // clear geometry cache attributes
  19791. this.attributes = null;
  19792. this.attributesId = null;
  19793. };
  19794. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19795. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19796. }
  19797. /**
  19798. * Updates the clipping context.
  19799. *
  19800. * @param {ClippingContext} context - The clipping context to set.
  19801. */
  19802. updateClipping( context ) {
  19803. this.clippingContext = context;
  19804. }
  19805. /**
  19806. * Whether the clipping requires an update or not.
  19807. *
  19808. * @type {boolean}
  19809. * @readonly
  19810. */
  19811. get clippingNeedsUpdate() {
  19812. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19813. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19814. return true;
  19815. }
  19816. /**
  19817. * The number of clipping planes defined in context of hardware clipping.
  19818. *
  19819. * @type {number}
  19820. * @readonly
  19821. */
  19822. get hardwareClippingPlanes() {
  19823. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19824. }
  19825. /**
  19826. * Returns the node builder state of this render object.
  19827. *
  19828. * @return {NodeBuilderState} The node builder state.
  19829. */
  19830. getNodeBuilderState() {
  19831. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  19832. }
  19833. /**
  19834. * Returns the node material observer of this render object.
  19835. *
  19836. * @return {NodeMaterialObserver} The node material observer.
  19837. */
  19838. getMonitor() {
  19839. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  19840. }
  19841. /**
  19842. * Returns an array of bind groups of this render object.
  19843. *
  19844. * @return {Array<BindGroup>} The bindings.
  19845. */
  19846. getBindings() {
  19847. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  19848. }
  19849. /**
  19850. * Returns a binding group by group name of this render object.
  19851. *
  19852. * @param {string} name - The name of the binding group.
  19853. * @return {?BindGroup} The bindings.
  19854. */
  19855. getBindingGroup( name ) {
  19856. for ( const bindingGroup of this.getBindings() ) {
  19857. if ( bindingGroup.name === name ) {
  19858. return bindingGroup;
  19859. }
  19860. }
  19861. }
  19862. /**
  19863. * Returns the index of the render object's geometry.
  19864. *
  19865. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19866. */
  19867. getIndex() {
  19868. return this._geometries.getIndex( this );
  19869. }
  19870. /**
  19871. * Returns the indirect buffer attribute.
  19872. *
  19873. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19874. */
  19875. getIndirect() {
  19876. return this._geometries.getIndirect( this );
  19877. }
  19878. /**
  19879. * Returns an array that acts as a key for identifying the render object in a chain map.
  19880. *
  19881. * @return {Array<Object>} An array with object references.
  19882. */
  19883. getChainArray() {
  19884. return [ this.object, this.material, this.context, this.lightsNode ];
  19885. }
  19886. /**
  19887. * This method is used when the geometry of a 3D object has been exchanged and the
  19888. * respective render object now requires an update.
  19889. *
  19890. * @param {BufferGeometry} geometry - The geometry to set.
  19891. */
  19892. setGeometry( geometry ) {
  19893. this.geometry = geometry;
  19894. this.attributes = null;
  19895. this.attributesId = null;
  19896. }
  19897. /**
  19898. * Returns the buffer attributes of the render object. The returned array holds
  19899. * attribute definitions on geometry and node level.
  19900. *
  19901. * @return {Array<BufferAttribute>} An array with buffer attributes.
  19902. */
  19903. getAttributes() {
  19904. if ( this.attributes !== null ) return this.attributes;
  19905. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  19906. const geometry = this.geometry;
  19907. const attributes = [];
  19908. const vertexBuffers = new Set();
  19909. const attributesId = {};
  19910. for ( const nodeAttribute of nodeAttributes ) {
  19911. let attribute;
  19912. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  19913. // node attribute
  19914. attribute = nodeAttribute.node.attribute;
  19915. } else {
  19916. // geometry attribute
  19917. attribute = geometry.getAttribute( nodeAttribute.name );
  19918. attributesId[ nodeAttribute.name ] = attribute.version;
  19919. }
  19920. if ( attribute === undefined ) continue;
  19921. attributes.push( attribute );
  19922. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  19923. vertexBuffers.add( bufferAttribute );
  19924. }
  19925. this.attributes = attributes;
  19926. this.attributesId = attributesId;
  19927. this.vertexBuffers = Array.from( vertexBuffers.values() );
  19928. return attributes;
  19929. }
  19930. /**
  19931. * Returns the vertex buffers of the render object.
  19932. *
  19933. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  19934. */
  19935. getVertexBuffers() {
  19936. if ( this.vertexBuffers === null ) this.getAttributes();
  19937. return this.vertexBuffers;
  19938. }
  19939. /**
  19940. * Returns the draw parameters for the render object.
  19941. *
  19942. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  19943. */
  19944. getDrawParameters() {
  19945. const { object, material, geometry, group, drawRange } = this;
  19946. const drawParams = this.drawParams || ( this.drawParams = {
  19947. vertexCount: 0,
  19948. firstVertex: 0,
  19949. instanceCount: 0,
  19950. firstInstance: 0
  19951. } );
  19952. const index = this.getIndex();
  19953. const hasIndex = ( index !== null );
  19954. let instanceCount = 1;
  19955. if ( geometry.isInstancedBufferGeometry === true ) {
  19956. instanceCount = geometry.instanceCount;
  19957. } else if ( object.count !== undefined ) {
  19958. instanceCount = Math.max( 0, object.count );
  19959. }
  19960. if ( instanceCount === 0 ) return null;
  19961. drawParams.instanceCount = instanceCount;
  19962. if ( object.isBatchedMesh === true ) return drawParams;
  19963. let rangeFactor = 1;
  19964. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  19965. rangeFactor = 2;
  19966. }
  19967. let firstVertex = drawRange.start * rangeFactor;
  19968. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  19969. if ( group !== null ) {
  19970. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  19971. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  19972. }
  19973. const position = geometry.attributes.position;
  19974. let itemCount = Infinity;
  19975. if ( hasIndex ) {
  19976. itemCount = index.count;
  19977. } else if ( position !== undefined && position !== null ) {
  19978. itemCount = position.count;
  19979. }
  19980. firstVertex = Math.max( firstVertex, 0 );
  19981. lastVertex = Math.min( lastVertex, itemCount );
  19982. const count = lastVertex - firstVertex;
  19983. if ( count < 0 || count === Infinity ) return null;
  19984. drawParams.vertexCount = count;
  19985. drawParams.firstVertex = firstVertex;
  19986. return drawParams;
  19987. }
  19988. /**
  19989. * Returns the render object's geometry cache key.
  19990. *
  19991. * The geometry cache key is part of the material cache key.
  19992. *
  19993. * @return {string} The geometry cache key.
  19994. */
  19995. getGeometryCacheKey() {
  19996. const { geometry } = this;
  19997. let cacheKey = '';
  19998. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  19999. const attribute = geometry.attributes[ name ];
  20000. cacheKey += name + ',';
  20001. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  20002. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  20003. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  20004. if ( attribute.normalized ) cacheKey += 'n,';
  20005. }
  20006. // structural equality isn't sufficient for morph targets since the
  20007. // data are maintained in textures. only if the targets are all equal
  20008. // the texture and thus the instance of `MorphNode` can be shared.
  20009. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  20010. const targets = geometry.morphAttributes[ name ];
  20011. cacheKey += 'morph-' + name + ',';
  20012. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  20013. const attribute = targets[ i ];
  20014. cacheKey += attribute.id + ',';
  20015. }
  20016. }
  20017. if ( geometry.index ) {
  20018. cacheKey += 'index,';
  20019. }
  20020. return cacheKey;
  20021. }
  20022. /**
  20023. * Returns the render object's material cache key.
  20024. *
  20025. * The material cache key is part of the render object cache key.
  20026. *
  20027. * @return {number} The material cache key.
  20028. */
  20029. getMaterialCacheKey() {
  20030. const { object, material, renderer } = this;
  20031. let cacheKey = material.customProgramCacheKey();
  20032. for ( const property of getKeys( material ) ) {
  20033. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  20034. const value = material[ property ];
  20035. let valueKey;
  20036. if ( value !== null ) {
  20037. // some material values require a formatting
  20038. const type = typeof value;
  20039. if ( type === 'number' ) {
  20040. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  20041. } else if ( type === 'object' ) {
  20042. valueKey = '{';
  20043. if ( value.isTexture ) {
  20044. valueKey += value.mapping;
  20045. // WebGPU must honor the sampler data because they are part of the bindings
  20046. if ( renderer.backend.isWebGPUBackend === true ) {
  20047. valueKey += value.magFilter;
  20048. valueKey += value.minFilter;
  20049. valueKey += value.wrapS;
  20050. valueKey += value.wrapT;
  20051. valueKey += value.wrapR;
  20052. }
  20053. }
  20054. valueKey += '}';
  20055. } else {
  20056. valueKey = String( value );
  20057. }
  20058. } else {
  20059. valueKey = String( value );
  20060. }
  20061. cacheKey += /*property + ':' +*/ valueKey + ',';
  20062. }
  20063. cacheKey += this.clippingContextCacheKey + ',';
  20064. if ( object.geometry ) {
  20065. cacheKey += this.getGeometryCacheKey();
  20066. }
  20067. if ( object.skeleton ) {
  20068. cacheKey += object.skeleton.bones.length + ',';
  20069. }
  20070. if ( object.isBatchedMesh ) {
  20071. cacheKey += object._matricesTexture.uuid + ',';
  20072. if ( object._colorsTexture !== null ) {
  20073. cacheKey += object._colorsTexture.uuid + ',';
  20074. }
  20075. }
  20076. if ( object.isInstancedMesh || object.count > 1 || Array.isArray( object.morphTargetInfluences ) ) {
  20077. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  20078. cacheKey += object.uuid + ',';
  20079. }
  20080. cacheKey += object.receiveShadow + ',';
  20081. return hashString( cacheKey );
  20082. }
  20083. /**
  20084. * Whether the geometry requires an update or not.
  20085. *
  20086. * @type {boolean}
  20087. * @readonly
  20088. */
  20089. get needsGeometryUpdate() {
  20090. if ( this.geometry.id !== this.object.geometry.id ) return true;
  20091. if ( this.attributes !== null ) {
  20092. const attributesId = this.attributesId;
  20093. for ( const name in attributesId ) {
  20094. const attribute = this.geometry.getAttribute( name );
  20095. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  20096. return true;
  20097. }
  20098. }
  20099. }
  20100. return false;
  20101. }
  20102. /**
  20103. * Whether the render object requires an update or not.
  20104. *
  20105. * Note: There are two distinct places where render objects are checked for an update.
  20106. *
  20107. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  20108. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  20109. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  20110. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  20111. * a need for a refresh due to material, geometry or object related value changes.
  20112. *
  20113. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  20114. * that performs the 'needsUpdate' check.
  20115. *
  20116. * @type {boolean}
  20117. * @readonly
  20118. */
  20119. get needsUpdate() {
  20120. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  20121. }
  20122. /**
  20123. * Returns the dynamic cache key which represents a key that is computed per draw command.
  20124. *
  20125. * @return {number} The cache key.
  20126. */
  20127. getDynamicCacheKey() {
  20128. let cacheKey = 0;
  20129. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  20130. // the renderer is inside a shadow pass.
  20131. if ( this.material.isShadowPassMaterial !== true ) {
  20132. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  20133. }
  20134. if ( this.camera.isArrayCamera ) {
  20135. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  20136. }
  20137. if ( this.object.receiveShadow ) {
  20138. cacheKey = hash$1( cacheKey, 1 );
  20139. }
  20140. return cacheKey;
  20141. }
  20142. /**
  20143. * Returns the render object's cache key.
  20144. *
  20145. * @return {number} The cache key.
  20146. */
  20147. getCacheKey() {
  20148. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  20149. }
  20150. /**
  20151. * Frees internal resources.
  20152. */
  20153. dispose() {
  20154. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  20155. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  20156. this.onDispose();
  20157. }
  20158. }
  20159. const _chainKeys$5 = [];
  20160. /**
  20161. * This module manages the render objects of the renderer.
  20162. *
  20163. * @private
  20164. */
  20165. class RenderObjects {
  20166. /**
  20167. * Constructs a new render object management component.
  20168. *
  20169. * @param {Renderer} renderer - The renderer.
  20170. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20171. * @param {Geometries} geometries - Renderer component for managing geometries.
  20172. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20173. * @param {Bindings} bindings - Renderer component for managing bindings.
  20174. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20175. */
  20176. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20177. /**
  20178. * The renderer.
  20179. *
  20180. * @type {Renderer}
  20181. */
  20182. this.renderer = renderer;
  20183. /**
  20184. * Renderer component for managing nodes related logic.
  20185. *
  20186. * @type {Nodes}
  20187. */
  20188. this.nodes = nodes;
  20189. /**
  20190. * Renderer component for managing geometries.
  20191. *
  20192. * @type {Geometries}
  20193. */
  20194. this.geometries = geometries;
  20195. /**
  20196. * Renderer component for managing pipelines.
  20197. *
  20198. * @type {Pipelines}
  20199. */
  20200. this.pipelines = pipelines;
  20201. /**
  20202. * Renderer component for managing bindings.
  20203. *
  20204. * @type {Bindings}
  20205. */
  20206. this.bindings = bindings;
  20207. /**
  20208. * Renderer component for managing metrics and monitoring data.
  20209. *
  20210. * @type {Info}
  20211. */
  20212. this.info = info;
  20213. /**
  20214. * A dictionary that manages render contexts in chain maps
  20215. * for each pass ID.
  20216. *
  20217. * @type {Object<string,ChainMap>}
  20218. */
  20219. this.chainMaps = {};
  20220. }
  20221. /**
  20222. * Returns a render object for the given object and state data.
  20223. *
  20224. * @param {Object3D} object - The 3D object.
  20225. * @param {Material} material - The 3D object's material.
  20226. * @param {Scene} scene - The scene the 3D object belongs to.
  20227. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20228. * @param {LightsNode} lightsNode - The lights node.
  20229. * @param {RenderContext} renderContext - The render context.
  20230. * @param {ClippingContext} clippingContext - The clipping context.
  20231. * @param {string} [passId] - An optional ID for identifying the pass.
  20232. * @return {RenderObject} The render object.
  20233. */
  20234. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20235. const chainMap = this.getChainMap( passId );
  20236. // reuse chainArray
  20237. _chainKeys$5[ 0 ] = object;
  20238. _chainKeys$5[ 1 ] = material;
  20239. _chainKeys$5[ 2 ] = renderContext;
  20240. _chainKeys$5[ 3 ] = lightsNode;
  20241. let renderObject = chainMap.get( _chainKeys$5 );
  20242. if ( renderObject === undefined ) {
  20243. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20244. chainMap.set( _chainKeys$5, renderObject );
  20245. } else {
  20246. renderObject.updateClipping( clippingContext );
  20247. if ( renderObject.needsGeometryUpdate ) {
  20248. renderObject.setGeometry( object.geometry );
  20249. }
  20250. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20251. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20252. renderObject.dispose();
  20253. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20254. } else {
  20255. renderObject.version = material.version;
  20256. }
  20257. }
  20258. }
  20259. _chainKeys$5.length = 0;
  20260. return renderObject;
  20261. }
  20262. /**
  20263. * Returns a chain map for the given pass ID.
  20264. *
  20265. * @param {string} [passId='default'] - The pass ID.
  20266. * @return {ChainMap} The chain map.
  20267. */
  20268. getChainMap( passId = 'default' ) {
  20269. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20270. }
  20271. /**
  20272. * Frees internal resources.
  20273. */
  20274. dispose() {
  20275. this.chainMaps = {};
  20276. }
  20277. /**
  20278. * Factory method for creating render objects with the given list of parameters.
  20279. *
  20280. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20281. * @param {Geometries} geometries - Renderer component for managing geometries.
  20282. * @param {Renderer} renderer - The renderer.
  20283. * @param {Object3D} object - The 3D object.
  20284. * @param {Material} material - The object's material.
  20285. * @param {Scene} scene - The scene the 3D object belongs to.
  20286. * @param {Camera} camera - The camera the object should be rendered with.
  20287. * @param {LightsNode} lightsNode - The lights node.
  20288. * @param {RenderContext} renderContext - The render context.
  20289. * @param {ClippingContext} clippingContext - The clipping context.
  20290. * @param {string} [passId] - An optional ID for identifying the pass.
  20291. * @return {RenderObject} The render object.
  20292. */
  20293. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20294. const chainMap = this.getChainMap( passId );
  20295. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  20296. renderObject.onDispose = () => {
  20297. this.pipelines.delete( renderObject );
  20298. this.bindings.deleteForRender( renderObject );
  20299. this.nodes.delete( renderObject );
  20300. chainMap.delete( renderObject.getChainArray() );
  20301. };
  20302. return renderObject;
  20303. }
  20304. }
  20305. /**
  20306. * Data structure for the renderer. It is intended to manage
  20307. * data of objects in dictionaries.
  20308. *
  20309. * @private
  20310. */
  20311. class DataMap {
  20312. /**
  20313. * Constructs a new data map.
  20314. */
  20315. constructor() {
  20316. /**
  20317. * `DataMap` internally uses a weak map
  20318. * to manage its data.
  20319. *
  20320. * @type {WeakMap<Object, Object>}
  20321. */
  20322. this.data = new WeakMap();
  20323. }
  20324. /**
  20325. * Returns the dictionary for the given object.
  20326. *
  20327. * @param {Object} object - The object.
  20328. * @return {Object} The dictionary.
  20329. */
  20330. get( object ) {
  20331. let map = this.data.get( object );
  20332. if ( map === undefined ) {
  20333. map = {};
  20334. this.data.set( object, map );
  20335. }
  20336. return map;
  20337. }
  20338. /**
  20339. * Deletes the dictionary for the given object.
  20340. *
  20341. * @param {Object} object - The object.
  20342. * @return {?Object} The deleted dictionary.
  20343. */
  20344. delete( object ) {
  20345. let map = null;
  20346. if ( this.data.has( object ) ) {
  20347. map = this.data.get( object );
  20348. this.data.delete( object );
  20349. }
  20350. return map;
  20351. }
  20352. /**
  20353. * Returns `true` if the given object has a dictionary defined.
  20354. *
  20355. * @param {Object} object - The object to test.
  20356. * @return {boolean} Whether a dictionary is defined or not.
  20357. */
  20358. has( object ) {
  20359. return this.data.has( object );
  20360. }
  20361. /**
  20362. * Frees internal resources.
  20363. */
  20364. dispose() {
  20365. this.data = new WeakMap();
  20366. }
  20367. }
  20368. const AttributeType = {
  20369. VERTEX: 1,
  20370. INDEX: 2,
  20371. STORAGE: 3,
  20372. INDIRECT: 4
  20373. };
  20374. // size of a chunk in bytes (STD140 layout)
  20375. const GPU_CHUNK_BYTES = 16;
  20376. // @TODO: Move to src/constants.js
  20377. const BlendColorFactor = 211;
  20378. const OneMinusBlendColorFactor = 212;
  20379. /**
  20380. * This renderer module manages geometry attributes.
  20381. *
  20382. * @private
  20383. * @augments DataMap
  20384. */
  20385. class Attributes extends DataMap {
  20386. /**
  20387. * Constructs a new attribute management component.
  20388. *
  20389. * @param {Backend} backend - The renderer's backend.
  20390. */
  20391. constructor( backend ) {
  20392. super();
  20393. /**
  20394. * The renderer's backend.
  20395. *
  20396. * @type {Backend}
  20397. */
  20398. this.backend = backend;
  20399. }
  20400. /**
  20401. * Deletes the data for the given attribute.
  20402. *
  20403. * @param {BufferAttribute} attribute - The attribute.
  20404. * @return {?Object} The deleted attribute data.
  20405. */
  20406. delete( attribute ) {
  20407. const attributeData = super.delete( attribute );
  20408. if ( attributeData !== null ) {
  20409. this.backend.destroyAttribute( attribute );
  20410. }
  20411. return attributeData;
  20412. }
  20413. /**
  20414. * Updates the given attribute. This method creates attribute buffers
  20415. * for new attributes and updates data for existing ones.
  20416. *
  20417. * @param {BufferAttribute} attribute - The attribute to update.
  20418. * @param {number} type - The attribute type.
  20419. */
  20420. update( attribute, type ) {
  20421. const data = this.get( attribute );
  20422. if ( data.version === undefined ) {
  20423. if ( type === AttributeType.VERTEX ) {
  20424. this.backend.createAttribute( attribute );
  20425. } else if ( type === AttributeType.INDEX ) {
  20426. this.backend.createIndexAttribute( attribute );
  20427. } else if ( type === AttributeType.STORAGE ) {
  20428. this.backend.createStorageAttribute( attribute );
  20429. } else if ( type === AttributeType.INDIRECT ) {
  20430. this.backend.createIndirectStorageAttribute( attribute );
  20431. }
  20432. data.version = this._getBufferAttribute( attribute ).version;
  20433. } else {
  20434. const bufferAttribute = this._getBufferAttribute( attribute );
  20435. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20436. this.backend.updateAttribute( attribute );
  20437. data.version = bufferAttribute.version;
  20438. }
  20439. }
  20440. }
  20441. /**
  20442. * Utility method for handling interleaved buffer attributes correctly.
  20443. * To process them, their `InterleavedBuffer` is returned.
  20444. *
  20445. * @param {BufferAttribute} attribute - The attribute.
  20446. * @return {BufferAttribute|InterleavedBuffer}
  20447. */
  20448. _getBufferAttribute( attribute ) {
  20449. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20450. return attribute;
  20451. }
  20452. }
  20453. /**
  20454. * Returns the wireframe version for the given geometry.
  20455. *
  20456. * @private
  20457. * @function
  20458. * @param {BufferGeometry} geometry - The geometry.
  20459. * @return {number} The version.
  20460. */
  20461. function getWireframeVersion( geometry ) {
  20462. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  20463. }
  20464. /**
  20465. * Returns a wireframe index attribute for the given geometry.
  20466. *
  20467. * @private
  20468. * @function
  20469. * @param {BufferGeometry} geometry - The geometry.
  20470. * @return {BufferAttribute} The wireframe index attribute.
  20471. */
  20472. function getWireframeIndex( geometry ) {
  20473. const indices = [];
  20474. const geometryIndex = geometry.index;
  20475. const geometryPosition = geometry.attributes.position;
  20476. if ( geometryIndex !== null ) {
  20477. const array = geometryIndex.array;
  20478. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  20479. const a = array[ i + 0 ];
  20480. const b = array[ i + 1 ];
  20481. const c = array[ i + 2 ];
  20482. indices.push( a, b, b, c, c, a );
  20483. }
  20484. } else {
  20485. const array = geometryPosition.array;
  20486. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  20487. const a = i + 0;
  20488. const b = i + 1;
  20489. const c = i + 2;
  20490. indices.push( a, b, b, c, c, a );
  20491. }
  20492. }
  20493. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  20494. attribute.version = getWireframeVersion( geometry );
  20495. return attribute;
  20496. }
  20497. /**
  20498. * This renderer module manages geometries.
  20499. *
  20500. * @private
  20501. * @augments DataMap
  20502. */
  20503. class Geometries extends DataMap {
  20504. /**
  20505. * Constructs a new geometry management component.
  20506. *
  20507. * @param {Attributes} attributes - Renderer component for managing attributes.
  20508. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20509. */
  20510. constructor( attributes, info ) {
  20511. super();
  20512. /**
  20513. * Renderer component for managing attributes.
  20514. *
  20515. * @type {Attributes}
  20516. */
  20517. this.attributes = attributes;
  20518. /**
  20519. * Renderer component for managing metrics and monitoring data.
  20520. *
  20521. * @type {Info}
  20522. */
  20523. this.info = info;
  20524. /**
  20525. * Weak Map for managing attributes for wireframe rendering.
  20526. *
  20527. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20528. */
  20529. this.wireframes = new WeakMap();
  20530. /**
  20531. * This Weak Map is used to make sure buffer attributes are
  20532. * updated only once per render call.
  20533. *
  20534. * @type {WeakMap<BufferAttribute,number>}
  20535. */
  20536. this.attributeCall = new WeakMap();
  20537. /**
  20538. * Stores the event listeners attached to geometries.
  20539. *
  20540. * @private
  20541. * @type {Map<BufferGeometry,Function>}
  20542. */
  20543. this._geometryDisposeListeners = new Map();
  20544. }
  20545. /**
  20546. * Returns `true` if the given render object has an initialized geometry.
  20547. *
  20548. * @param {RenderObject} renderObject - The render object.
  20549. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20550. */
  20551. has( renderObject ) {
  20552. const geometry = renderObject.geometry;
  20553. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20554. }
  20555. /**
  20556. * Prepares the geometry of the given render object for rendering.
  20557. *
  20558. * @param {RenderObject} renderObject - The render object.
  20559. */
  20560. updateForRender( renderObject ) {
  20561. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20562. this.updateAttributes( renderObject );
  20563. }
  20564. /**
  20565. * Initializes the geometry of the given render object.
  20566. *
  20567. * @param {RenderObject} renderObject - The render object.
  20568. */
  20569. initGeometry( renderObject ) {
  20570. const geometry = renderObject.geometry;
  20571. const geometryData = this.get( geometry );
  20572. geometryData.initialized = true;
  20573. this.info.memory.geometries ++;
  20574. const onDispose = () => {
  20575. this.info.memory.geometries --;
  20576. const index = geometry.index;
  20577. const geometryAttributes = renderObject.getAttributes();
  20578. if ( index !== null ) {
  20579. this.attributes.delete( index );
  20580. }
  20581. for ( const geometryAttribute of geometryAttributes ) {
  20582. this.attributes.delete( geometryAttribute );
  20583. }
  20584. const wireframeAttribute = this.wireframes.get( geometry );
  20585. if ( wireframeAttribute !== undefined ) {
  20586. this.attributes.delete( wireframeAttribute );
  20587. }
  20588. geometry.removeEventListener( 'dispose', onDispose );
  20589. this._geometryDisposeListeners.delete( geometry );
  20590. };
  20591. geometry.addEventListener( 'dispose', onDispose );
  20592. // see #31798 why tracking separate remove listeners is required right now
  20593. // TODO: Re-evaluate how onDispose() is managed in this component
  20594. this._geometryDisposeListeners.set( geometry, onDispose );
  20595. }
  20596. /**
  20597. * Updates the geometry attributes of the given render object.
  20598. *
  20599. * @param {RenderObject} renderObject - The render object.
  20600. */
  20601. updateAttributes( renderObject ) {
  20602. // attributes
  20603. const attributes = renderObject.getAttributes();
  20604. for ( const attribute of attributes ) {
  20605. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20606. this.updateAttribute( attribute, AttributeType.STORAGE );
  20607. } else {
  20608. this.updateAttribute( attribute, AttributeType.VERTEX );
  20609. }
  20610. }
  20611. // indexes
  20612. const index = this.getIndex( renderObject );
  20613. if ( index !== null ) {
  20614. this.updateAttribute( index, AttributeType.INDEX );
  20615. }
  20616. // indirect
  20617. const indirect = renderObject.geometry.indirect;
  20618. if ( indirect !== null ) {
  20619. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20620. }
  20621. }
  20622. /**
  20623. * Updates the given attribute.
  20624. *
  20625. * @param {BufferAttribute} attribute - The attribute to update.
  20626. * @param {number} type - The attribute type.
  20627. */
  20628. updateAttribute( attribute, type ) {
  20629. const callId = this.info.render.calls;
  20630. if ( ! attribute.isInterleavedBufferAttribute ) {
  20631. if ( this.attributeCall.get( attribute ) !== callId ) {
  20632. this.attributes.update( attribute, type );
  20633. this.attributeCall.set( attribute, callId );
  20634. }
  20635. } else {
  20636. if ( this.attributeCall.get( attribute ) === undefined ) {
  20637. this.attributes.update( attribute, type );
  20638. this.attributeCall.set( attribute, callId );
  20639. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20640. this.attributes.update( attribute, type );
  20641. this.attributeCall.set( attribute.data, callId );
  20642. this.attributeCall.set( attribute, callId );
  20643. }
  20644. }
  20645. }
  20646. /**
  20647. * Returns the indirect buffer attribute of the given render object.
  20648. *
  20649. * @param {RenderObject} renderObject - The render object.
  20650. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20651. */
  20652. getIndirect( renderObject ) {
  20653. return renderObject.geometry.indirect;
  20654. }
  20655. /**
  20656. * Returns the index of the given render object's geometry. This is implemented
  20657. * in a method to return a wireframe index if necessary.
  20658. *
  20659. * @param {RenderObject} renderObject - The render object.
  20660. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20661. */
  20662. getIndex( renderObject ) {
  20663. const { geometry, material } = renderObject;
  20664. let index = geometry.index;
  20665. if ( material.wireframe === true ) {
  20666. const wireframes = this.wireframes;
  20667. let wireframeAttribute = wireframes.get( geometry );
  20668. if ( wireframeAttribute === undefined ) {
  20669. wireframeAttribute = getWireframeIndex( geometry );
  20670. wireframes.set( geometry, wireframeAttribute );
  20671. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20672. this.attributes.delete( wireframeAttribute );
  20673. wireframeAttribute = getWireframeIndex( geometry );
  20674. wireframes.set( geometry, wireframeAttribute );
  20675. }
  20676. index = wireframeAttribute;
  20677. }
  20678. return index;
  20679. }
  20680. dispose() {
  20681. for ( const [ geometry, onDispose ] of this._geometryDisposeListeners.entries() ) {
  20682. geometry.removeEventListener( 'dispose', onDispose );
  20683. }
  20684. this._geometryDisposeListeners.clear();
  20685. }
  20686. }
  20687. /**
  20688. * This renderer module provides a series of statistical information
  20689. * about the GPU memory and the rendering process. Useful for debugging
  20690. * and monitoring.
  20691. */
  20692. class Info {
  20693. /**
  20694. * Constructs a new info component.
  20695. */
  20696. constructor() {
  20697. /**
  20698. * Whether frame related metrics should automatically
  20699. * be resetted or not. This property should be set to `false`
  20700. * by apps which manage their own animation loop. They must
  20701. * then call `renderer.info.reset()` once per frame manually.
  20702. *
  20703. * @type {boolean}
  20704. * @default true
  20705. */
  20706. this.autoReset = true;
  20707. /**
  20708. * The current frame ID. This ID is managed
  20709. * by `NodeFrame`.
  20710. *
  20711. * @type {number}
  20712. * @readonly
  20713. * @default 0
  20714. */
  20715. this.frame = 0;
  20716. /**
  20717. * The number of render calls since the
  20718. * app has been started.
  20719. *
  20720. * @type {number}
  20721. * @readonly
  20722. * @default 0
  20723. */
  20724. this.calls = 0;
  20725. /**
  20726. * Render related metrics.
  20727. *
  20728. * @type {Object}
  20729. * @readonly
  20730. * @property {number} calls - The number of render calls since the app has been started.
  20731. * @property {number} frameCalls - The number of render calls of the current frame.
  20732. * @property {number} drawCalls - The number of draw calls of the current frame.
  20733. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20734. * @property {number} points - The number of rendered point primitives of the current frame.
  20735. * @property {number} lines - The number of rendered line primitives of the current frame.
  20736. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  20737. */
  20738. this.render = {
  20739. calls: 0,
  20740. frameCalls: 0,
  20741. drawCalls: 0,
  20742. triangles: 0,
  20743. points: 0,
  20744. lines: 0,
  20745. timestamp: 0,
  20746. };
  20747. /**
  20748. * Compute related metrics.
  20749. *
  20750. * @type {Object}
  20751. * @readonly
  20752. * @property {number} calls - The number of compute calls since the app has been started.
  20753. * @property {number} frameCalls - The number of compute calls of the current frame.
  20754. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20755. */
  20756. this.compute = {
  20757. calls: 0,
  20758. frameCalls: 0,
  20759. timestamp: 0
  20760. };
  20761. /**
  20762. * Memory related metrics.
  20763. *
  20764. * @type {Object}
  20765. * @readonly
  20766. * @property {number} geometries - The number of active geometries.
  20767. * @property {number} frameCalls - The number of active textures.
  20768. */
  20769. this.memory = {
  20770. geometries: 0,
  20771. textures: 0
  20772. };
  20773. }
  20774. /**
  20775. * This method should be executed per draw call and updates the corresponding metrics.
  20776. *
  20777. * @param {Object3D} object - The 3D object that is going to be rendered.
  20778. * @param {number} count - The vertex or index count.
  20779. * @param {number} instanceCount - The instance count.
  20780. */
  20781. update( object, count, instanceCount ) {
  20782. this.render.drawCalls ++;
  20783. if ( object.isMesh || object.isSprite ) {
  20784. this.render.triangles += instanceCount * ( count / 3 );
  20785. } else if ( object.isPoints ) {
  20786. this.render.points += instanceCount * count;
  20787. } else if ( object.isLineSegments ) {
  20788. this.render.lines += instanceCount * ( count / 2 );
  20789. } else if ( object.isLine ) {
  20790. this.render.lines += instanceCount * ( count - 1 );
  20791. } else {
  20792. error( 'WebGPUInfo: Unknown object type.' );
  20793. }
  20794. }
  20795. /**
  20796. * Resets frame related metrics.
  20797. */
  20798. reset() {
  20799. this.render.drawCalls = 0;
  20800. this.render.frameCalls = 0;
  20801. this.compute.frameCalls = 0;
  20802. this.render.triangles = 0;
  20803. this.render.points = 0;
  20804. this.render.lines = 0;
  20805. }
  20806. /**
  20807. * Performs a complete reset of the object.
  20808. */
  20809. dispose() {
  20810. this.reset();
  20811. this.calls = 0;
  20812. this.render.calls = 0;
  20813. this.compute.calls = 0;
  20814. this.render.timestamp = 0;
  20815. this.compute.timestamp = 0;
  20816. this.memory.geometries = 0;
  20817. this.memory.textures = 0;
  20818. }
  20819. }
  20820. /**
  20821. * Abstract class for representing pipelines.
  20822. *
  20823. * @private
  20824. * @abstract
  20825. */
  20826. class Pipeline {
  20827. /**
  20828. * Constructs a new pipeline.
  20829. *
  20830. * @param {string} cacheKey - The pipeline's cache key.
  20831. */
  20832. constructor( cacheKey ) {
  20833. /**
  20834. * The pipeline's cache key.
  20835. *
  20836. * @type {string}
  20837. */
  20838. this.cacheKey = cacheKey;
  20839. /**
  20840. * How often the pipeline is currently in use.
  20841. *
  20842. * @type {number}
  20843. * @default 0
  20844. */
  20845. this.usedTimes = 0;
  20846. }
  20847. }
  20848. /**
  20849. * Class for representing render pipelines.
  20850. *
  20851. * @private
  20852. * @augments Pipeline
  20853. */
  20854. class RenderPipeline extends Pipeline {
  20855. /**
  20856. * Constructs a new render pipeline.
  20857. *
  20858. * @param {string} cacheKey - The pipeline's cache key.
  20859. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  20860. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  20861. */
  20862. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  20863. super( cacheKey );
  20864. /**
  20865. * The pipeline's vertex shader.
  20866. *
  20867. * @type {ProgrammableStage}
  20868. */
  20869. this.vertexProgram = vertexProgram;
  20870. /**
  20871. * The pipeline's fragment shader.
  20872. *
  20873. * @type {ProgrammableStage}
  20874. */
  20875. this.fragmentProgram = fragmentProgram;
  20876. }
  20877. }
  20878. /**
  20879. * Class for representing compute pipelines.
  20880. *
  20881. * @private
  20882. * @augments Pipeline
  20883. */
  20884. class ComputePipeline extends Pipeline {
  20885. /**
  20886. * Constructs a new render pipeline.
  20887. *
  20888. * @param {string} cacheKey - The pipeline's cache key.
  20889. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  20890. */
  20891. constructor( cacheKey, computeProgram ) {
  20892. super( cacheKey );
  20893. /**
  20894. * The pipeline's compute shader.
  20895. *
  20896. * @type {ProgrammableStage}
  20897. */
  20898. this.computeProgram = computeProgram;
  20899. /**
  20900. * This flag can be used for type testing.
  20901. *
  20902. * @type {boolean}
  20903. * @readonly
  20904. * @default true
  20905. */
  20906. this.isComputePipeline = true;
  20907. }
  20908. }
  20909. let _id$8 = 0;
  20910. /**
  20911. * Class for representing programmable stages which are vertex,
  20912. * fragment or compute shaders. Unlike fixed-function states (like blending),
  20913. * they represent the programmable part of a pipeline.
  20914. *
  20915. * @private
  20916. */
  20917. class ProgrammableStage {
  20918. /**
  20919. * Constructs a new programmable stage.
  20920. *
  20921. * @param {string} code - The shader code.
  20922. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  20923. * @param {string} name - The name of the shader.
  20924. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20925. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20926. */
  20927. constructor( code, stage, name, transforms = null, attributes = null ) {
  20928. /**
  20929. * The id of the programmable stage.
  20930. *
  20931. * @type {number}
  20932. */
  20933. this.id = _id$8 ++;
  20934. /**
  20935. * The shader code.
  20936. *
  20937. * @type {string}
  20938. */
  20939. this.code = code;
  20940. /**
  20941. * The type of stage.
  20942. *
  20943. * @type {string}
  20944. */
  20945. this.stage = stage;
  20946. /**
  20947. * The name of the stage.
  20948. * This is used for debugging purposes.
  20949. *
  20950. * @type {string}
  20951. */
  20952. this.name = name;
  20953. /**
  20954. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20955. *
  20956. * @type {?Array<Object>}
  20957. */
  20958. this.transforms = transforms;
  20959. /**
  20960. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20961. *
  20962. * @type {?Array<Object>}
  20963. */
  20964. this.attributes = attributes;
  20965. /**
  20966. * How often the programmable stage is currently in use.
  20967. *
  20968. * @type {number}
  20969. * @default 0
  20970. */
  20971. this.usedTimes = 0;
  20972. }
  20973. }
  20974. /**
  20975. * This renderer module manages the pipelines of the renderer.
  20976. *
  20977. * @private
  20978. * @augments DataMap
  20979. */
  20980. class Pipelines extends DataMap {
  20981. /**
  20982. * Constructs a new pipeline management component.
  20983. *
  20984. * @param {Backend} backend - The renderer's backend.
  20985. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20986. */
  20987. constructor( backend, nodes ) {
  20988. super();
  20989. /**
  20990. * The renderer's backend.
  20991. *
  20992. * @type {Backend}
  20993. */
  20994. this.backend = backend;
  20995. /**
  20996. * Renderer component for managing nodes related logic.
  20997. *
  20998. * @type {Nodes}
  20999. */
  21000. this.nodes = nodes;
  21001. /**
  21002. * A references to the bindings management component.
  21003. * This reference will be set inside the `Bindings`
  21004. * constructor.
  21005. *
  21006. * @type {?Bindings}
  21007. * @default null
  21008. */
  21009. this.bindings = null;
  21010. /**
  21011. * Internal cache for maintaining pipelines.
  21012. * The key of the map is a cache key, the value the pipeline.
  21013. *
  21014. * @type {Map<string,Pipeline>}
  21015. */
  21016. this.caches = new Map();
  21017. /**
  21018. * This dictionary maintains for each shader stage type (vertex,
  21019. * fragment and compute) the programmable stage objects which
  21020. * represent the actual shader code.
  21021. *
  21022. * @type {Object<string,Map<string, ProgrammableStage>>}
  21023. */
  21024. this.programs = {
  21025. vertex: new Map(),
  21026. fragment: new Map(),
  21027. compute: new Map()
  21028. };
  21029. }
  21030. /**
  21031. * Returns a compute pipeline for the given compute node.
  21032. *
  21033. * @param {Node} computeNode - The compute node.
  21034. * @param {Array<BindGroup>} bindings - The bindings.
  21035. * @return {ComputePipeline} The compute pipeline.
  21036. */
  21037. getForCompute( computeNode, bindings ) {
  21038. const { backend } = this;
  21039. const data = this.get( computeNode );
  21040. if ( this._needsComputeUpdate( computeNode ) ) {
  21041. const previousPipeline = data.pipeline;
  21042. if ( previousPipeline ) {
  21043. previousPipeline.usedTimes --;
  21044. previousPipeline.computeProgram.usedTimes --;
  21045. }
  21046. // get shader
  21047. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  21048. // programmable stage
  21049. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  21050. if ( stageCompute === undefined ) {
  21051. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  21052. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  21053. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  21054. backend.createProgram( stageCompute );
  21055. }
  21056. // determine compute pipeline
  21057. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  21058. let pipeline = this.caches.get( cacheKey );
  21059. if ( pipeline === undefined ) {
  21060. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21061. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  21062. }
  21063. // keep track of all used times
  21064. pipeline.usedTimes ++;
  21065. stageCompute.usedTimes ++;
  21066. //
  21067. data.version = computeNode.version;
  21068. data.pipeline = pipeline;
  21069. }
  21070. return data.pipeline;
  21071. }
  21072. /**
  21073. * Returns a render pipeline for the given render object.
  21074. *
  21075. * @param {RenderObject} renderObject - The render object.
  21076. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21077. * @return {RenderPipeline} The render pipeline.
  21078. */
  21079. getForRender( renderObject, promises = null ) {
  21080. const { backend } = this;
  21081. const data = this.get( renderObject );
  21082. if ( this._needsRenderUpdate( renderObject ) ) {
  21083. const previousPipeline = data.pipeline;
  21084. if ( previousPipeline ) {
  21085. previousPipeline.usedTimes --;
  21086. previousPipeline.vertexProgram.usedTimes --;
  21087. previousPipeline.fragmentProgram.usedTimes --;
  21088. }
  21089. // get shader
  21090. const nodeBuilderState = renderObject.getNodeBuilderState();
  21091. const name = renderObject.material ? renderObject.material.name : '';
  21092. // programmable stages
  21093. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  21094. if ( stageVertex === undefined ) {
  21095. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  21096. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  21097. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  21098. backend.createProgram( stageVertex );
  21099. }
  21100. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  21101. if ( stageFragment === undefined ) {
  21102. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  21103. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  21104. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  21105. backend.createProgram( stageFragment );
  21106. }
  21107. // determine render pipeline
  21108. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21109. let pipeline = this.caches.get( cacheKey );
  21110. if ( pipeline === undefined ) {
  21111. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  21112. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  21113. } else {
  21114. renderObject.pipeline = pipeline;
  21115. }
  21116. // keep track of all used times
  21117. pipeline.usedTimes ++;
  21118. stageVertex.usedTimes ++;
  21119. stageFragment.usedTimes ++;
  21120. //
  21121. data.pipeline = pipeline;
  21122. }
  21123. return data.pipeline;
  21124. }
  21125. /**
  21126. * Deletes the pipeline for the given render object.
  21127. *
  21128. * @param {RenderObject} object - The render object.
  21129. * @return {?Object} The deleted dictionary.
  21130. */
  21131. delete( object ) {
  21132. const pipeline = this.get( object ).pipeline;
  21133. if ( pipeline ) {
  21134. // pipeline
  21135. pipeline.usedTimes --;
  21136. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  21137. // programs
  21138. if ( pipeline.isComputePipeline ) {
  21139. pipeline.computeProgram.usedTimes --;
  21140. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  21141. } else {
  21142. pipeline.fragmentProgram.usedTimes --;
  21143. pipeline.vertexProgram.usedTimes --;
  21144. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  21145. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  21146. }
  21147. }
  21148. return super.delete( object );
  21149. }
  21150. /**
  21151. * Frees internal resources.
  21152. */
  21153. dispose() {
  21154. super.dispose();
  21155. this.caches = new Map();
  21156. this.programs = {
  21157. vertex: new Map(),
  21158. fragment: new Map(),
  21159. compute: new Map()
  21160. };
  21161. }
  21162. /**
  21163. * Updates the pipeline for the given render object.
  21164. *
  21165. * @param {RenderObject} renderObject - The render object.
  21166. */
  21167. updateForRender( renderObject ) {
  21168. this.getForRender( renderObject );
  21169. }
  21170. /**
  21171. * Returns a compute pipeline for the given parameters.
  21172. *
  21173. * @private
  21174. * @param {Node} computeNode - The compute node.
  21175. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21176. * @param {string} cacheKey - The cache key.
  21177. * @param {Array<BindGroup>} bindings - The bindings.
  21178. * @return {ComputePipeline} The compute pipeline.
  21179. */
  21180. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21181. // check for existing pipeline
  21182. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21183. let pipeline = this.caches.get( cacheKey );
  21184. if ( pipeline === undefined ) {
  21185. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21186. this.caches.set( cacheKey, pipeline );
  21187. this.backend.createComputePipeline( pipeline, bindings );
  21188. }
  21189. return pipeline;
  21190. }
  21191. /**
  21192. * Returns a render pipeline for the given parameters.
  21193. *
  21194. * @private
  21195. * @param {RenderObject} renderObject - The render object.
  21196. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21197. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21198. * @param {string} cacheKey - The cache key.
  21199. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21200. * @return {ComputePipeline} The compute pipeline.
  21201. */
  21202. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21203. // check for existing pipeline
  21204. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21205. let pipeline = this.caches.get( cacheKey );
  21206. if ( pipeline === undefined ) {
  21207. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21208. this.caches.set( cacheKey, pipeline );
  21209. renderObject.pipeline = pipeline;
  21210. // The `promises` array is `null` by default and only set to an empty array when
  21211. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21212. // pending promises that resolve when the render pipelines are ready for rendering.
  21213. this.backend.createRenderPipeline( renderObject, promises );
  21214. }
  21215. return pipeline;
  21216. }
  21217. /**
  21218. * Computes a cache key representing a compute pipeline.
  21219. *
  21220. * @private
  21221. * @param {Node} computeNode - The compute node.
  21222. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21223. * @return {string} The cache key.
  21224. */
  21225. _getComputeCacheKey( computeNode, stageCompute ) {
  21226. return computeNode.id + ',' + stageCompute.id;
  21227. }
  21228. /**
  21229. * Computes a cache key representing a render pipeline.
  21230. *
  21231. * @private
  21232. * @param {RenderObject} renderObject - The render object.
  21233. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21234. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21235. * @return {string} The cache key.
  21236. */
  21237. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21238. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21239. }
  21240. /**
  21241. * Releases the given pipeline.
  21242. *
  21243. * @private
  21244. * @param {Pipeline} pipeline - The pipeline to release.
  21245. */
  21246. _releasePipeline( pipeline ) {
  21247. this.caches.delete( pipeline.cacheKey );
  21248. }
  21249. /**
  21250. * Releases the shader program.
  21251. *
  21252. * @private
  21253. * @param {Object} program - The shader program to release.
  21254. */
  21255. _releaseProgram( program ) {
  21256. const code = program.code;
  21257. const stage = program.stage;
  21258. this.programs[ stage ].delete( code );
  21259. }
  21260. /**
  21261. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21262. *
  21263. * @private
  21264. * @param {Node} computeNode - The compute node.
  21265. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21266. */
  21267. _needsComputeUpdate( computeNode ) {
  21268. const data = this.get( computeNode );
  21269. return data.pipeline === undefined || data.version !== computeNode.version;
  21270. }
  21271. /**
  21272. * Returns `true` if the render pipeline for the given render object requires an update.
  21273. *
  21274. * @private
  21275. * @param {RenderObject} renderObject - The render object.
  21276. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21277. */
  21278. _needsRenderUpdate( renderObject ) {
  21279. const data = this.get( renderObject );
  21280. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21281. }
  21282. }
  21283. /**
  21284. * This renderer module manages the bindings of the renderer.
  21285. *
  21286. * @private
  21287. * @augments DataMap
  21288. */
  21289. class Bindings extends DataMap {
  21290. /**
  21291. * Constructs a new bindings management component.
  21292. *
  21293. * @param {Backend} backend - The renderer's backend.
  21294. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21295. * @param {Textures} textures - Renderer component for managing textures.
  21296. * @param {Attributes} attributes - Renderer component for managing attributes.
  21297. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21298. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21299. */
  21300. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  21301. super();
  21302. /**
  21303. * The renderer's backend.
  21304. *
  21305. * @type {Backend}
  21306. */
  21307. this.backend = backend;
  21308. /**
  21309. * Renderer component for managing textures.
  21310. *
  21311. * @type {Textures}
  21312. */
  21313. this.textures = textures;
  21314. /**
  21315. * Renderer component for managing pipelines.
  21316. *
  21317. * @type {Pipelines}
  21318. */
  21319. this.pipelines = pipelines;
  21320. /**
  21321. * Renderer component for managing attributes.
  21322. *
  21323. * @type {Attributes}
  21324. */
  21325. this.attributes = attributes;
  21326. /**
  21327. * Renderer component for managing nodes related logic.
  21328. *
  21329. * @type {Nodes}
  21330. */
  21331. this.nodes = nodes;
  21332. /**
  21333. * Renderer component for managing metrics and monitoring data.
  21334. *
  21335. * @type {Info}
  21336. */
  21337. this.info = info;
  21338. this.pipelines.bindings = this; // assign bindings to pipelines
  21339. }
  21340. /**
  21341. * Returns the bind groups for the given render object.
  21342. *
  21343. * @param {RenderObject} renderObject - The render object.
  21344. * @return {Array<BindGroup>} The bind groups.
  21345. */
  21346. getForRender( renderObject ) {
  21347. const bindings = renderObject.getBindings();
  21348. for ( const bindGroup of bindings ) {
  21349. const groupData = this.get( bindGroup );
  21350. if ( groupData.bindGroup === undefined ) {
  21351. // each object defines an array of bindings (ubos, textures, samplers etc.)
  21352. this._init( bindGroup );
  21353. this.backend.createBindings( bindGroup, bindings, 0 );
  21354. groupData.bindGroup = bindGroup;
  21355. }
  21356. }
  21357. return bindings;
  21358. }
  21359. /**
  21360. * Returns the bind groups for the given compute node.
  21361. *
  21362. * @param {Node} computeNode - The compute node.
  21363. * @return {Array<BindGroup>} The bind groups.
  21364. */
  21365. getForCompute( computeNode ) {
  21366. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21367. for ( const bindGroup of bindings ) {
  21368. const groupData = this.get( bindGroup );
  21369. if ( groupData.bindGroup === undefined ) {
  21370. this._init( bindGroup );
  21371. this.backend.createBindings( bindGroup, bindings, 0 );
  21372. groupData.bindGroup = bindGroup;
  21373. }
  21374. }
  21375. return bindings;
  21376. }
  21377. /**
  21378. * Updates the bindings for the given compute node.
  21379. *
  21380. * @param {Node} computeNode - The compute node.
  21381. */
  21382. updateForCompute( computeNode ) {
  21383. this._updateBindings( this.getForCompute( computeNode ) );
  21384. }
  21385. /**
  21386. * Updates the bindings for the given render object.
  21387. *
  21388. * @param {RenderObject} renderObject - The render object.
  21389. */
  21390. updateForRender( renderObject ) {
  21391. this._updateBindings( this.getForRender( renderObject ) );
  21392. }
  21393. /**
  21394. * Deletes the bindings for the given compute node.
  21395. *
  21396. * @param {Node} computeNode - The compute node.
  21397. */
  21398. deleteForCompute( computeNode ) {
  21399. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21400. for ( const bindGroup of bindings ) {
  21401. this.delete( bindGroup );
  21402. }
  21403. }
  21404. /**
  21405. * Deletes the bindings for the given renderObject node.
  21406. *
  21407. * @param {RenderObject} renderObject - The renderObject.
  21408. */
  21409. deleteForRender( renderObject ) {
  21410. const bindings = renderObject.getBindings();
  21411. for ( const bindGroup of bindings ) {
  21412. this.delete( bindGroup );
  21413. }
  21414. }
  21415. /**
  21416. * Updates the given array of bindings.
  21417. *
  21418. * @param {Array<BindGroup>} bindings - The bind groups.
  21419. */
  21420. _updateBindings( bindings ) {
  21421. for ( const bindGroup of bindings ) {
  21422. this._update( bindGroup, bindings );
  21423. }
  21424. }
  21425. /**
  21426. * Initializes the given bind group.
  21427. *
  21428. * @param {BindGroup} bindGroup - The bind group to initialize.
  21429. */
  21430. _init( bindGroup ) {
  21431. for ( const binding of bindGroup.bindings ) {
  21432. if ( binding.isSampledTexture ) {
  21433. this.textures.updateTexture( binding.texture );
  21434. } else if ( binding.isSampler ) {
  21435. this.textures.updateSampler( binding.texture );
  21436. } else if ( binding.isStorageBuffer ) {
  21437. const attribute = binding.attribute;
  21438. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21439. this.attributes.update( attribute, attributeType );
  21440. }
  21441. }
  21442. }
  21443. /**
  21444. * Updates the given bind group.
  21445. *
  21446. * @param {BindGroup} bindGroup - The bind group to update.
  21447. * @param {Array<BindGroup>} bindings - The bind groups.
  21448. */
  21449. _update( bindGroup, bindings ) {
  21450. const { backend } = this;
  21451. let needsBindingsUpdate = false;
  21452. let cacheBindings = true;
  21453. let cacheIndex = 0;
  21454. let version = 0;
  21455. // iterate over all bindings and check if buffer updates or a new binding group is required
  21456. for ( const binding of bindGroup.bindings ) {
  21457. if ( binding.isNodeUniformsGroup ) {
  21458. const updated = this.nodes.updateGroup( binding );
  21459. // every uniforms group is a uniform buffer. So if no update is required,
  21460. // we move one with the next binding. Otherwise the next if block will update the group.
  21461. if ( updated === false ) continue;
  21462. }
  21463. if ( binding.isStorageBuffer ) {
  21464. const attribute = binding.attribute;
  21465. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21466. this.attributes.update( attribute, attributeType );
  21467. }
  21468. if ( binding.isUniformBuffer ) {
  21469. const updated = binding.update();
  21470. if ( updated ) {
  21471. backend.updateBinding( binding );
  21472. }
  21473. } else if ( binding.isSampledTexture ) {
  21474. const updated = binding.update();
  21475. // get the texture data after the update, to sync the texture reference from node
  21476. const texture = binding.texture;
  21477. const texturesTextureData = this.textures.get( texture );
  21478. if ( updated ) {
  21479. // version: update the texture data or create a new one
  21480. this.textures.updateTexture( texture );
  21481. // generation: update the bindings if a new texture has been created
  21482. if ( binding.generation !== texturesTextureData.generation ) {
  21483. binding.generation = texturesTextureData.generation;
  21484. needsBindingsUpdate = true;
  21485. cacheBindings = false;
  21486. }
  21487. }
  21488. const textureData = backend.get( texture );
  21489. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  21490. cacheBindings = false;
  21491. } else {
  21492. cacheIndex = cacheIndex * 10 + texture.id;
  21493. version += texture.version;
  21494. }
  21495. if ( texture.isStorageTexture === true ) {
  21496. const textureData = this.get( texture );
  21497. if ( binding.store === true ) {
  21498. textureData.needsMipmap = true;
  21499. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  21500. this.backend.generateMipmaps( texture );
  21501. textureData.needsMipmap = false;
  21502. }
  21503. }
  21504. } else if ( binding.isSampler ) {
  21505. const updated = binding.update();
  21506. if ( updated ) {
  21507. const samplerKey = this.textures.updateSampler( binding.texture );
  21508. if ( binding.samplerKey !== samplerKey ) {
  21509. binding.samplerKey = samplerKey;
  21510. needsBindingsUpdate = true;
  21511. cacheBindings = false;
  21512. }
  21513. }
  21514. }
  21515. }
  21516. if ( needsBindingsUpdate === true ) {
  21517. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  21518. }
  21519. }
  21520. }
  21521. /**
  21522. * Default sorting function for opaque render items.
  21523. *
  21524. * @private
  21525. * @function
  21526. * @param {Object} a - The first render item.
  21527. * @param {Object} b - The second render item.
  21528. * @return {number} A numeric value which defines the sort order.
  21529. */
  21530. function painterSortStable( a, b ) {
  21531. if ( a.groupOrder !== b.groupOrder ) {
  21532. return a.groupOrder - b.groupOrder;
  21533. } else if ( a.renderOrder !== b.renderOrder ) {
  21534. return a.renderOrder - b.renderOrder;
  21535. } else if ( a.z !== b.z ) {
  21536. return a.z - b.z;
  21537. } else {
  21538. return a.id - b.id;
  21539. }
  21540. }
  21541. /**
  21542. * Default sorting function for transparent render items.
  21543. *
  21544. * @private
  21545. * @function
  21546. * @param {Object} a - The first render item.
  21547. * @param {Object} b - The second render item.
  21548. * @return {number} A numeric value which defines the sort order.
  21549. */
  21550. function reversePainterSortStable( a, b ) {
  21551. if ( a.groupOrder !== b.groupOrder ) {
  21552. return a.groupOrder - b.groupOrder;
  21553. } else if ( a.renderOrder !== b.renderOrder ) {
  21554. return a.renderOrder - b.renderOrder;
  21555. } else if ( a.z !== b.z ) {
  21556. return b.z - a.z;
  21557. } else {
  21558. return a.id - b.id;
  21559. }
  21560. }
  21561. /**
  21562. * Returns `true` if the given transparent material requires a double pass.
  21563. *
  21564. * @private
  21565. * @function
  21566. * @param {Material} material - The transparent material.
  21567. * @return {boolean} Whether the given material requires a double pass or not.
  21568. */
  21569. function needsDoublePass( material ) {
  21570. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  21571. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21572. }
  21573. /**
  21574. * When the renderer analyzes the scene at the beginning of a render call,
  21575. * it stores 3D object for further processing in render lists. Depending on the
  21576. * properties of a 3D objects (like their transformation or material state), the
  21577. * objects are maintained in ordered lists for the actual rendering.
  21578. *
  21579. * Render lists are unique per scene and camera combination.
  21580. *
  21581. * @private
  21582. * @augments Pipeline
  21583. */
  21584. class RenderList {
  21585. /**
  21586. * Constructs a render list.
  21587. *
  21588. * @param {Lighting} lighting - The lighting management component.
  21589. * @param {Scene} scene - The scene.
  21590. * @param {Camera} camera - The camera the scene is rendered with.
  21591. */
  21592. constructor( lighting, scene, camera ) {
  21593. /**
  21594. * 3D objects are transformed into render items and stored in this array.
  21595. *
  21596. * @type {Array<Object>}
  21597. */
  21598. this.renderItems = [];
  21599. /**
  21600. * The current render items index.
  21601. *
  21602. * @type {number}
  21603. * @default 0
  21604. */
  21605. this.renderItemsIndex = 0;
  21606. /**
  21607. * A list with opaque render items.
  21608. *
  21609. * @type {Array<Object>}
  21610. */
  21611. this.opaque = [];
  21612. /**
  21613. * A list with transparent render items which require
  21614. * double pass rendering (e.g. transmissive objects).
  21615. *
  21616. * @type {Array<Object>}
  21617. */
  21618. this.transparentDoublePass = [];
  21619. /**
  21620. * A list with transparent render items.
  21621. *
  21622. * @type {Array<Object>}
  21623. */
  21624. this.transparent = [];
  21625. /**
  21626. * A list with transparent render bundle data.
  21627. *
  21628. * @type {Array<Object>}
  21629. */
  21630. this.bundles = [];
  21631. /**
  21632. * The render list's lights node. This node is later
  21633. * relevant for the actual analytical light nodes which
  21634. * compute the scene's lighting in the shader.
  21635. *
  21636. * @type {LightsNode}
  21637. */
  21638. this.lightsNode = lighting.getNode( scene, camera );
  21639. /**
  21640. * The scene's lights stored in an array. This array
  21641. * is used to setup the lights node.
  21642. *
  21643. * @type {Array<Light>}
  21644. */
  21645. this.lightsArray = [];
  21646. /**
  21647. * The scene.
  21648. *
  21649. * @type {Scene}
  21650. */
  21651. this.scene = scene;
  21652. /**
  21653. * The camera the scene is rendered with.
  21654. *
  21655. * @type {Camera}
  21656. */
  21657. this.camera = camera;
  21658. /**
  21659. * How many objects perform occlusion query tests.
  21660. *
  21661. * @type {number}
  21662. * @default 0
  21663. */
  21664. this.occlusionQueryCount = 0;
  21665. }
  21666. /**
  21667. * This method is called right at the beginning of a render call
  21668. * before the scene is analyzed. It prepares the internal data
  21669. * structures for the upcoming render lists generation.
  21670. *
  21671. * @return {RenderList} A reference to this render list.
  21672. */
  21673. begin() {
  21674. this.renderItemsIndex = 0;
  21675. this.opaque.length = 0;
  21676. this.transparentDoublePass.length = 0;
  21677. this.transparent.length = 0;
  21678. this.bundles.length = 0;
  21679. this.lightsArray.length = 0;
  21680. this.occlusionQueryCount = 0;
  21681. return this;
  21682. }
  21683. /**
  21684. * Returns a render item for the giving render item state. The state is defined
  21685. * by a series of object-related parameters.
  21686. *
  21687. * The method avoids object creation by holding render items and reusing them in
  21688. * subsequent render calls (just with different property values).
  21689. *
  21690. * @param {Object3D} object - The 3D object.
  21691. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21692. * @param {Material} material - The 3D object's material.
  21693. * @param {number} groupOrder - The current group order.
  21694. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21695. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21696. * @param {ClippingContext} clippingContext - The current clipping context.
  21697. * @return {Object} The render item.
  21698. */
  21699. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21700. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21701. if ( renderItem === undefined ) {
  21702. renderItem = {
  21703. id: object.id,
  21704. object: object,
  21705. geometry: geometry,
  21706. material: material,
  21707. groupOrder: groupOrder,
  21708. renderOrder: object.renderOrder,
  21709. z: z,
  21710. group: group,
  21711. clippingContext: clippingContext
  21712. };
  21713. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21714. } else {
  21715. renderItem.id = object.id;
  21716. renderItem.object = object;
  21717. renderItem.geometry = geometry;
  21718. renderItem.material = material;
  21719. renderItem.groupOrder = groupOrder;
  21720. renderItem.renderOrder = object.renderOrder;
  21721. renderItem.z = z;
  21722. renderItem.group = group;
  21723. renderItem.clippingContext = clippingContext;
  21724. }
  21725. this.renderItemsIndex ++;
  21726. return renderItem;
  21727. }
  21728. /**
  21729. * Pushes the given object as a render item to the internal render lists.
  21730. * The selected lists depend on the object properties.
  21731. *
  21732. * @param {Object3D} object - The 3D object.
  21733. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21734. * @param {Material} material - The 3D object's material.
  21735. * @param {number} groupOrder - The current group order.
  21736. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21737. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21738. * @param {ClippingContext} clippingContext - The current clipping context.
  21739. */
  21740. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21741. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21742. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21743. if ( material.transparent === true || material.transmission > 0 ) {
  21744. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21745. this.transparent.push( renderItem );
  21746. } else {
  21747. this.opaque.push( renderItem );
  21748. }
  21749. }
  21750. /**
  21751. * Inserts the given object as a render item at the start of the internal render lists.
  21752. * The selected lists depend on the object properties.
  21753. *
  21754. * @param {Object3D} object - The 3D object.
  21755. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21756. * @param {Material} material - The 3D object's material.
  21757. * @param {number} groupOrder - The current group order.
  21758. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21759. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21760. * @param {ClippingContext} clippingContext - The current clipping context.
  21761. */
  21762. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21763. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21764. if ( material.transparent === true || material.transmission > 0 ) {
  21765. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21766. this.transparent.unshift( renderItem );
  21767. } else {
  21768. this.opaque.unshift( renderItem );
  21769. }
  21770. }
  21771. /**
  21772. * Pushes render bundle group data into the render list.
  21773. *
  21774. * @param {Object} group - Bundle group data.
  21775. */
  21776. pushBundle( group ) {
  21777. this.bundles.push( group );
  21778. }
  21779. /**
  21780. * Pushes a light into the render list.
  21781. *
  21782. * @param {Light} light - The light.
  21783. */
  21784. pushLight( light ) {
  21785. this.lightsArray.push( light );
  21786. }
  21787. /**
  21788. * Sorts the internal render lists.
  21789. *
  21790. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  21791. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  21792. */
  21793. sort( customOpaqueSort, customTransparentSort ) {
  21794. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  21795. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  21796. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  21797. }
  21798. /**
  21799. * This method performs finalizing tasks right after the render lists
  21800. * have been generated.
  21801. */
  21802. finish() {
  21803. // update lights
  21804. this.lightsNode.setLights( this.lightsArray );
  21805. // Clear references from inactive renderItems in the list
  21806. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  21807. const renderItem = this.renderItems[ i ];
  21808. if ( renderItem.id === null ) break;
  21809. renderItem.id = null;
  21810. renderItem.object = null;
  21811. renderItem.geometry = null;
  21812. renderItem.material = null;
  21813. renderItem.groupOrder = null;
  21814. renderItem.renderOrder = null;
  21815. renderItem.z = null;
  21816. renderItem.group = null;
  21817. renderItem.clippingContext = null;
  21818. }
  21819. }
  21820. }
  21821. const _chainKeys$4 = [];
  21822. /**
  21823. * This renderer module manages the render lists which are unique
  21824. * per scene and camera combination.
  21825. *
  21826. * @private
  21827. */
  21828. class RenderLists {
  21829. /**
  21830. * Constructs a render lists management component.
  21831. *
  21832. * @param {Lighting} lighting - The lighting management component.
  21833. */
  21834. constructor( lighting ) {
  21835. /**
  21836. * The lighting management component.
  21837. *
  21838. * @type {Lighting}
  21839. */
  21840. this.lighting = lighting;
  21841. /**
  21842. * The internal chain map which holds the render lists.
  21843. *
  21844. * @type {ChainMap}
  21845. */
  21846. this.lists = new ChainMap();
  21847. }
  21848. /**
  21849. * Returns a render list for the given scene and camera.
  21850. *
  21851. * @param {Scene} scene - The scene.
  21852. * @param {Camera} camera - The camera.
  21853. * @return {RenderList} The render list.
  21854. */
  21855. get( scene, camera ) {
  21856. const lists = this.lists;
  21857. _chainKeys$4[ 0 ] = scene;
  21858. _chainKeys$4[ 1 ] = camera;
  21859. let list = lists.get( _chainKeys$4 );
  21860. if ( list === undefined ) {
  21861. list = new RenderList( this.lighting, scene, camera );
  21862. lists.set( _chainKeys$4, list );
  21863. }
  21864. _chainKeys$4.length = 0;
  21865. return list;
  21866. }
  21867. /**
  21868. * Frees all internal resources.
  21869. */
  21870. dispose() {
  21871. this.lists = new ChainMap();
  21872. }
  21873. }
  21874. let _id$7 = 0;
  21875. /**
  21876. * Any render or compute command is executed in a specific context that defines
  21877. * the state of the renderer and its backend. Typical examples for such context
  21878. * data are the current clear values or data from the active framebuffer. This
  21879. * module is used to represent these contexts as objects.
  21880. *
  21881. * @private
  21882. */
  21883. class RenderContext {
  21884. /**
  21885. * Constructs a new render context.
  21886. */
  21887. constructor() {
  21888. /**
  21889. * The context's ID.
  21890. *
  21891. * @type {number}
  21892. */
  21893. this.id = _id$7 ++;
  21894. /**
  21895. * Whether the current active framebuffer has a color attachment.
  21896. *
  21897. * @type {boolean}
  21898. * @default true
  21899. */
  21900. this.color = true;
  21901. /**
  21902. * Whether the color attachment should be cleared or not.
  21903. *
  21904. * @type {boolean}
  21905. * @default true
  21906. */
  21907. this.clearColor = true;
  21908. /**
  21909. * The clear color value.
  21910. *
  21911. * @type {Object}
  21912. * @default true
  21913. */
  21914. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  21915. /**
  21916. * Whether the current active framebuffer has a depth attachment.
  21917. *
  21918. * @type {boolean}
  21919. * @default true
  21920. */
  21921. this.depth = true;
  21922. /**
  21923. * Whether the depth attachment should be cleared or not.
  21924. *
  21925. * @type {boolean}
  21926. * @default true
  21927. */
  21928. this.clearDepth = true;
  21929. /**
  21930. * The clear depth value.
  21931. *
  21932. * @type {number}
  21933. * @default 1
  21934. */
  21935. this.clearDepthValue = 1;
  21936. /**
  21937. * Whether the current active framebuffer has a stencil attachment.
  21938. *
  21939. * @type {boolean}
  21940. * @default false
  21941. */
  21942. this.stencil = false;
  21943. /**
  21944. * Whether the stencil attachment should be cleared or not.
  21945. *
  21946. * @type {boolean}
  21947. * @default true
  21948. */
  21949. this.clearStencil = true;
  21950. /**
  21951. * The clear stencil value.
  21952. *
  21953. * @type {number}
  21954. * @default 1
  21955. */
  21956. this.clearStencilValue = 1;
  21957. /**
  21958. * By default the viewport encloses the entire framebuffer If a smaller
  21959. * viewport is manually defined, this property is to `true` by the renderer.
  21960. *
  21961. * @type {boolean}
  21962. * @default false
  21963. */
  21964. this.viewport = false;
  21965. /**
  21966. * The viewport value. This value is in physical pixels meaning it incorporates
  21967. * the renderer's pixel ratio. The viewport property of render targets or
  21968. * the renderer is in logical pixels.
  21969. *
  21970. * @type {Vector4}
  21971. */
  21972. this.viewportValue = new Vector4();
  21973. /**
  21974. * When the scissor test is active and scissor rectangle smaller than the
  21975. * framebuffers dimensions, this property is to `true` by the renderer.
  21976. *
  21977. * @type {boolean}
  21978. * @default false
  21979. */
  21980. this.scissor = false;
  21981. /**
  21982. * The scissor rectangle.
  21983. *
  21984. * @type {Vector4}
  21985. */
  21986. this.scissorValue = new Vector4();
  21987. /**
  21988. * The active render target.
  21989. *
  21990. * @type {?RenderTarget}
  21991. * @default null
  21992. */
  21993. this.renderTarget = null;
  21994. /**
  21995. * The textures of the active render target.
  21996. * `null` when no render target is set.
  21997. *
  21998. * @type {?Array<Texture>}
  21999. * @default null
  22000. */
  22001. this.textures = null;
  22002. /**
  22003. * The depth texture of the active render target.
  22004. * `null` when no render target is set.
  22005. *
  22006. * @type {?DepthTexture}
  22007. * @default null
  22008. */
  22009. this.depthTexture = null;
  22010. /**
  22011. * The active cube face.
  22012. *
  22013. * @type {number}
  22014. * @default 0
  22015. */
  22016. this.activeCubeFace = 0;
  22017. /**
  22018. * The active mipmap level.
  22019. *
  22020. * @type {number}
  22021. * @default 0
  22022. */
  22023. this.activeMipmapLevel = 0;
  22024. /**
  22025. * The number of MSAA samples. This value is always `1` when
  22026. * MSAA isn't used.
  22027. *
  22028. * @type {number}
  22029. * @default 1
  22030. */
  22031. this.sampleCount = 1;
  22032. /**
  22033. * The active render target's width in physical pixels.
  22034. *
  22035. * @type {number}
  22036. * @default 0
  22037. */
  22038. this.width = 0;
  22039. /**
  22040. * The active render target's height in physical pixels.
  22041. *
  22042. * @type {number}
  22043. * @default 0
  22044. */
  22045. this.height = 0;
  22046. /**
  22047. * The occlusion query count.
  22048. *
  22049. * @type {number}
  22050. * @default 0
  22051. */
  22052. this.occlusionQueryCount = 0;
  22053. /**
  22054. * The current clipping context.
  22055. *
  22056. * @type {?ClippingContext}
  22057. * @default null
  22058. */
  22059. this.clippingContext = null;
  22060. /**
  22061. * This flag can be used for type testing.
  22062. *
  22063. * @type {boolean}
  22064. * @readonly
  22065. * @default true
  22066. */
  22067. this.isRenderContext = true;
  22068. }
  22069. /**
  22070. * Returns the cache key of this render context.
  22071. *
  22072. * @return {number} The cache key.
  22073. */
  22074. getCacheKey() {
  22075. return getCacheKey( this );
  22076. }
  22077. }
  22078. /**
  22079. * Computes a cache key for the given render context. This key
  22080. * should identify the render target state so it is possible to
  22081. * configure the correct attachments in the respective backend.
  22082. *
  22083. * @param {RenderContext} renderContext - The render context.
  22084. * @return {number} The cache key.
  22085. */
  22086. function getCacheKey( renderContext ) {
  22087. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  22088. const values = [ activeCubeFace, activeMipmapLevel ];
  22089. for ( const texture of textures ) {
  22090. values.push( texture.id );
  22091. }
  22092. return hashArray( values );
  22093. }
  22094. const _chainKeys$3 = [];
  22095. const _defaultScene = /*@__PURE__*/ new Scene();
  22096. const _defaultCamera = /*@__PURE__*/ new Camera();
  22097. /**
  22098. * This module manages the render contexts of the renderer.
  22099. *
  22100. * @private
  22101. */
  22102. class RenderContexts {
  22103. /**
  22104. * Constructs a new render context management component.
  22105. */
  22106. constructor() {
  22107. /**
  22108. * A dictionary that manages render contexts in chain maps
  22109. * for each attachment state.
  22110. *
  22111. * @type {Object<string,ChainMap>}
  22112. */
  22113. this.chainMaps = {};
  22114. }
  22115. /**
  22116. * Returns a render context for the given scene, camera and render target.
  22117. *
  22118. * @param {Scene} scene - The scene.
  22119. * @param {Camera} camera - The camera that is used to render the scene.
  22120. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22121. * @return {RenderContext} The render context.
  22122. */
  22123. get( scene, camera, renderTarget = null ) {
  22124. _chainKeys$3[ 0 ] = scene;
  22125. _chainKeys$3[ 1 ] = camera;
  22126. let attachmentState;
  22127. if ( renderTarget === null ) {
  22128. attachmentState = 'default';
  22129. } else {
  22130. const format = renderTarget.texture.format;
  22131. const count = renderTarget.textures.length;
  22132. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  22133. }
  22134. const chainMap = this._getChainMap( attachmentState );
  22135. let renderState = chainMap.get( _chainKeys$3 );
  22136. if ( renderState === undefined ) {
  22137. renderState = new RenderContext();
  22138. chainMap.set( _chainKeys$3, renderState );
  22139. }
  22140. _chainKeys$3.length = 0;
  22141. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22142. return renderState;
  22143. }
  22144. /**
  22145. * Returns a render context intended for clear operations.
  22146. *
  22147. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  22148. * @return {RenderContext} The render context.
  22149. */
  22150. getForClear( renderTarget = null ) {
  22151. return this.get( _defaultScene, _defaultCamera, renderTarget );
  22152. }
  22153. /**
  22154. * Returns a chain map for the given attachment state.
  22155. *
  22156. * @private
  22157. * @param {string} attachmentState - The attachment state.
  22158. * @return {ChainMap} The chain map.
  22159. */
  22160. _getChainMap( attachmentState ) {
  22161. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  22162. }
  22163. /**
  22164. * Frees internal resources.
  22165. */
  22166. dispose() {
  22167. this.chainMaps = {};
  22168. }
  22169. }
  22170. const _size$3 = /*@__PURE__*/ new Vector3();
  22171. /**
  22172. * This module manages the textures of the renderer.
  22173. *
  22174. * @private
  22175. * @augments DataMap
  22176. */
  22177. class Textures extends DataMap {
  22178. /**
  22179. * Constructs a new texture management component.
  22180. *
  22181. * @param {Renderer} renderer - The renderer.
  22182. * @param {Backend} backend - The renderer's backend.
  22183. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  22184. */
  22185. constructor( renderer, backend, info ) {
  22186. super();
  22187. /**
  22188. * The renderer.
  22189. *
  22190. * @type {Renderer}
  22191. */
  22192. this.renderer = renderer;
  22193. /**
  22194. * The backend.
  22195. *
  22196. * @type {Backend}
  22197. */
  22198. this.backend = backend;
  22199. /**
  22200. * Renderer component for managing metrics and monitoring data.
  22201. *
  22202. * @type {Info}
  22203. */
  22204. this.info = info;
  22205. }
  22206. /**
  22207. * Updates the given render target. Based on the given render target configuration,
  22208. * it updates the texture states representing the attachments of the framebuffer.
  22209. *
  22210. * @param {RenderTarget} renderTarget - The render target to update.
  22211. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22212. */
  22213. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22214. const renderTargetData = this.get( renderTarget );
  22215. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22216. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22217. const textures = renderTarget.textures;
  22218. const size = this.getSize( textures[ 0 ] );
  22219. const mipWidth = size.width >> activeMipmapLevel;
  22220. const mipHeight = size.height >> activeMipmapLevel;
  22221. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22222. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22223. let textureNeedsUpdate = false;
  22224. if ( depthTexture === undefined && useDepthTexture ) {
  22225. depthTexture = new DepthTexture();
  22226. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  22227. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  22228. depthTexture.image.width = mipWidth;
  22229. depthTexture.image.height = mipHeight;
  22230. depthTexture.image.depth = size.depth;
  22231. depthTexture.renderTarget = renderTarget;
  22232. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22233. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22234. }
  22235. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22236. textureNeedsUpdate = true;
  22237. if ( depthTexture ) {
  22238. depthTexture.needsUpdate = true;
  22239. depthTexture.image.width = mipWidth;
  22240. depthTexture.image.height = mipHeight;
  22241. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22242. }
  22243. }
  22244. renderTargetData.width = size.width;
  22245. renderTargetData.height = size.height;
  22246. renderTargetData.textures = textures;
  22247. renderTargetData.depthTexture = depthTexture || null;
  22248. renderTargetData.depth = renderTarget.depthBuffer;
  22249. renderTargetData.stencil = renderTarget.stencilBuffer;
  22250. renderTargetData.renderTarget = renderTarget;
  22251. if ( renderTargetData.sampleCount !== sampleCount ) {
  22252. textureNeedsUpdate = true;
  22253. if ( depthTexture ) {
  22254. depthTexture.needsUpdate = true;
  22255. }
  22256. renderTargetData.sampleCount = sampleCount;
  22257. }
  22258. //
  22259. const options = { sampleCount };
  22260. // XR render targets require no texture updates
  22261. if ( renderTarget.isXRRenderTarget !== true ) {
  22262. for ( let i = 0; i < textures.length; i ++ ) {
  22263. const texture = textures[ i ];
  22264. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22265. this.updateTexture( texture, options );
  22266. }
  22267. if ( depthTexture ) {
  22268. this.updateTexture( depthTexture, options );
  22269. }
  22270. }
  22271. // dispose handler
  22272. if ( renderTargetData.initialized !== true ) {
  22273. renderTargetData.initialized = true;
  22274. // dispose
  22275. const onDispose = () => {
  22276. renderTarget.removeEventListener( 'dispose', onDispose );
  22277. for ( let i = 0; i < textures.length; i ++ ) {
  22278. this._destroyTexture( textures[ i ] );
  22279. }
  22280. if ( depthTexture ) {
  22281. this._destroyTexture( depthTexture );
  22282. }
  22283. this.delete( renderTarget );
  22284. this.backend.delete( renderTarget );
  22285. };
  22286. renderTarget.addEventListener( 'dispose', onDispose );
  22287. }
  22288. }
  22289. /**
  22290. * Updates the given texture. Depending on the texture state, this method
  22291. * triggers the upload of texture data to the GPU memory. If the texture data are
  22292. * not yet ready for the upload, it uses default texture data for as a placeholder.
  22293. *
  22294. * @param {Texture} texture - The texture to update.
  22295. * @param {Object} [options={}] - The options.
  22296. */
  22297. updateTexture( texture, options = {} ) {
  22298. const textureData = this.get( texture );
  22299. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  22300. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  22301. const backend = this.backend;
  22302. if ( isRenderTarget && textureData.initialized === true ) {
  22303. // it's an update
  22304. backend.destroyTexture( texture );
  22305. }
  22306. //
  22307. if ( texture.isFramebufferTexture ) {
  22308. const renderTarget = this.renderer.getRenderTarget();
  22309. if ( renderTarget ) {
  22310. texture.type = renderTarget.texture.type;
  22311. } else {
  22312. texture.type = UnsignedByteType;
  22313. }
  22314. }
  22315. //
  22316. const { width, height, depth } = this.getSize( texture );
  22317. options.width = width;
  22318. options.height = height;
  22319. options.depth = depth;
  22320. options.needsMipmaps = this.needsMipmaps( texture );
  22321. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  22322. // TODO: Uniformly handle mipmap definitions
  22323. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  22324. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  22325. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  22326. //
  22327. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  22328. backend.createTexture( texture, options );
  22329. textureData.generation = texture.version;
  22330. } else {
  22331. if ( texture.version > 0 ) {
  22332. const image = texture.image;
  22333. if ( image === undefined ) {
  22334. warn( 'Renderer: Texture marked for update but image is undefined.' );
  22335. } else if ( image.complete === false ) {
  22336. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  22337. } else {
  22338. if ( texture.images ) {
  22339. const images = [];
  22340. for ( const image of texture.images ) {
  22341. images.push( image );
  22342. }
  22343. options.images = images;
  22344. } else {
  22345. options.image = image;
  22346. }
  22347. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  22348. backend.createTexture( texture, options );
  22349. textureData.isDefaultTexture = false;
  22350. textureData.generation = texture.version;
  22351. }
  22352. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  22353. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  22354. if ( texture.onUpdate ) texture.onUpdate( texture );
  22355. }
  22356. } else {
  22357. // async update
  22358. backend.createDefaultTexture( texture );
  22359. textureData.isDefaultTexture = true;
  22360. textureData.generation = texture.version;
  22361. }
  22362. }
  22363. // dispose handler
  22364. if ( textureData.initialized !== true ) {
  22365. textureData.initialized = true;
  22366. textureData.generation = texture.version;
  22367. //
  22368. this.info.memory.textures ++;
  22369. //
  22370. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  22371. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  22372. }
  22373. // dispose
  22374. const onDispose = () => {
  22375. texture.removeEventListener( 'dispose', onDispose );
  22376. this._destroyTexture( texture );
  22377. };
  22378. texture.addEventListener( 'dispose', onDispose );
  22379. }
  22380. //
  22381. textureData.version = texture.version;
  22382. }
  22383. /**
  22384. * Updates the sampler for the given texture. This method has no effect
  22385. * for the WebGL backend since it has no concept of samplers. Texture
  22386. * parameters are configured with the `texParameter()` command for each
  22387. * texture.
  22388. *
  22389. * In WebGPU, samplers are objects like textures and it's possible to share
  22390. * them when the texture parameters match.
  22391. *
  22392. * @param {Texture} texture - The texture to update the sampler for.
  22393. * @return {string} The current sampler key.
  22394. */
  22395. updateSampler( texture ) {
  22396. return this.backend.updateSampler( texture );
  22397. }
  22398. /**
  22399. * Computes the size of the given texture and writes the result
  22400. * into the target vector. This vector is also returned by the
  22401. * method.
  22402. *
  22403. * If no texture data are available for the compute yet, the method
  22404. * returns default size values.
  22405. *
  22406. * @param {Texture} texture - The texture to compute the size for.
  22407. * @param {Vector3} target - The target vector.
  22408. * @return {Vector3} The target vector.
  22409. */
  22410. getSize( texture, target = _size$3 ) {
  22411. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22412. if ( image ) {
  22413. if ( image.image !== undefined ) image = image.image;
  22414. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22415. target.width = image.videoWidth || 1;
  22416. target.height = image.videoHeight || 1;
  22417. target.depth = 1;
  22418. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  22419. target.width = image.displayWidth || 1;
  22420. target.height = image.displayHeight || 1;
  22421. target.depth = 1;
  22422. } else {
  22423. target.width = image.width || 1;
  22424. target.height = image.height || 1;
  22425. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22426. }
  22427. } else {
  22428. target.width = target.height = target.depth = 1;
  22429. }
  22430. return target;
  22431. }
  22432. /**
  22433. * Computes the number of mipmap levels for the given texture.
  22434. *
  22435. * @param {Texture} texture - The texture.
  22436. * @param {number} width - The texture's width.
  22437. * @param {number} height - The texture's height.
  22438. * @return {number} The number of mipmap levels.
  22439. */
  22440. getMipLevels( texture, width, height ) {
  22441. let mipLevelCount;
  22442. if ( texture.mipmaps.length > 0 ) {
  22443. mipLevelCount = texture.mipmaps.length;
  22444. } else {
  22445. if ( texture.isCompressedTexture === true ) {
  22446. // it is not possible to compute mipmaps for compressed textures. So
  22447. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22448. // level of 1
  22449. mipLevelCount = 1;
  22450. } else {
  22451. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22452. }
  22453. }
  22454. return mipLevelCount;
  22455. }
  22456. /**
  22457. * Returns `true` if the given texture makes use of mipmapping.
  22458. *
  22459. * @param {Texture} texture - The texture.
  22460. * @return {boolean} Whether mipmaps are required or not.
  22461. */
  22462. needsMipmaps( texture ) {
  22463. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  22464. }
  22465. /**
  22466. * Frees internal resource when the given texture isn't
  22467. * required anymore.
  22468. *
  22469. * @param {Texture} texture - The texture to destroy.
  22470. */
  22471. _destroyTexture( texture ) {
  22472. if ( this.has( texture ) === true ) {
  22473. // if a texture is not ready for use, it falls back to a default texture so it's possible
  22474. // to use it for rendering. If a texture in this state is disposed, it's important to
  22475. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  22476. // other textures.
  22477. const isDefaultTexture = this.get( texture ).isDefaultTexture;
  22478. this.backend.destroyTexture( texture, isDefaultTexture );
  22479. this.delete( texture );
  22480. this.info.memory.textures --;
  22481. }
  22482. }
  22483. }
  22484. /**
  22485. * A four-component version of {@link Color} which is internally
  22486. * used by the renderer to represents clear color with alpha as
  22487. * one object.
  22488. *
  22489. * @private
  22490. * @augments Color
  22491. */
  22492. class Color4 extends Color {
  22493. /**
  22494. * Constructs a new four-component color.
  22495. * You can also pass a single THREE.Color, hex or
  22496. * string argument to this constructor.
  22497. *
  22498. * @param {number|string} [r=1] - The red value.
  22499. * @param {number} [g=1] - The green value.
  22500. * @param {number} [b=1] - The blue value.
  22501. * @param {number} [a=1] - The alpha value.
  22502. */
  22503. constructor( r, g, b, a = 1 ) {
  22504. super( r, g, b );
  22505. this.a = a;
  22506. }
  22507. /**
  22508. * Overwrites the default to honor alpha.
  22509. * You can also pass a single THREE.Color, hex or
  22510. * string argument to this method.
  22511. *
  22512. * @param {number|string|Color} r - The red value.
  22513. * @param {number} [g] - The green value.
  22514. * @param {number} [b] - The blue value.
  22515. * @param {number} [a=1] - The alpha value.
  22516. * @return {Color4} A reference to this object.
  22517. */
  22518. set( r, g, b, a = 1 ) {
  22519. this.a = a;
  22520. return super.set( r, g, b );
  22521. }
  22522. /**
  22523. * Overwrites the default to honor alpha.
  22524. *
  22525. * @param {Color4} color - The color to copy.
  22526. * @return {Color4} A reference to this object.
  22527. */
  22528. copy( color ) {
  22529. if ( color.a !== undefined ) this.a = color.a;
  22530. return super.copy( color );
  22531. }
  22532. /**
  22533. * Overwrites the default to honor alpha.
  22534. *
  22535. * @return {Color4} The cloned color.
  22536. */
  22537. clone() {
  22538. return new this.constructor( this.r, this.g, this.b, this.a );
  22539. }
  22540. }
  22541. /**
  22542. * Special version of {@link PropertyNode} which is used for parameters.
  22543. *
  22544. * @augments PropertyNode
  22545. */
  22546. class ParameterNode extends PropertyNode {
  22547. static get type() {
  22548. return 'ParameterNode';
  22549. }
  22550. /**
  22551. * Constructs a new parameter node.
  22552. *
  22553. * @param {string} nodeType - The type of the node.
  22554. * @param {?string} [name=null] - The name of the parameter in the shader.
  22555. */
  22556. constructor( nodeType, name = null ) {
  22557. super( nodeType, name );
  22558. /**
  22559. * This flag can be used for type testing.
  22560. *
  22561. * @type {boolean}
  22562. * @readonly
  22563. * @default true
  22564. */
  22565. this.isParameterNode = true;
  22566. }
  22567. /**
  22568. * Gets the type of a member variable in the parameter node.
  22569. *
  22570. * @param {NodeBuilder} builder - The node builder.
  22571. * @param {string} name - The name of the member variable.
  22572. * @returns {string}
  22573. */
  22574. getMemberType( builder, name ) {
  22575. const type = this.getNodeType( builder );
  22576. const struct = builder.getStructTypeNode( type );
  22577. let memberType;
  22578. if ( struct !== null ) {
  22579. memberType = struct.getMemberType( builder, name );
  22580. } else {
  22581. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  22582. memberType = 'float';
  22583. }
  22584. return memberType;
  22585. }
  22586. getHash() {
  22587. return this.uuid;
  22588. }
  22589. generate() {
  22590. return this.name;
  22591. }
  22592. }
  22593. /**
  22594. * TSL function for creating a parameter node.
  22595. *
  22596. * @tsl
  22597. * @function
  22598. * @param {string} type - The type of the node.
  22599. * @param {?string} name - The name of the parameter in the shader.
  22600. * @returns {ParameterNode}
  22601. */
  22602. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  22603. /**
  22604. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  22605. * They are usually needed in cases like `If`, `Else`.
  22606. *
  22607. * @augments Node
  22608. */
  22609. class StackNode extends Node {
  22610. static get type() {
  22611. return 'StackNode';
  22612. }
  22613. /**
  22614. * Constructs a new stack node.
  22615. *
  22616. * @param {?StackNode} [parent=null] - The parent stack node.
  22617. */
  22618. constructor( parent = null ) {
  22619. super();
  22620. /**
  22621. * List of nodes.
  22622. *
  22623. * @type {Array<Node>}
  22624. */
  22625. this.nodes = [];
  22626. /**
  22627. * The output node.
  22628. *
  22629. * @type {?Node}
  22630. * @default null
  22631. */
  22632. this.outputNode = null;
  22633. /**
  22634. * The parent stack node.
  22635. *
  22636. * @type {?StackNode}
  22637. * @default null
  22638. */
  22639. this.parent = parent;
  22640. /**
  22641. * The current conditional node.
  22642. *
  22643. * @private
  22644. * @type {ConditionalNode}
  22645. * @default null
  22646. */
  22647. this._currentCond = null;
  22648. /**
  22649. * The expression node. Only
  22650. * relevant for Switch/Case.
  22651. *
  22652. * @private
  22653. * @type {Node}
  22654. * @default null
  22655. */
  22656. this._expressionNode = null;
  22657. /**
  22658. * This flag can be used for type testing.
  22659. *
  22660. * @type {boolean}
  22661. * @readonly
  22662. * @default true
  22663. */
  22664. this.isStackNode = true;
  22665. }
  22666. getNodeType( builder ) {
  22667. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  22668. }
  22669. getMemberType( builder, name ) {
  22670. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  22671. }
  22672. /**
  22673. * Adds a node to this stack.
  22674. *
  22675. * @param {Node} node - The node to add.
  22676. * @return {StackNode} A reference to this stack node.
  22677. */
  22678. add( node ) {
  22679. if ( node.isNode !== true ) {
  22680. error( 'TSL: Invalid node added to stack.' );
  22681. return this;
  22682. }
  22683. this.nodes.push( node );
  22684. return this;
  22685. }
  22686. /**
  22687. * Represent an `if` statement in TSL.
  22688. *
  22689. * @param {Node} boolNode - Represents the condition.
  22690. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22691. * @return {StackNode} A reference to this stack node.
  22692. */
  22693. If( boolNode, method ) {
  22694. const methodNode = new ShaderNode( method );
  22695. this._currentCond = select( boolNode, methodNode );
  22696. return this.add( this._currentCond );
  22697. }
  22698. /**
  22699. * Represent an `elseif` statement in TSL.
  22700. *
  22701. * @param {Node} boolNode - Represents the condition.
  22702. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22703. * @return {StackNode} A reference to this stack node.
  22704. */
  22705. ElseIf( boolNode, method ) {
  22706. const methodNode = new ShaderNode( method );
  22707. const ifNode = select( boolNode, methodNode );
  22708. this._currentCond.elseNode = ifNode;
  22709. this._currentCond = ifNode;
  22710. return this;
  22711. }
  22712. /**
  22713. * Represent an `else` statement in TSL.
  22714. *
  22715. * @param {Function} method - TSL code which is executed in the `else` case.
  22716. * @return {StackNode} A reference to this stack node.
  22717. */
  22718. Else( method ) {
  22719. this._currentCond.elseNode = new ShaderNode( method );
  22720. return this;
  22721. }
  22722. /**
  22723. * Represents a `switch` statement in TSL.
  22724. *
  22725. * @param {any} expression - Represents the expression.
  22726. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22727. * @return {StackNode} A reference to this stack node.
  22728. */
  22729. Switch( expression ) {
  22730. this._expressionNode = nodeObject( expression );
  22731. return this;
  22732. }
  22733. /**
  22734. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22735. * The last parameter must be the callback method that should be executed in the `true` case.
  22736. *
  22737. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22738. * @return {StackNode} A reference to this stack node.
  22739. */
  22740. Case( ...params ) {
  22741. const caseNodes = [];
  22742. // extract case nodes from the parameter list
  22743. if ( params.length >= 2 ) {
  22744. for ( let i = 0; i < params.length - 1; i ++ ) {
  22745. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22746. }
  22747. } else {
  22748. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22749. }
  22750. // extract method
  22751. const method = params[ params.length - 1 ];
  22752. const methodNode = new ShaderNode( method );
  22753. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22754. let caseNode = caseNodes[ 0 ];
  22755. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22756. caseNode = caseNode.or( caseNodes[ i ] );
  22757. }
  22758. // build condition
  22759. const condNode = select( caseNode, methodNode );
  22760. if ( this._currentCond === null ) {
  22761. this._currentCond = condNode;
  22762. return this.add( this._currentCond );
  22763. } else {
  22764. this._currentCond.elseNode = condNode;
  22765. this._currentCond = condNode;
  22766. return this;
  22767. }
  22768. }
  22769. /**
  22770. * Represents the default code block of a Switch/Case statement.
  22771. *
  22772. * @param {Function} method - TSL code which is executed in the `else` case.
  22773. * @return {StackNode} A reference to this stack node.
  22774. */
  22775. Default( method ) {
  22776. this.Else( method );
  22777. return this;
  22778. }
  22779. setup( builder ) {
  22780. const nodeProperties = builder.getNodeProperties( this );
  22781. let index = 0;
  22782. for ( const childNode of this.getChildren() ) {
  22783. if ( childNode.isVarNode && childNode.intent === true ) {
  22784. const properties = builder.getNodeProperties( childNode );
  22785. if ( properties.assign !== true ) {
  22786. continue;
  22787. }
  22788. }
  22789. nodeProperties[ 'node' + index ++ ] = childNode;
  22790. }
  22791. // return a outputNode if exists or null
  22792. return nodeProperties.outputNode || null;
  22793. }
  22794. get hasOutput() {
  22795. return this.outputNode && this.outputNode.isNode;
  22796. }
  22797. build( builder, ...params ) {
  22798. const previousBuildStack = builder.currentStack;
  22799. const previousStack = getCurrentStack();
  22800. setCurrentStack( this );
  22801. builder.currentStack = this;
  22802. const buildStage = builder.buildStage;
  22803. for ( const node of this.nodes ) {
  22804. if ( node.isVarNode && node.intent === true ) {
  22805. const properties = builder.getNodeProperties( node );
  22806. if ( properties.assign !== true ) {
  22807. continue;
  22808. }
  22809. }
  22810. if ( buildStage === 'setup' ) {
  22811. node.build( builder );
  22812. } else if ( buildStage === 'analyze' ) {
  22813. node.build( builder, this );
  22814. } else if ( buildStage === 'generate' ) {
  22815. const stages = builder.getDataFromNode( node, 'any' ).stages;
  22816. const parents = stages && stages[ builder.shaderStage ];
  22817. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  22818. continue; // skip var nodes that are only used in .toVarying()
  22819. }
  22820. node.build( builder, 'void' );
  22821. }
  22822. }
  22823. //
  22824. let result;
  22825. if ( this.hasOutput ) {
  22826. result = this.outputNode.build( builder, ...params );
  22827. } else {
  22828. result = super.build( builder, ...params );
  22829. }
  22830. setCurrentStack( previousStack );
  22831. builder.currentStack = previousBuildStack;
  22832. return result;
  22833. }
  22834. }
  22835. /**
  22836. * TSL function for creating a stack node.
  22837. *
  22838. * @tsl
  22839. * @function
  22840. * @param {?StackNode} [parent=null] - The parent stack node.
  22841. * @returns {StackNode}
  22842. */
  22843. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  22844. /**
  22845. * Generates a layout for struct members.
  22846. * This function takes an object representing struct members and returns an array of member layouts.
  22847. * Each member layout includes the member's name, type, and whether it is atomic.
  22848. *
  22849. * @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.
  22850. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  22851. */
  22852. function getMembersLayout( members ) {
  22853. return Object.entries( members ).map( ( [ name, value ] ) => {
  22854. if ( typeof value === 'string' ) {
  22855. return { name, type: value, atomic: false };
  22856. }
  22857. return { name, type: value.type, atomic: value.atomic || false };
  22858. } );
  22859. }
  22860. /**
  22861. * Represents a struct type node in the node-based system.
  22862. * This class is used to define and manage the layout and types of struct members.
  22863. * It extends the base Node class and provides methods to get the length of the struct,
  22864. * retrieve member types, and generate the struct type for a builder.
  22865. *
  22866. * @augments Node
  22867. */
  22868. class StructTypeNode extends Node {
  22869. static get type() {
  22870. return 'StructTypeNode';
  22871. }
  22872. /**
  22873. * Creates an instance of StructTypeNode.
  22874. *
  22875. * @param {Object} membersLayout - The layout of the members for the struct.
  22876. * @param {?string} [name=null] - The optional name of the struct.
  22877. */
  22878. constructor( membersLayout, name = null ) {
  22879. super( 'struct' );
  22880. /**
  22881. * The layout of the members for the struct
  22882. *
  22883. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  22884. */
  22885. this.membersLayout = getMembersLayout( membersLayout );
  22886. /**
  22887. * The name of the struct.
  22888. *
  22889. * @type {?string}
  22890. * @default null
  22891. */
  22892. this.name = name;
  22893. /**
  22894. * This flag can be used for type testing.
  22895. *
  22896. * @type {boolean}
  22897. * @readonly
  22898. * @default true
  22899. */
  22900. this.isStructLayoutNode = true;
  22901. }
  22902. /**
  22903. * Returns the length of the struct.
  22904. * The length is calculated by summing the lengths of the struct's members.
  22905. *
  22906. * @returns {number} The length of the struct.
  22907. */
  22908. getLength() {
  22909. const GPU_CHUNK_BYTES = 8;
  22910. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  22911. let offset = 0; // global buffer offset in bytes
  22912. for ( const member of this.membersLayout ) {
  22913. const type = member.type;
  22914. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  22915. const boundary = getByteBoundaryFromType( type );
  22916. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  22917. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  22918. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  22919. offset += chunkPadding;
  22920. // Check for chunk overflow
  22921. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  22922. // Add padding to the end of the chunk
  22923. offset += ( GPU_CHUNK_BYTES - chunkStart );
  22924. }
  22925. offset += itemSize;
  22926. }
  22927. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  22928. }
  22929. getMemberType( builder, name ) {
  22930. const member = this.membersLayout.find( m => m.name === name );
  22931. return member ? member.type : 'void';
  22932. }
  22933. getNodeType( builder ) {
  22934. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22935. return structType.name;
  22936. }
  22937. setup( builder ) {
  22938. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22939. builder.addInclude( this );
  22940. }
  22941. generate( builder ) {
  22942. return this.getNodeType( builder );
  22943. }
  22944. }
  22945. /**
  22946. * StructNode allows to create custom structures with multiple members.
  22947. * This can also be used to define structures in attribute and uniform data.
  22948. *
  22949. * ```js
  22950. * // Define a custom struct
  22951. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  22952. *
  22953. * // Create a new instance of the struct
  22954. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  22955. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  22956. *
  22957. * // Access the struct members
  22958. * const min = bb.get( 'min' );
  22959. *
  22960. * // Assign a new value to a member
  22961. * min.assign( vec3() );
  22962. * ```
  22963. * @augments Node
  22964. */
  22965. class StructNode extends Node {
  22966. static get type() {
  22967. return 'StructNode';
  22968. }
  22969. constructor( structTypeNode, values ) {
  22970. super( 'vec3' );
  22971. this.structTypeNode = structTypeNode;
  22972. this.values = values;
  22973. this.isStructNode = true;
  22974. }
  22975. getNodeType( builder ) {
  22976. return this.structTypeNode.getNodeType( builder );
  22977. }
  22978. getMemberType( builder, name ) {
  22979. return this.structTypeNode.getMemberType( builder, name );
  22980. }
  22981. generate( builder ) {
  22982. const nodeVar = builder.getVarFromNode( this );
  22983. const structType = nodeVar.type;
  22984. const propertyName = builder.getPropertyName( nodeVar );
  22985. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  22986. return nodeVar.name;
  22987. }
  22988. }
  22989. /**
  22990. * TSL function for creating a struct node.
  22991. *
  22992. * @tsl
  22993. * @function
  22994. * @param {Object} membersLayout - The layout of the struct members.
  22995. * @param {?string} [name=null] - The name of the struct.
  22996. * @returns {Function} The struct function.
  22997. */
  22998. const struct = ( membersLayout, name = null ) => {
  22999. const structLayout = new StructTypeNode( membersLayout, name );
  23000. const struct = ( ...params ) => {
  23001. let values = null;
  23002. if ( params.length > 0 ) {
  23003. if ( params[ 0 ].isNode ) {
  23004. values = {};
  23005. const names = Object.keys( membersLayout );
  23006. for ( let i = 0; i < params.length; i ++ ) {
  23007. values[ names[ i ] ] = params[ i ];
  23008. }
  23009. } else {
  23010. values = params[ 0 ];
  23011. }
  23012. }
  23013. return nodeObject( new StructNode( structLayout, values ) );
  23014. };
  23015. struct.layout = structLayout;
  23016. struct.isStruct = true;
  23017. return struct;
  23018. };
  23019. /**
  23020. * This node can be used to define multiple outputs in a shader programs.
  23021. *
  23022. * @augments Node
  23023. */
  23024. class OutputStructNode extends Node {
  23025. static get type() {
  23026. return 'OutputStructNode';
  23027. }
  23028. /**
  23029. * Constructs a new output struct node. The constructor can be invoked with an
  23030. * arbitrary number of nodes representing the members.
  23031. *
  23032. * @param {...Node} members - A parameter list of nodes.
  23033. */
  23034. constructor( ...members ) {
  23035. super();
  23036. /**
  23037. * An array of nodes which defines the output.
  23038. *
  23039. * @type {Array<Node>}
  23040. */
  23041. this.members = members;
  23042. /**
  23043. * This flag can be used for type testing.
  23044. *
  23045. * @type {boolean}
  23046. * @readonly
  23047. * @default true
  23048. */
  23049. this.isOutputStructNode = true;
  23050. }
  23051. getNodeType( builder ) {
  23052. const properties = builder.getNodeProperties( this );
  23053. if ( properties.membersLayout === undefined ) {
  23054. const members = this.members;
  23055. const membersLayout = [];
  23056. for ( let i = 0; i < members.length; i ++ ) {
  23057. const name = 'm' + i;
  23058. const type = members[ i ].getNodeType( builder );
  23059. membersLayout.push( { name, type, index: i } );
  23060. }
  23061. properties.membersLayout = membersLayout;
  23062. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  23063. }
  23064. return properties.structType.name;
  23065. }
  23066. generate( builder ) {
  23067. const propertyName = builder.getOutputStructName();
  23068. const members = this.members;
  23069. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  23070. for ( let i = 0; i < members.length; i ++ ) {
  23071. const snippet = members[ i ].build( builder );
  23072. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  23073. }
  23074. return propertyName;
  23075. }
  23076. }
  23077. /**
  23078. * TSL function for creating an output struct node.
  23079. *
  23080. * @tsl
  23081. * @function
  23082. * @param {...Node} members - A parameter list of nodes.
  23083. * @returns {OutputStructNode}
  23084. */
  23085. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  23086. /**
  23087. * Returns the MRT texture index for the given name.
  23088. *
  23089. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  23090. * @param {string} name - The name of the MRT texture which index is requested.
  23091. * @return {number} The texture index.
  23092. */
  23093. function getTextureIndex( textures, name ) {
  23094. for ( let i = 0; i < textures.length; i ++ ) {
  23095. if ( textures[ i ].name === name ) {
  23096. return i;
  23097. }
  23098. }
  23099. return -1;
  23100. }
  23101. /**
  23102. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  23103. * post-processing is shown below:
  23104. * ```js
  23105. * const mrtNode = mrt( {
  23106. * output: output,
  23107. * normal: normalView
  23108. * } ) );
  23109. * ```
  23110. * The MRT output is defined as a dictionary.
  23111. *
  23112. * @augments OutputStructNode
  23113. */
  23114. class MRTNode extends OutputStructNode {
  23115. static get type() {
  23116. return 'MRTNode';
  23117. }
  23118. /**
  23119. * Constructs a new output struct node.
  23120. *
  23121. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23122. */
  23123. constructor( outputNodes ) {
  23124. super();
  23125. /**
  23126. * A dictionary representing the MRT outputs. The key
  23127. * is the name of the output, the value the node which produces
  23128. * the output result.
  23129. *
  23130. * @type {Object<string, Node>}
  23131. */
  23132. this.outputNodes = outputNodes;
  23133. /**
  23134. * This flag can be used for type testing.
  23135. *
  23136. * @type {boolean}
  23137. * @readonly
  23138. * @default true
  23139. */
  23140. this.isMRTNode = true;
  23141. }
  23142. /**
  23143. * Returns `true` if the MRT node has an output with the given name.
  23144. *
  23145. * @param {string} name - The name of the output.
  23146. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  23147. */
  23148. has( name ) {
  23149. return this.outputNodes[ name ] !== undefined;
  23150. }
  23151. /**
  23152. * Returns the output node for the given name.
  23153. *
  23154. * @param {string} name - The name of the output.
  23155. * @return {Node} The output node.
  23156. */
  23157. get( name ) {
  23158. return this.outputNodes[ name ];
  23159. }
  23160. /**
  23161. * Merges the outputs of the given MRT node with the outputs of this node.
  23162. *
  23163. * @param {MRTNode} mrtNode - The MRT to merge.
  23164. * @return {MRTNode} A new MRT node with merged outputs..
  23165. */
  23166. merge( mrtNode ) {
  23167. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  23168. return mrt( outputs );
  23169. }
  23170. setup( builder ) {
  23171. const outputNodes = this.outputNodes;
  23172. const mrt = builder.renderer.getRenderTarget();
  23173. const members = [];
  23174. const textures = mrt.textures;
  23175. for ( const name in outputNodes ) {
  23176. const index = getTextureIndex( textures, name );
  23177. members[ index ] = vec4( outputNodes[ name ] );
  23178. }
  23179. this.members = members;
  23180. return super.setup( builder );
  23181. }
  23182. }
  23183. /**
  23184. * TSL function for creating a MRT node.
  23185. *
  23186. * @tsl
  23187. * @function
  23188. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  23189. * @returns {MRTNode}
  23190. */
  23191. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  23192. /**
  23193. * This node represents an operation that reinterprets the bit representation of a value
  23194. * in one type as a value in another type.
  23195. *
  23196. * @augments TempNode
  23197. */
  23198. class BitcastNode extends TempNode {
  23199. static get type() {
  23200. return 'BitcastNode';
  23201. }
  23202. /**
  23203. * Constructs a new bitcast node.
  23204. *
  23205. * @param {Node} valueNode - The value to convert.
  23206. * @param {string} conversionType - The type to convert to.
  23207. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23208. */
  23209. constructor( valueNode, conversionType, inputType = null ) {
  23210. super();
  23211. /**
  23212. * The data to bitcast to a new type.
  23213. *
  23214. * @type {Node}
  23215. */
  23216. this.valueNode = valueNode;
  23217. /**
  23218. * The type the value will be converted to.
  23219. *
  23220. * @type {string}
  23221. */
  23222. this.conversionType = conversionType;
  23223. /**
  23224. * The expected input data type of the bitcast operation.
  23225. *
  23226. *
  23227. * @type {string}
  23228. * @default null
  23229. */
  23230. this.inputType = inputType;
  23231. /**
  23232. * This flag can be used for type testing.
  23233. *
  23234. * @type {boolean}
  23235. * @readonly
  23236. * @default true
  23237. */
  23238. this.isBitcastNode = true;
  23239. }
  23240. getNodeType( builder ) {
  23241. // GLSL aliasing
  23242. if ( this.inputType !== null ) {
  23243. const valueType = this.valueNode.getNodeType( builder );
  23244. const valueLength = builder.getTypeLength( valueType );
  23245. return builder.getTypeFromLength( valueLength, this.conversionType );
  23246. }
  23247. return this.conversionType;
  23248. }
  23249. generate( builder ) {
  23250. const type = this.getNodeType( builder );
  23251. let inputType = '';
  23252. if ( this.inputType !== null ) {
  23253. const valueType = this.valueNode.getNodeType( builder );
  23254. const valueTypeLength = builder.getTypeLength( valueType );
  23255. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  23256. } else {
  23257. inputType = this.valueNode.getNodeType( builder );
  23258. }
  23259. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  23260. }
  23261. }
  23262. /**
  23263. * Reinterpret the bit representation of a value in one type as a value in another type.
  23264. *
  23265. * @tsl
  23266. * @function
  23267. * @param {Node | number} x - The parameter.
  23268. * @param {string} y - The new type.
  23269. * @returns {Node}
  23270. */
  23271. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  23272. /**
  23273. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  23274. *
  23275. * @tsl
  23276. * @function
  23277. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23278. * @returns {BitcastNode}
  23279. */
  23280. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  23281. /**
  23282. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  23283. *
  23284. * @tsl
  23285. * @function
  23286. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23287. * @returns {BitcastNode}
  23288. */
  23289. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  23290. /**
  23291. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  23292. *
  23293. * @tsl
  23294. * @function
  23295. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  23296. * @returns {BitcastNode}
  23297. */
  23298. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  23299. /**
  23300. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  23301. *
  23302. * @tsl
  23303. * @function
  23304. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  23305. * @returns {BitcastNode}
  23306. */
  23307. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  23308. /**
  23309. * Generates a hash value in the range `[0, 1]` from the given seed.
  23310. *
  23311. * @tsl
  23312. * @function
  23313. * @param {Node<float>} seed - The seed.
  23314. * @return {Node<float>} The hash value.
  23315. */
  23316. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  23317. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  23318. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  23319. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  23320. const result = word.shiftRight( 22 ).bitXor( word );
  23321. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  23322. } );
  23323. /**
  23324. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23325. * The corners are mapped to `0` and the center to `1`.
  23326. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23327. *
  23328. * @tsl
  23329. * @function
  23330. * @param {Node<float>} x - The value to remap.
  23331. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  23332. * @return {Node<float>} The remapped value.
  23333. */
  23334. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  23335. /**
  23336. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23337. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  23338. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23339. *
  23340. * @tsl
  23341. * @function
  23342. * @param {Node<float>} x - The value to remap.
  23343. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  23344. * @return {Node<float>} The remapped value.
  23345. */
  23346. 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 ) );
  23347. /**
  23348. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23349. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  23350. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23351. *
  23352. * @tsl
  23353. * @function
  23354. * @param {Node<float>} x - The value to remap.
  23355. * @param {Node<float>} a - First control parameter.
  23356. * @param {Node<float>} b - Second control parameter.
  23357. * @return {Node<float>} The remapped value.
  23358. */
  23359. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  23360. /**
  23361. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  23362. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23363. *
  23364. * @tsl
  23365. * @function
  23366. * @param {Node<float>} x - The value to compute the sin for.
  23367. * @param {Node<float>} k - Controls the amount of bounces.
  23368. * @return {Node<float>} The result value.
  23369. */
  23370. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  23371. // https://github.com/cabbibo/glsl-tri-noise-3d
  23372. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  23373. return x.fract().sub( .5 ).abs();
  23374. } ).setLayout( {
  23375. name: 'tri',
  23376. type: 'float',
  23377. inputs: [
  23378. { name: 'x', type: 'float' }
  23379. ]
  23380. } );
  23381. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  23382. 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. ) ) ) ) );
  23383. } ).setLayout( {
  23384. name: 'tri3',
  23385. type: 'vec3',
  23386. inputs: [
  23387. { name: 'p', type: 'vec3' }
  23388. ]
  23389. } );
  23390. /**
  23391. * Generates a noise value from the given position, speed and time parameters.
  23392. *
  23393. * @tsl
  23394. * @function
  23395. * @param {Node<vec3>} position - The position.
  23396. * @param {Node<float>} speed - The speed.
  23397. * @param {Node<float>} time - The time.
  23398. * @return {Node<float>} The generated noise.
  23399. */
  23400. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  23401. const p = vec3( position ).toVar();
  23402. const z = float( 1.4 ).toVar();
  23403. const rz = float( 0.0 ).toVar();
  23404. const bp = vec3( p ).toVar();
  23405. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  23406. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  23407. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  23408. bp.mulAssign( 1.8 );
  23409. z.mulAssign( 1.5 );
  23410. p.mulAssign( 1.2 );
  23411. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  23412. rz.addAssign( t.div( z ) );
  23413. bp.addAssign( 0.14 );
  23414. } );
  23415. return rz;
  23416. } ).setLayout( {
  23417. name: 'triNoise3D',
  23418. type: 'float',
  23419. inputs: [
  23420. { name: 'position', type: 'vec3' },
  23421. { name: 'speed', type: 'float' },
  23422. { name: 'time', type: 'float' }
  23423. ]
  23424. } );
  23425. /**
  23426. * This class allows to define multiple overloaded versions
  23427. * of the same function. Depending on the parameters of the function
  23428. * call, the node picks the best-fit overloaded version.
  23429. *
  23430. * @augments Node
  23431. */
  23432. class FunctionOverloadingNode extends Node {
  23433. static get type() {
  23434. return 'FunctionOverloadingNode';
  23435. }
  23436. /**
  23437. * Constructs a new function overloading node.
  23438. *
  23439. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23440. * @param {...Node} parametersNodes - A list of parameter nodes.
  23441. */
  23442. constructor( functionNodes = [], ...parametersNodes ) {
  23443. super();
  23444. /**
  23445. * Array of `Fn` function definitions.
  23446. *
  23447. * @type {Array<Function>}
  23448. */
  23449. this.functionNodes = functionNodes;
  23450. /**
  23451. * A list of parameter nodes.
  23452. *
  23453. * @type {Array<Node>}
  23454. */
  23455. this.parametersNodes = parametersNodes;
  23456. /**
  23457. * The selected overloaded function call.
  23458. *
  23459. * @private
  23460. * @type {ShaderCallNodeInternal}
  23461. */
  23462. this._candidateFnCall = null;
  23463. /**
  23464. * This node is marked as global.
  23465. *
  23466. * @type {boolean}
  23467. * @default true
  23468. */
  23469. this.global = true;
  23470. }
  23471. /**
  23472. * This method is overwritten since the node type is inferred from
  23473. * the function's return type.
  23474. *
  23475. * @param {NodeBuilder} builder - The current node builder.
  23476. * @return {string} The node type.
  23477. */
  23478. getNodeType() {
  23479. return this.functionNodes[ 0 ].shaderNode.layout.type;
  23480. }
  23481. setup( builder ) {
  23482. const params = this.parametersNodes;
  23483. let candidateFnCall = this._candidateFnCall;
  23484. if ( candidateFnCall === null ) {
  23485. let candidateFn = null;
  23486. let candidateScore = -1;
  23487. for ( const functionNode of this.functionNodes ) {
  23488. const shaderNode = functionNode.shaderNode;
  23489. const layout = shaderNode.layout;
  23490. if ( layout === null ) {
  23491. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  23492. }
  23493. const inputs = layout.inputs;
  23494. if ( params.length === inputs.length ) {
  23495. let score = 0;
  23496. for ( let i = 0; i < params.length; i ++ ) {
  23497. const param = params[ i ];
  23498. const input = inputs[ i ];
  23499. if ( param.getNodeType( builder ) === input.type ) {
  23500. score ++;
  23501. } else {
  23502. score = 0;
  23503. }
  23504. }
  23505. if ( score > candidateScore ) {
  23506. candidateFn = functionNode;
  23507. candidateScore = score;
  23508. }
  23509. }
  23510. }
  23511. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  23512. }
  23513. return candidateFnCall;
  23514. }
  23515. }
  23516. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  23517. /**
  23518. * TSL function for creating a function overloading node.
  23519. *
  23520. * @tsl
  23521. * @function
  23522. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23523. * @returns {FunctionOverloadingNode}
  23524. */
  23525. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  23526. /**
  23527. * Represents the elapsed time in seconds.
  23528. *
  23529. * @tsl
  23530. * @type {UniformNode<float>}
  23531. */
  23532. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  23533. /**
  23534. * Represents the delta time in seconds.
  23535. *
  23536. * @tsl
  23537. * @type {UniformNode<float>}
  23538. */
  23539. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  23540. /**
  23541. * Represents the current frame ID.
  23542. *
  23543. * @tsl
  23544. * @type {UniformNode<uint>}
  23545. */
  23546. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  23547. /**
  23548. * Generates a sine wave oscillation based on a timer.
  23549. *
  23550. * @tsl
  23551. * @function
  23552. * @param {Node<float>} t - The timer to generate the oscillation with.
  23553. * @return {Node<float>} The oscillation node.
  23554. */
  23555. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  23556. /**
  23557. * Generates a square wave oscillation based on a timer.
  23558. *
  23559. * @tsl
  23560. * @function
  23561. * @param {Node<float>} t - The timer to generate the oscillation with.
  23562. * @return {Node<float>} The oscillation node.
  23563. */
  23564. const oscSquare = ( t = time ) => t.fract().round();
  23565. /**
  23566. * Generates a triangle wave oscillation based on a timer.
  23567. *
  23568. * @tsl
  23569. * @function
  23570. * @param {Node<float>} t - The timer to generate the oscillation with.
  23571. * @return {Node<float>} The oscillation node.
  23572. */
  23573. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  23574. /**
  23575. * Generates a sawtooth wave oscillation based on a timer.
  23576. *
  23577. * @tsl
  23578. * @function
  23579. * @param {Node<float>} t - The timer to generate the oscillation with.
  23580. * @return {Node<float>} The oscillation node.
  23581. */
  23582. const oscSawtooth = ( t = time ) => t.fract();
  23583. /**
  23584. * Rotates the given uv coordinates around a center point
  23585. *
  23586. * @tsl
  23587. * @function
  23588. * @param {Node<vec2>} uv - The uv coordinates.
  23589. * @param {Node<float>} rotation - The rotation defined in radians.
  23590. * @param {Node<vec2>} center - The center of rotation
  23591. * @return {Node<vec2>} The rotated uv coordinates.
  23592. */
  23593. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  23594. return rotate( uv.sub( center ), rotation ).add( center );
  23595. } );
  23596. /**
  23597. * Applies a spherical warping effect to the given uv coordinates.
  23598. *
  23599. * @tsl
  23600. * @function
  23601. * @param {Node<vec2>} uv - The uv coordinates.
  23602. * @param {Node<float>} strength - The strength of the effect.
  23603. * @param {Node<vec2>} center - The center point
  23604. * @return {Node<vec2>} The updated uv coordinates.
  23605. */
  23606. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  23607. const delta = uv.sub( center );
  23608. const delta2 = delta.dot( delta );
  23609. const delta4 = delta2.mul( delta2 );
  23610. const deltaOffset = delta4.mul( strength );
  23611. return uv.add( delta.mul( deltaOffset ) );
  23612. } );
  23613. /**
  23614. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  23615. * oriented always towards the camera.
  23616. *
  23617. * ```js
  23618. * material.vertexNode = billboarding();
  23619. * ```
  23620. *
  23621. * @tsl
  23622. * @function
  23623. * @param {Object} config - The configuration object.
  23624. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  23625. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  23626. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  23627. * @return {Node<vec3>} The updated vertex position in clip space.
  23628. */
  23629. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  23630. let worldMatrix;
  23631. if ( position !== null ) {
  23632. worldMatrix = modelWorldMatrix.toVar();
  23633. worldMatrix[ 3 ][ 0 ] = position.x;
  23634. worldMatrix[ 3 ][ 1 ] = position.y;
  23635. worldMatrix[ 3 ][ 2 ] = position.z;
  23636. } else {
  23637. worldMatrix = modelWorldMatrix;
  23638. }
  23639. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  23640. if ( defined( horizontal ) ) {
  23641. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  23642. modelViewMatrix[ 0 ][ 1 ] = 0;
  23643. modelViewMatrix[ 0 ][ 2 ] = 0;
  23644. }
  23645. if ( defined( vertical ) ) {
  23646. modelViewMatrix[ 1 ][ 0 ] = 0;
  23647. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  23648. modelViewMatrix[ 1 ][ 2 ] = 0;
  23649. }
  23650. modelViewMatrix[ 2 ][ 0 ] = 0;
  23651. modelViewMatrix[ 2 ][ 1 ] = 0;
  23652. modelViewMatrix[ 2 ][ 2 ] = 1;
  23653. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23654. } );
  23655. /**
  23656. * A special version of a screen uv function that involves a depth comparison
  23657. * when computing the final uvs. The function mitigates visual errors when
  23658. * using viewport texture nodes for refraction purposes. Without this function
  23659. * objects in front of a refractive surface might appear on the refractive surface
  23660. * which is incorrect.
  23661. *
  23662. * @tsl
  23663. * @function
  23664. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  23665. * @return {Node<vec2>} The update uv coordinates.
  23666. */
  23667. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  23668. const depth = linearDepth();
  23669. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  23670. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  23671. return finalUV;
  23672. } );
  23673. /**
  23674. * Can be used to compute texture coordinates for animated sprite sheets.
  23675. *
  23676. * ```js
  23677. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  23678. *
  23679. * material.colorNode = texture( spriteSheet, uvNode );
  23680. * ```
  23681. *
  23682. * @augments Node
  23683. */
  23684. class SpriteSheetUVNode extends Node {
  23685. static get type() {
  23686. return 'SpriteSheetUVNode';
  23687. }
  23688. /**
  23689. * Constructs a new sprite sheet uv node.
  23690. *
  23691. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23692. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  23693. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23694. */
  23695. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  23696. super( 'vec2' );
  23697. /**
  23698. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23699. *
  23700. * @type {Node<vec2>}
  23701. */
  23702. this.countNode = countNode;
  23703. /**
  23704. * The uv node.
  23705. *
  23706. * @type {Node<vec2>}
  23707. */
  23708. this.uvNode = uvNode;
  23709. /**
  23710. * The node that defines the current frame/sprite.
  23711. *
  23712. * @type {Node<float>}
  23713. */
  23714. this.frameNode = frameNode;
  23715. }
  23716. setup() {
  23717. const { frameNode, uvNode, countNode } = this;
  23718. const { width, height } = countNode;
  23719. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  23720. const column = frameNum.mod( width );
  23721. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  23722. const scale = countNode.reciprocal();
  23723. const uvFrameOffset = vec2( column, row );
  23724. return uvNode.add( uvFrameOffset ).mul( scale );
  23725. }
  23726. }
  23727. /**
  23728. * TSL function for creating a sprite sheet uv node.
  23729. *
  23730. * @tsl
  23731. * @function
  23732. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23733. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  23734. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23735. * @returns {SpriteSheetUVNode}
  23736. */
  23737. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  23738. /**
  23739. * TSL function for creating a triplanar textures node.
  23740. *
  23741. * Can be used for triplanar texture mapping.
  23742. *
  23743. * ```js
  23744. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  23745. * ```
  23746. *
  23747. * @tsl
  23748. * @function
  23749. * @param {Node} textureXNode - First texture node.
  23750. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23751. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23752. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23753. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23754. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23755. * @returns {Node<vec4>}
  23756. */
  23757. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  23758. // Reference: https://github.com/keijiro/StandardTriplanar
  23759. // Blending factor of triplanar mapping
  23760. let bf = normalNode.abs().normalize();
  23761. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  23762. // Triplanar mapping
  23763. const tx = positionNode.yz.mul( scaleNode );
  23764. const ty = positionNode.zx.mul( scaleNode );
  23765. const tz = positionNode.xy.mul( scaleNode );
  23766. // Base color
  23767. const textureX = textureXNode.value;
  23768. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  23769. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  23770. const cx = texture( textureX, tx ).mul( bf.x );
  23771. const cy = texture( textureY, ty ).mul( bf.y );
  23772. const cz = texture( textureZ, tz ).mul( bf.z );
  23773. return add( cx, cy, cz );
  23774. } );
  23775. /**
  23776. * TSL function for creating a triplanar textures node.
  23777. *
  23778. * @tsl
  23779. * @function
  23780. * @param {Node} textureXNode - First texture node.
  23781. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23782. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23783. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23784. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23785. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23786. * @returns {Node<vec4>}
  23787. */
  23788. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  23789. const _reflectorPlane = new Plane();
  23790. const _normal = new Vector3();
  23791. const _reflectorWorldPosition = new Vector3();
  23792. const _cameraWorldPosition = new Vector3();
  23793. const _rotationMatrix = new Matrix4();
  23794. const _lookAtPosition = new Vector3( 0, 0, -1 );
  23795. const clipPlane = new Vector4();
  23796. const _view = new Vector3();
  23797. const _target = new Vector3();
  23798. const _q = new Vector4();
  23799. const _size$2 = new Vector2();
  23800. const _defaultRT = new RenderTarget();
  23801. const _defaultUV = screenUV.flipX();
  23802. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  23803. let _inReflector = false;
  23804. /**
  23805. * This node can be used to implement mirror-like flat reflective surfaces.
  23806. *
  23807. * ```js
  23808. * const groundReflector = reflector();
  23809. * material.colorNode = groundReflector;
  23810. *
  23811. * const plane = new Mesh( geometry, material );
  23812. * plane.add( groundReflector.target );
  23813. * ```
  23814. *
  23815. * @augments TextureNode
  23816. */
  23817. class ReflectorNode extends TextureNode {
  23818. static get type() {
  23819. return 'ReflectorNode';
  23820. }
  23821. /**
  23822. * Constructs a new reflector node.
  23823. *
  23824. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23825. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23826. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  23827. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23828. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23829. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23830. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23831. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23832. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23833. */
  23834. constructor( parameters = {} ) {
  23835. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  23836. /**
  23837. * A reference to the internal reflector base node which holds the actual implementation.
  23838. *
  23839. * @private
  23840. * @type {ReflectorBaseNode}
  23841. * @default ReflectorBaseNode
  23842. */
  23843. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  23844. /**
  23845. * A reference to the internal depth node.
  23846. *
  23847. * @private
  23848. * @type {?Node}
  23849. * @default null
  23850. */
  23851. this._depthNode = null;
  23852. this.setUpdateMatrix( false );
  23853. }
  23854. /**
  23855. * A reference to the internal reflector node.
  23856. *
  23857. * @type {ReflectorBaseNode}
  23858. */
  23859. get reflector() {
  23860. return this._reflectorBaseNode;
  23861. }
  23862. /**
  23863. * A reference to 3D object the reflector is linked to.
  23864. *
  23865. * @type {Object3D}
  23866. */
  23867. get target() {
  23868. return this._reflectorBaseNode.target;
  23869. }
  23870. /**
  23871. * Returns a node representing the mirror's depth. That can be used
  23872. * to implement more advanced reflection effects like distance attenuation.
  23873. *
  23874. * @return {Node} The depth node.
  23875. */
  23876. getDepthNode() {
  23877. if ( this._depthNode === null ) {
  23878. if ( this._reflectorBaseNode.depth !== true ) {
  23879. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  23880. }
  23881. this._depthNode = nodeObject( new ReflectorNode( {
  23882. defaultTexture: _defaultRT.depthTexture,
  23883. reflector: this._reflectorBaseNode
  23884. } ) );
  23885. }
  23886. return this._depthNode;
  23887. }
  23888. setup( builder ) {
  23889. // ignore if used in post-processing
  23890. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  23891. return super.setup( builder );
  23892. }
  23893. clone() {
  23894. const newNode = new this.constructor( this.reflectorNode );
  23895. newNode.uvNode = this.uvNode;
  23896. newNode.levelNode = this.levelNode;
  23897. newNode.biasNode = this.biasNode;
  23898. newNode.sampler = this.sampler;
  23899. newNode.depthNode = this.depthNode;
  23900. newNode.compareNode = this.compareNode;
  23901. newNode.gradNode = this.gradNode;
  23902. newNode.offsetNode = this.offsetNode;
  23903. newNode._reflectorBaseNode = this._reflectorBaseNode;
  23904. return newNode;
  23905. }
  23906. /**
  23907. * Frees internal resources. Should be called when the node is no longer in use.
  23908. */
  23909. dispose() {
  23910. super.dispose();
  23911. this._reflectorBaseNode.dispose();
  23912. }
  23913. }
  23914. /**
  23915. * Holds the actual implementation of the reflector.
  23916. *
  23917. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  23918. * in `ReflectorNode`, see #29619.
  23919. *
  23920. * @private
  23921. * @augments Node
  23922. */
  23923. class ReflectorBaseNode extends Node {
  23924. static get type() {
  23925. return 'ReflectorBaseNode';
  23926. }
  23927. /**
  23928. * Constructs a new reflector base node.
  23929. *
  23930. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  23931. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23932. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23933. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  23934. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23935. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23936. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23937. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23938. */
  23939. constructor( textureNode, parameters = {} ) {
  23940. super();
  23941. const {
  23942. target = new Object3D(),
  23943. resolutionScale = 1,
  23944. generateMipmaps = false,
  23945. bounces = true,
  23946. depth = false,
  23947. samples = 0
  23948. } = parameters;
  23949. /**
  23950. * Represents the rendered reflections as a texture node.
  23951. *
  23952. * @type {TextureNode}
  23953. */
  23954. this.textureNode = textureNode;
  23955. /**
  23956. * The 3D object the reflector is linked to.
  23957. *
  23958. * @type {Object3D}
  23959. * @default {new Object3D()}
  23960. */
  23961. this.target = target;
  23962. /**
  23963. * The resolution scale.
  23964. *
  23965. * @type {number}
  23966. * @default {1}
  23967. */
  23968. this.resolutionScale = resolutionScale;
  23969. if ( parameters.resolution !== undefined ) {
  23970. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  23971. this.resolutionScale = parameters.resolution;
  23972. }
  23973. /**
  23974. * Whether mipmaps should be generated or not.
  23975. *
  23976. * @type {boolean}
  23977. * @default {false}
  23978. */
  23979. this.generateMipmaps = generateMipmaps;
  23980. /**
  23981. * Whether reflectors can render other reflector nodes or not.
  23982. *
  23983. * @type {boolean}
  23984. * @default {true}
  23985. */
  23986. this.bounces = bounces;
  23987. /**
  23988. * Whether depth data should be generated or not.
  23989. *
  23990. * @type {boolean}
  23991. * @default {false}
  23992. */
  23993. this.depth = depth;
  23994. /**
  23995. * The number of anti-aliasing samples for the render-target
  23996. *
  23997. * @type {number}
  23998. * @default {0}
  23999. */
  24000. this.samples = samples;
  24001. /**
  24002. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  24003. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  24004. *
  24005. * @type {string}
  24006. * @default 'render'
  24007. */
  24008. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  24009. /**
  24010. * Weak map for managing virtual cameras.
  24011. *
  24012. * @type {WeakMap<Camera, Camera>}
  24013. */
  24014. this.virtualCameras = new WeakMap();
  24015. /**
  24016. * Weak map for managing render targets.
  24017. *
  24018. * @type {Map<Camera, RenderTarget>}
  24019. */
  24020. this.renderTargets = new Map();
  24021. /**
  24022. * Force render even if reflector is facing away from camera.
  24023. *
  24024. * @type {boolean}
  24025. * @default {false}
  24026. */
  24027. this.forceUpdate = false;
  24028. /**
  24029. * Whether the reflector has been rendered or not.
  24030. *
  24031. * When the reflector is facing away from the camera,
  24032. * this flag is set to `false` and the texture will be empty(black).
  24033. *
  24034. * @type {boolean}
  24035. * @default {false}
  24036. */
  24037. this.hasOutput = false;
  24038. }
  24039. /**
  24040. * Updates the resolution of the internal render target.
  24041. *
  24042. * @private
  24043. * @param {RenderTarget} renderTarget - The render target to resize.
  24044. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  24045. */
  24046. _updateResolution( renderTarget, renderer ) {
  24047. const resolution = this.resolutionScale;
  24048. renderer.getDrawingBufferSize( _size$2 );
  24049. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  24050. }
  24051. setup( builder ) {
  24052. this._updateResolution( _defaultRT, builder.renderer );
  24053. return super.setup( builder );
  24054. }
  24055. /**
  24056. * Frees internal resources. Should be called when the node is no longer in use.
  24057. */
  24058. dispose() {
  24059. super.dispose();
  24060. for ( const renderTarget of this.renderTargets.values() ) {
  24061. renderTarget.dispose();
  24062. }
  24063. }
  24064. /**
  24065. * Returns a virtual camera for the given camera. The virtual camera is used to
  24066. * render the scene from the reflector's view so correct reflections can be produced.
  24067. *
  24068. * @param {Camera} camera - The scene's camera.
  24069. * @return {Camera} The corresponding virtual camera.
  24070. */
  24071. getVirtualCamera( camera ) {
  24072. let virtualCamera = this.virtualCameras.get( camera );
  24073. if ( virtualCamera === undefined ) {
  24074. virtualCamera = camera.clone();
  24075. this.virtualCameras.set( camera, virtualCamera );
  24076. }
  24077. return virtualCamera;
  24078. }
  24079. /**
  24080. * Returns a render target for the given camera. The reflections are rendered
  24081. * into this render target.
  24082. *
  24083. * @param {Camera} camera - The scene's camera.
  24084. * @return {RenderTarget} The render target.
  24085. */
  24086. getRenderTarget( camera ) {
  24087. let renderTarget = this.renderTargets.get( camera );
  24088. if ( renderTarget === undefined ) {
  24089. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  24090. if ( this.generateMipmaps === true ) {
  24091. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  24092. renderTarget.texture.generateMipmaps = true;
  24093. }
  24094. if ( this.depth === true ) {
  24095. renderTarget.depthTexture = new DepthTexture();
  24096. }
  24097. this.renderTargets.set( camera, renderTarget );
  24098. }
  24099. return renderTarget;
  24100. }
  24101. updateBefore( frame ) {
  24102. if ( this.bounces === false && _inReflector ) return false;
  24103. _inReflector = true;
  24104. const { scene, camera, renderer, material } = frame;
  24105. const { target } = this;
  24106. const virtualCamera = this.getVirtualCamera( camera );
  24107. const renderTarget = this.getRenderTarget( virtualCamera );
  24108. renderer.getDrawingBufferSize( _size$2 );
  24109. this._updateResolution( renderTarget, renderer );
  24110. //
  24111. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  24112. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  24113. _rotationMatrix.extractRotation( target.matrixWorld );
  24114. _normal.set( 0, 0, 1 );
  24115. _normal.applyMatrix4( _rotationMatrix );
  24116. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  24117. // Avoid rendering when reflector is facing away unless forcing an update
  24118. const isFacingAway = _view.dot( _normal ) > 0;
  24119. let needsClear = false;
  24120. if ( isFacingAway === true && this.forceUpdate === false ) {
  24121. if ( this.hasOutput === false ) {
  24122. _inReflector = false;
  24123. return;
  24124. }
  24125. needsClear = true;
  24126. }
  24127. _view.reflect( _normal ).negate();
  24128. _view.add( _reflectorWorldPosition );
  24129. _rotationMatrix.extractRotation( camera.matrixWorld );
  24130. _lookAtPosition.set( 0, 0, -1 );
  24131. _lookAtPosition.applyMatrix4( _rotationMatrix );
  24132. _lookAtPosition.add( _cameraWorldPosition );
  24133. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  24134. _target.reflect( _normal ).negate();
  24135. _target.add( _reflectorWorldPosition );
  24136. //
  24137. virtualCamera.coordinateSystem = camera.coordinateSystem;
  24138. virtualCamera.position.copy( _view );
  24139. virtualCamera.up.set( 0, 1, 0 );
  24140. virtualCamera.up.applyMatrix4( _rotationMatrix );
  24141. virtualCamera.up.reflect( _normal );
  24142. virtualCamera.lookAt( _target );
  24143. virtualCamera.near = camera.near;
  24144. virtualCamera.far = camera.far;
  24145. virtualCamera.updateMatrixWorld();
  24146. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  24147. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  24148. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  24149. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  24150. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  24151. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  24152. const projectionMatrix = virtualCamera.projectionMatrix;
  24153. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  24154. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  24155. _q.z = -1;
  24156. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  24157. // Calculate the scaled plane vector
  24158. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  24159. const clipBias = 0;
  24160. // Replacing the third row of the projection matrix
  24161. projectionMatrix.elements[ 2 ] = clipPlane.x;
  24162. projectionMatrix.elements[ 6 ] = clipPlane.y;
  24163. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  24164. projectionMatrix.elements[ 14 ] = clipPlane.w;
  24165. //
  24166. this.textureNode.value = renderTarget.texture;
  24167. if ( this.depth === true ) {
  24168. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  24169. }
  24170. material.visible = false;
  24171. const currentRenderTarget = renderer.getRenderTarget();
  24172. const currentMRT = renderer.getMRT();
  24173. const currentAutoClear = renderer.autoClear;
  24174. renderer.setMRT( null );
  24175. renderer.setRenderTarget( renderTarget );
  24176. renderer.autoClear = true;
  24177. if ( needsClear ) {
  24178. renderer.clear();
  24179. this.hasOutput = false;
  24180. } else {
  24181. renderer.render( scene, virtualCamera );
  24182. this.hasOutput = true;
  24183. }
  24184. renderer.setMRT( currentMRT );
  24185. renderer.setRenderTarget( currentRenderTarget );
  24186. renderer.autoClear = currentAutoClear;
  24187. material.visible = true;
  24188. _inReflector = false;
  24189. this.forceUpdate = false;
  24190. }
  24191. /**
  24192. * The resolution scale.
  24193. *
  24194. * @deprecated
  24195. * @type {number}
  24196. * @default {1}
  24197. */
  24198. get resolution() {
  24199. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24200. return this.resolutionScale;
  24201. }
  24202. set resolution( value ) {
  24203. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  24204. this.resolutionScale = value;
  24205. }
  24206. }
  24207. /**
  24208. * TSL function for creating a reflector node.
  24209. *
  24210. * @tsl
  24211. * @function
  24212. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24213. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24214. * @param {number} [parameters.resolution=1] - The resolution scale.
  24215. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24216. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24217. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24218. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24219. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24220. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24221. * @returns {ReflectorNode}
  24222. */
  24223. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  24224. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  24225. /**
  24226. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  24227. *
  24228. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  24229. *
  24230. * @private
  24231. * @augments BufferGeometry
  24232. */
  24233. class QuadGeometry extends BufferGeometry {
  24234. /**
  24235. * Constructs a new quad geometry.
  24236. *
  24237. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  24238. */
  24239. constructor( flipY = false ) {
  24240. super();
  24241. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  24242. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  24243. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  24244. }
  24245. }
  24246. const _geometry = /*@__PURE__*/ new QuadGeometry();
  24247. /**
  24248. * This module is a helper for passes which need to render a full
  24249. * screen effect which is quite common in context of post processing.
  24250. *
  24251. * The intended usage is to reuse a single quad mesh for rendering
  24252. * subsequent passes by just reassigning the `material` reference.
  24253. *
  24254. * Note: This module can only be used with `WebGPURenderer`.
  24255. *
  24256. * @augments Mesh
  24257. */
  24258. class QuadMesh extends Mesh {
  24259. /**
  24260. * Constructs a new quad mesh.
  24261. *
  24262. * @param {?Material} [material=null] - The material to render the quad mesh with.
  24263. */
  24264. constructor( material = null ) {
  24265. super( _geometry, material );
  24266. /**
  24267. * The camera to render the quad mesh with.
  24268. *
  24269. * @type {OrthographicCamera}
  24270. * @readonly
  24271. */
  24272. this.camera = _camera;
  24273. /**
  24274. * This flag can be used for type testing.
  24275. *
  24276. * @type {boolean}
  24277. * @readonly
  24278. * @default true
  24279. */
  24280. this.isQuadMesh = true;
  24281. }
  24282. /**
  24283. * Async version of `render()`.
  24284. *
  24285. * @async
  24286. * @param {Renderer} renderer - The renderer.
  24287. * @return {Promise} A Promise that resolves when the render has been finished.
  24288. */
  24289. async renderAsync( renderer ) {
  24290. return renderer.renderAsync( this, _camera );
  24291. }
  24292. /**
  24293. * Renders the quad mesh
  24294. *
  24295. * @param {Renderer} renderer - The renderer.
  24296. */
  24297. render( renderer ) {
  24298. renderer.render( this, _camera );
  24299. }
  24300. }
  24301. const _size$1 = /*@__PURE__*/ new Vector2();
  24302. /**
  24303. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  24304. * This module is especially relevant in context of post processing where certain nodes require
  24305. * texture input for their effects. With the helper function `convertToTexture()` which is based
  24306. * on this module, the node system can automatically ensure texture input if required.
  24307. *
  24308. * @augments TextureNode
  24309. */
  24310. class RTTNode extends TextureNode {
  24311. static get type() {
  24312. return 'RTTNode';
  24313. }
  24314. /**
  24315. * Constructs a new RTT node.
  24316. *
  24317. * @param {Node} node - The node to render a texture with.
  24318. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24319. * @param {?number} [height=null] - The height of the internal render target.
  24320. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24321. */
  24322. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  24323. const renderTarget = new RenderTarget( width, height, options );
  24324. super( renderTarget.texture, uv$1() );
  24325. /**
  24326. * This flag can be used for type testing.
  24327. *
  24328. * @type {boolean}
  24329. * @readonly
  24330. * @default true
  24331. */
  24332. this.isRTTNode = true;
  24333. /**
  24334. * The node to render a texture with.
  24335. *
  24336. * @type {Node}
  24337. */
  24338. this.node = node;
  24339. /**
  24340. * The width of the internal render target.
  24341. * If not width is applied, the render target is automatically resized.
  24342. *
  24343. * @type {?number}
  24344. * @default null
  24345. */
  24346. this.width = width;
  24347. /**
  24348. * The height of the internal render target.
  24349. *
  24350. * @type {?number}
  24351. * @default null
  24352. */
  24353. this.height = height;
  24354. /**
  24355. * The pixel ratio
  24356. *
  24357. * @type {number}
  24358. * @default 1
  24359. */
  24360. this.pixelRatio = 1;
  24361. /**
  24362. * The render target
  24363. *
  24364. * @type {RenderTarget}
  24365. */
  24366. this.renderTarget = renderTarget;
  24367. /**
  24368. * Whether the texture requires an update or not.
  24369. *
  24370. * @type {boolean}
  24371. * @default true
  24372. */
  24373. this.textureNeedsUpdate = true;
  24374. /**
  24375. * Whether the texture should automatically be updated or not.
  24376. *
  24377. * @type {boolean}
  24378. * @default true
  24379. */
  24380. this.autoUpdate = true;
  24381. /**
  24382. * The node which is used with the quad mesh for RTT.
  24383. *
  24384. * @private
  24385. * @type {Node}
  24386. * @default null
  24387. */
  24388. this._rttNode = null;
  24389. /**
  24390. * The internal quad mesh for RTT.
  24391. *
  24392. * @private
  24393. * @type {QuadMesh}
  24394. */
  24395. this._quadMesh = new QuadMesh( new NodeMaterial() );
  24396. /**
  24397. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  24398. * the texture once per render in its {@link RTTNode#updateBefore} method.
  24399. *
  24400. * @type {string}
  24401. * @default 'render'
  24402. */
  24403. this.updateBeforeType = NodeUpdateType.RENDER;
  24404. }
  24405. /**
  24406. * Whether the internal render target should automatically be resized or not.
  24407. *
  24408. * @type {boolean}
  24409. * @readonly
  24410. * @default true
  24411. */
  24412. get autoResize() {
  24413. return this.width === null;
  24414. }
  24415. setup( builder ) {
  24416. this._rttNode = this.node.context( builder.getSharedContext() );
  24417. this._quadMesh.material.name = 'RTT';
  24418. this._quadMesh.material.needsUpdate = true;
  24419. return super.setup( builder );
  24420. }
  24421. /**
  24422. * Sets the size of the internal render target
  24423. *
  24424. * @param {number} width - The width to set.
  24425. * @param {number} height - The width to set.
  24426. */
  24427. setSize( width, height ) {
  24428. this.width = width;
  24429. this.height = height;
  24430. const effectiveWidth = width * this.pixelRatio;
  24431. const effectiveHeight = height * this.pixelRatio;
  24432. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24433. this.textureNeedsUpdate = true;
  24434. }
  24435. /**
  24436. * Sets the pixel ratio. This will also resize the render target.
  24437. *
  24438. * @param {number} pixelRatio - The pixel ratio to set.
  24439. */
  24440. setPixelRatio( pixelRatio ) {
  24441. this.pixelRatio = pixelRatio;
  24442. this.setSize( this.width, this.height );
  24443. }
  24444. updateBefore( { renderer } ) {
  24445. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  24446. this.textureNeedsUpdate = false;
  24447. //
  24448. if ( this.autoResize === true ) {
  24449. const pixelRatio = renderer.getPixelRatio();
  24450. const size = renderer.getSize( _size$1 );
  24451. const effectiveWidth = size.width * pixelRatio;
  24452. const effectiveHeight = size.height * pixelRatio;
  24453. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  24454. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24455. this.textureNeedsUpdate = true;
  24456. }
  24457. }
  24458. //
  24459. let name = 'RTT';
  24460. if ( this.node.name ) {
  24461. name = this.node.name + ' [ ' + name + ' ]';
  24462. }
  24463. this._quadMesh.material.fragmentNode = this._rttNode;
  24464. this._quadMesh.name = name;
  24465. //
  24466. const currentRenderTarget = renderer.getRenderTarget();
  24467. renderer.setRenderTarget( this.renderTarget );
  24468. this._quadMesh.render( renderer );
  24469. renderer.setRenderTarget( currentRenderTarget );
  24470. }
  24471. clone() {
  24472. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  24473. newNode.sampler = this.sampler;
  24474. newNode.referenceNode = this;
  24475. return newNode;
  24476. }
  24477. }
  24478. /**
  24479. * TSL function for creating a RTT node.
  24480. *
  24481. * @tsl
  24482. * @function
  24483. * @param {Node} node - The node to render a texture with.
  24484. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24485. * @param {?number} [height=null] - The height of the internal render target.
  24486. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24487. * @returns {RTTNode}
  24488. */
  24489. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  24490. /**
  24491. * TSL function for converting nodes to textures nodes.
  24492. *
  24493. * @tsl
  24494. * @function
  24495. * @param {Node} node - The node to render a texture with.
  24496. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24497. * @param {?number} [height=null] - The height of the internal render target.
  24498. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24499. * @returns {RTTNode}
  24500. */
  24501. const convertToTexture = ( node, ...params ) => {
  24502. if ( node.isSampleNode || node.isTextureNode ) return node;
  24503. if ( node.isPassNode ) return node.getTextureNode();
  24504. return rtt( node, ...params );
  24505. };
  24506. /**
  24507. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  24508. * depth value and the camera's inverse projection matrix.
  24509. *
  24510. * @tsl
  24511. * @function
  24512. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  24513. * @param {Node<float>} depth - The fragment's depth value.
  24514. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24515. * @return {Node<vec3>} The fragments position in view space.
  24516. */
  24517. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  24518. let clipSpacePosition;
  24519. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  24520. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  24521. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  24522. } else {
  24523. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  24524. }
  24525. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  24526. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  24527. } );
  24528. /**
  24529. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  24530. * and the camera's projection matrix
  24531. *
  24532. * @tsl
  24533. * @function
  24534. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  24535. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  24536. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  24537. */
  24538. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  24539. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  24540. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  24541. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  24542. } );
  24543. /**
  24544. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  24545. * target is available or if flat surface normals are required.
  24546. *
  24547. * @tsl
  24548. * @function
  24549. * @param {Node<vec2>} uv - The texture coordinate.
  24550. * @param {DepthTexture} depthTexture - The depth texture.
  24551. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24552. * @return {Node<vec3>} The computed normal vector.
  24553. */
  24554. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  24555. const size = textureSize( textureLoad( depthTexture ) );
  24556. const p = ivec2( uv.mul( size ) ).toVar();
  24557. const c0 = textureLoad( depthTexture, p ).toVar();
  24558. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  24559. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  24560. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  24561. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  24562. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  24563. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  24564. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  24565. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  24566. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  24567. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  24568. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  24569. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  24570. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  24571. 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 ) ) );
  24572. 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 ) ) );
  24573. return normalize( cross( dpdx, dpdy ) );
  24574. } );
  24575. /**
  24576. * Class representing a node that samples a value using a provided callback function.
  24577. *
  24578. * @extends Node
  24579. */
  24580. class SampleNode extends Node {
  24581. /**
  24582. * Returns the type of the node.
  24583. *
  24584. * @type {string}
  24585. * @readonly
  24586. * @static
  24587. */
  24588. static get type() {
  24589. return 'SampleNode';
  24590. }
  24591. /**
  24592. * Creates an instance of SampleNode.
  24593. *
  24594. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24595. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  24596. */
  24597. constructor( callback, uvNode = null ) {
  24598. super();
  24599. this.callback = callback;
  24600. /**
  24601. * Represents the texture coordinates.
  24602. *
  24603. * @type {?Node<vec2|vec3>}
  24604. * @default null
  24605. */
  24606. this.uvNode = uvNode;
  24607. /**
  24608. * This flag can be used for type testing.
  24609. *
  24610. * @type {boolean}
  24611. * @readonly
  24612. * @default true
  24613. */
  24614. this.isSampleNode = true;
  24615. }
  24616. /**
  24617. * Sets up the node by sampling with the default UV accessor.
  24618. *
  24619. * @returns {Node} The result of the callback function when called with the UV node.
  24620. */
  24621. setup() {
  24622. return this.sample( uv$1() );
  24623. }
  24624. /**
  24625. * Calls the callback function with the provided UV node.
  24626. *
  24627. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  24628. * @returns {Node} The result of the callback function.
  24629. */
  24630. sample( uv ) {
  24631. return this.callback( uv );
  24632. }
  24633. }
  24634. /**
  24635. * Helper function to create a SampleNode wrapped as a node object.
  24636. *
  24637. * @function
  24638. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24639. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  24640. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  24641. */
  24642. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  24643. /**
  24644. * EventNode is a node that executes a callback during specific update phases.
  24645. *
  24646. * @augments Node
  24647. */
  24648. class EventNode extends Node {
  24649. static get type() {
  24650. return 'EventNode';
  24651. }
  24652. /**
  24653. * Creates an EventNode.
  24654. *
  24655. * @param {string} eventType - The type of event
  24656. * @param {Function} callback - The callback to execute on update.
  24657. */
  24658. constructor( eventType, callback ) {
  24659. super( 'void' );
  24660. this.eventType = eventType;
  24661. this.callback = callback;
  24662. if ( eventType === EventNode.OBJECT ) {
  24663. this.updateType = NodeUpdateType.OBJECT;
  24664. } else if ( eventType === EventNode.MATERIAL ) {
  24665. this.updateType = NodeUpdateType.RENDER;
  24666. }
  24667. }
  24668. update( frame ) {
  24669. this.callback( frame );
  24670. }
  24671. }
  24672. EventNode.OBJECT = 'object';
  24673. EventNode.MATERIAL = 'material';
  24674. /**
  24675. * Helper to create an EventNode and add it to the stack.
  24676. *
  24677. * @param {string} type - The event type.
  24678. * @param {Function} callback - The callback function.
  24679. * @returns {EventNode}
  24680. */
  24681. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  24682. /**
  24683. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  24684. *
  24685. * 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.
  24686. *
  24687. * @param {Function} callback - The callback function.
  24688. * @returns {EventNode}
  24689. */
  24690. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  24691. /**
  24692. * Creates an event that triggers a function when the first object that uses the material is rendered.
  24693. *
  24694. * 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.
  24695. *
  24696. * @param {Function} callback - The callback function.
  24697. * @returns {EventNode}
  24698. */
  24699. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  24700. /**
  24701. * This special type of instanced buffer attribute is intended for compute shaders.
  24702. * In earlier three.js versions it was only possible to update attribute data
  24703. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24704. * new material system and renderer it is now possible to use compute shaders
  24705. * to compute the data for an attribute more efficiently on the GPU.
  24706. *
  24707. * The idea is to create an instance of this class and provide it as an input
  24708. * to {@link StorageBufferNode}.
  24709. *
  24710. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24711. *
  24712. * @augments InstancedBufferAttribute
  24713. */
  24714. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24715. /**
  24716. * Constructs a new storage instanced buffer attribute.
  24717. *
  24718. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24719. * The subsequent parameters are then obsolete.
  24720. * @param {number} itemSize - The item size.
  24721. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24722. */
  24723. constructor( count, itemSize, typeClass = Float32Array ) {
  24724. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24725. super( array, itemSize );
  24726. /**
  24727. * This flag can be used for type testing.
  24728. *
  24729. * @type {boolean}
  24730. * @readonly
  24731. * @default true
  24732. */
  24733. this.isStorageInstancedBufferAttribute = true;
  24734. }
  24735. }
  24736. /**
  24737. * This special type of buffer attribute is intended for compute shaders.
  24738. * In earlier three.js versions it was only possible to update attribute data
  24739. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24740. * new material system and renderer it is now possible to use compute shaders
  24741. * to compute the data for an attribute more efficiently on the GPU.
  24742. *
  24743. * The idea is to create an instance of this class and provide it as an input
  24744. * to {@link StorageBufferNode}.
  24745. *
  24746. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24747. *
  24748. * @augments BufferAttribute
  24749. */
  24750. class StorageBufferAttribute extends BufferAttribute {
  24751. /**
  24752. * Constructs a new storage buffer attribute.
  24753. *
  24754. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24755. * The subsequent parameters are then obsolete.
  24756. * @param {number} itemSize - The item size.
  24757. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24758. */
  24759. constructor( count, itemSize, typeClass = Float32Array ) {
  24760. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24761. super( array, itemSize );
  24762. /**
  24763. * This flag can be used for type testing.
  24764. *
  24765. * @type {boolean}
  24766. * @readonly
  24767. * @default true
  24768. */
  24769. this.isStorageBufferAttribute = true;
  24770. }
  24771. }
  24772. /**
  24773. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  24774. *
  24775. * @tsl
  24776. * @function
  24777. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24778. * @param {string|Struct} [type='float'] - The data type.
  24779. * @returns {StorageBufferNode}
  24780. */
  24781. const attributeArray = ( count, type = 'float' ) => {
  24782. let itemSize, typedArray;
  24783. if ( type.isStruct === true ) {
  24784. itemSize = type.layout.getLength();
  24785. typedArray = getTypedArrayFromType( 'float' );
  24786. } else {
  24787. itemSize = getLengthFromType( type );
  24788. typedArray = getTypedArrayFromType( type );
  24789. }
  24790. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  24791. const node = storage( buffer, type, count );
  24792. return node;
  24793. };
  24794. /**
  24795. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  24796. *
  24797. * @tsl
  24798. * @function
  24799. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24800. * @param {string|Struct} [type='float'] - The data type.
  24801. * @returns {StorageBufferNode}
  24802. */
  24803. const instancedArray = ( count, type = 'float' ) => {
  24804. let itemSize, typedArray;
  24805. if ( type.isStruct === true ) {
  24806. itemSize = type.layout.getLength();
  24807. typedArray = getTypedArrayFromType( 'float' );
  24808. } else {
  24809. itemSize = getLengthFromType( type );
  24810. typedArray = getTypedArrayFromType( type );
  24811. }
  24812. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  24813. const node = storage( buffer, type, count );
  24814. return node;
  24815. };
  24816. /**
  24817. * A node for representing the uv coordinates of points.
  24818. *
  24819. * Can only be used with a WebGL backend. In WebGPU, point
  24820. * primitives always have the size of one pixel and can thus
  24821. * can't be used as sprite-like objects that display textures.
  24822. *
  24823. * @augments Node
  24824. */
  24825. class PointUVNode extends Node {
  24826. static get type() {
  24827. return 'PointUVNode';
  24828. }
  24829. /**
  24830. * Constructs a new point uv node.
  24831. */
  24832. constructor() {
  24833. super( 'vec2' );
  24834. /**
  24835. * This flag can be used for type testing.
  24836. *
  24837. * @type {boolean}
  24838. * @readonly
  24839. * @default true
  24840. */
  24841. this.isPointUVNode = true;
  24842. }
  24843. generate( /*builder*/ ) {
  24844. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  24845. }
  24846. }
  24847. /**
  24848. * TSL object that represents the uv coordinates of points.
  24849. *
  24850. * @tsl
  24851. * @type {PointUVNode}
  24852. */
  24853. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  24854. const _e1 = /*@__PURE__*/ new Euler();
  24855. const _m1 = /*@__PURE__*/ new Matrix4();
  24856. /**
  24857. * This module allows access to a collection of scene properties. The following predefined TSL objects
  24858. * are available for easier use:
  24859. *
  24860. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  24861. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  24862. * - `backgroundRotation`: A node that represents the scene's background rotation.
  24863. *
  24864. * @augments Node
  24865. */
  24866. class SceneNode extends Node {
  24867. static get type() {
  24868. return 'SceneNode';
  24869. }
  24870. /**
  24871. * Constructs a new scene node.
  24872. *
  24873. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  24874. * @param {?Scene} [scene=null] - A reference to the scene.
  24875. */
  24876. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  24877. super();
  24878. /**
  24879. * The scope defines the type of scene property that is accessed.
  24880. *
  24881. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  24882. */
  24883. this.scope = scope;
  24884. /**
  24885. * A reference to the scene that is going to be accessed.
  24886. *
  24887. * @type {?Scene}
  24888. * @default null
  24889. */
  24890. this.scene = scene;
  24891. }
  24892. /**
  24893. * Depending on the scope, the method returns a different type of node that represents
  24894. * the respective scene property.
  24895. *
  24896. * @param {NodeBuilder} builder - The current node builder.
  24897. * @return {Node} The output node.
  24898. */
  24899. setup( builder ) {
  24900. const scope = this.scope;
  24901. const scene = this.scene !== null ? this.scene : builder.scene;
  24902. let output;
  24903. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  24904. output = reference( 'backgroundBlurriness', 'float', scene );
  24905. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  24906. output = reference( 'backgroundIntensity', 'float', scene );
  24907. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  24908. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24909. const background = scene.background;
  24910. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  24911. _e1.copy( scene.backgroundRotation );
  24912. // accommodate left-handed frame
  24913. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  24914. _m1.makeRotationFromEuler( _e1 );
  24915. } else {
  24916. _m1.identity();
  24917. }
  24918. return _m1;
  24919. } );
  24920. } else {
  24921. error( 'SceneNode: Unknown scope:', scope );
  24922. }
  24923. return output;
  24924. }
  24925. }
  24926. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  24927. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  24928. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  24929. /**
  24930. * TSL object that represents the scene's background blurriness.
  24931. *
  24932. * @tsl
  24933. * @type {SceneNode}
  24934. */
  24935. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  24936. /**
  24937. * TSL object that represents the scene's background intensity.
  24938. *
  24939. * @tsl
  24940. * @type {SceneNode}
  24941. */
  24942. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  24943. /**
  24944. * TSL object that represents the scene's background rotation.
  24945. *
  24946. * @tsl
  24947. * @type {SceneNode}
  24948. */
  24949. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  24950. /**
  24951. * This special version of a texture node can be used to
  24952. * write data into a storage texture with a compute shader.
  24953. *
  24954. * ```js
  24955. * const storageTexture = new THREE.StorageTexture( width, height );
  24956. *
  24957. * const computeTexture = Fn( ( { storageTexture } ) => {
  24958. *
  24959. * const posX = instanceIndex.mod( width );
  24960. * const posY = instanceIndex.div( width );
  24961. * const indexUV = uvec2( posX, posY );
  24962. *
  24963. * // generate RGB values
  24964. *
  24965. * const r = 1;
  24966. * const g = 1;
  24967. * const b = 1;
  24968. *
  24969. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  24970. *
  24971. * } );
  24972. *
  24973. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  24974. * renderer.computeAsync( computeNode );
  24975. * ```
  24976. *
  24977. * This node can only be used with a WebGPU backend.
  24978. *
  24979. * @augments TextureNode
  24980. */
  24981. class StorageTextureNode extends TextureNode {
  24982. static get type() {
  24983. return 'StorageTextureNode';
  24984. }
  24985. /**
  24986. * Constructs a new storage texture node.
  24987. *
  24988. * @param {StorageTexture} value - The storage texture.
  24989. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24990. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24991. */
  24992. constructor( value, uvNode, storeNode = null ) {
  24993. super( value, uvNode );
  24994. /**
  24995. * The value node that should be stored in the texture.
  24996. *
  24997. * @type {?Node}
  24998. * @default null
  24999. */
  25000. this.storeNode = storeNode;
  25001. /**
  25002. * This flag can be used for type testing.
  25003. *
  25004. * @type {boolean}
  25005. * @readonly
  25006. * @default true
  25007. */
  25008. this.isStorageTextureNode = true;
  25009. /**
  25010. * The access type of the texture node.
  25011. *
  25012. * @type {string}
  25013. * @default 'writeOnly'
  25014. */
  25015. this.access = NodeAccess.WRITE_ONLY;
  25016. }
  25017. /**
  25018. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  25019. *
  25020. * @param {NodeBuilder} builder - The current node builder.
  25021. * @return {string} The input type.
  25022. */
  25023. getInputType( /*builder*/ ) {
  25024. return 'storageTexture';
  25025. }
  25026. setup( builder ) {
  25027. super.setup( builder );
  25028. const properties = builder.getNodeProperties( this );
  25029. properties.storeNode = this.storeNode;
  25030. return properties;
  25031. }
  25032. /**
  25033. * Defines the node access.
  25034. *
  25035. * @param {string} value - The node access.
  25036. * @return {StorageTextureNode} A reference to this node.
  25037. */
  25038. setAccess( value ) {
  25039. this.access = value;
  25040. return this;
  25041. }
  25042. /**
  25043. * Generates the code snippet of the storage node. If no `storeNode`
  25044. * is defined, the texture node is generated as normal texture.
  25045. *
  25046. * @param {NodeBuilder} builder - The current node builder.
  25047. * @param {string} output - The current output.
  25048. * @return {string} The generated code snippet.
  25049. */
  25050. generate( builder, output ) {
  25051. let snippet;
  25052. if ( this.storeNode !== null ) {
  25053. snippet = this.generateStore( builder );
  25054. } else {
  25055. snippet = super.generate( builder, output );
  25056. }
  25057. return snippet;
  25058. }
  25059. /**
  25060. * Convenience method for configuring a read/write node access.
  25061. *
  25062. * @return {StorageTextureNode} A reference to this node.
  25063. */
  25064. toReadWrite() {
  25065. return this.setAccess( NodeAccess.READ_WRITE );
  25066. }
  25067. /**
  25068. * Convenience method for configuring a read-only node access.
  25069. *
  25070. * @return {StorageTextureNode} A reference to this node.
  25071. */
  25072. toReadOnly() {
  25073. return this.setAccess( NodeAccess.READ_ONLY );
  25074. }
  25075. /**
  25076. * Convenience method for configuring a write-only node access.
  25077. *
  25078. * @return {StorageTextureNode} A reference to this node.
  25079. */
  25080. toWriteOnly() {
  25081. return this.setAccess( NodeAccess.WRITE_ONLY );
  25082. }
  25083. /**
  25084. * Generates the code snippet of the storage texture node.
  25085. *
  25086. * @param {NodeBuilder} builder - The current node builder.
  25087. */
  25088. generateStore( builder ) {
  25089. const properties = builder.getNodeProperties( this );
  25090. const { uvNode, storeNode, depthNode } = properties;
  25091. const textureProperty = super.generate( builder, 'property' );
  25092. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  25093. const storeSnippet = storeNode.build( builder, 'vec4' );
  25094. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  25095. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  25096. builder.addLineFlowCode( snippet, this );
  25097. }
  25098. clone() {
  25099. const newNode = super.clone();
  25100. newNode.storeNode = this.storeNode;
  25101. return newNode;
  25102. }
  25103. }
  25104. /**
  25105. * TSL function for creating a storage texture node.
  25106. *
  25107. * @tsl
  25108. * @function
  25109. * @param {StorageTexture} value - The storage texture.
  25110. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  25111. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25112. * @returns {StorageTextureNode}
  25113. */
  25114. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  25115. /**
  25116. * TODO: Explain difference to `storageTexture()`.
  25117. *
  25118. * @tsl
  25119. * @function
  25120. * @param {StorageTexture} value - The storage texture.
  25121. * @param {Node<vec2|vec3>} uvNode - The uv node.
  25122. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  25123. * @returns {StorageTextureNode}
  25124. */
  25125. const textureStore = ( value, uvNode, storeNode ) => {
  25126. const node = storageTexture( value, uvNode, storeNode );
  25127. if ( storeNode !== null ) node.toStack();
  25128. return node;
  25129. };
  25130. const normal = Fn( ( { texture, uv } ) => {
  25131. const epsilon = 0.0001;
  25132. const ret = vec3().toVar();
  25133. If( uv.x.lessThan( epsilon ), () => {
  25134. ret.assign( vec3( 1, 0, 0 ) );
  25135. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  25136. ret.assign( vec3( 0, 1, 0 ) );
  25137. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  25138. ret.assign( vec3( 0, 0, 1 ) );
  25139. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  25140. ret.assign( vec3( -1, 0, 0 ) );
  25141. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  25142. ret.assign( vec3( 0, -1, 0 ) );
  25143. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  25144. ret.assign( vec3( 0, 0, -1 ) );
  25145. } ).Else( () => {
  25146. const step = 0.01;
  25147. 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 );
  25148. 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 );
  25149. 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 );
  25150. ret.assign( vec3( x, y, z ) );
  25151. } );
  25152. return ret.normalize();
  25153. } );
  25154. /**
  25155. * This type of uniform node represents a 3D texture.
  25156. *
  25157. * @augments TextureNode
  25158. */
  25159. class Texture3DNode extends TextureNode {
  25160. static get type() {
  25161. return 'Texture3DNode';
  25162. }
  25163. /**
  25164. * Constructs a new 3D texture node.
  25165. *
  25166. * @param {Data3DTexture} value - The 3D texture.
  25167. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25168. * @param {?Node<int>} [levelNode=null] - The level node.
  25169. */
  25170. constructor( value, uvNode = null, levelNode = null ) {
  25171. super( value, uvNode, levelNode );
  25172. /**
  25173. * This flag can be used for type testing.
  25174. *
  25175. * @type {boolean}
  25176. * @readonly
  25177. * @default true
  25178. */
  25179. this.isTexture3DNode = true;
  25180. }
  25181. /**
  25182. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  25183. *
  25184. * @param {NodeBuilder} builder - The current node builder.
  25185. * @return {string} The input type.
  25186. */
  25187. getInputType( /*builder*/ ) {
  25188. return 'texture3D';
  25189. }
  25190. /**
  25191. * Returns a default uv node which is in context of 3D textures a three-dimensional
  25192. * uv node.
  25193. *
  25194. * @return {Node<vec3>} The default uv node.
  25195. */
  25196. getDefaultUV() {
  25197. return vec3( 0.5, 0.5, 0.5 );
  25198. }
  25199. /**
  25200. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  25201. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  25202. *
  25203. * @param {boolean} value - The update toggle.
  25204. */
  25205. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  25206. /**
  25207. * Overwrites the default implementation to return the unmodified uv node.
  25208. *
  25209. * @param {NodeBuilder} builder - The current node builder.
  25210. * @param {Node} uvNode - The uv node to setup.
  25211. * @return {Node} The unmodified uv node.
  25212. */
  25213. setupUV( builder, uvNode ) {
  25214. const texture = this.value;
  25215. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  25216. if ( this.sampler ) {
  25217. uvNode = uvNode.flipY();
  25218. } else {
  25219. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  25220. }
  25221. }
  25222. return uvNode;
  25223. }
  25224. /**
  25225. * Generates the uv code snippet.
  25226. *
  25227. * @param {NodeBuilder} builder - The current node builder.
  25228. * @param {Node} uvNode - The uv node to generate code for.
  25229. * @return {string} The generated code snippet.
  25230. */
  25231. generateUV( builder, uvNode ) {
  25232. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  25233. }
  25234. /**
  25235. * Generates the offset code snippet.
  25236. *
  25237. * @param {NodeBuilder} builder - The current node builder.
  25238. * @param {Node} offsetNode - The offset node to generate code for.
  25239. * @return {string} The generated code snippet.
  25240. */
  25241. generateOffset( builder, offsetNode ) {
  25242. return offsetNode.build( builder, 'ivec3' );
  25243. }
  25244. /**
  25245. * TODO.
  25246. *
  25247. * @param {Node<vec3>} uvNode - The uv node .
  25248. * @return {Node<vec3>} TODO.
  25249. */
  25250. normal( uvNode ) {
  25251. return normal( { texture: this, uv: uvNode } );
  25252. }
  25253. }
  25254. /**
  25255. * TSL function for creating a 3D texture node.
  25256. *
  25257. * @tsl
  25258. * @function
  25259. * @param {Data3DTexture} value - The 3D texture.
  25260. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25261. * @param {?Node<int>} [levelNode=null] - The level node.
  25262. * @returns {Texture3DNode}
  25263. */
  25264. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  25265. /**
  25266. * A special type of reference node that allows to link values in
  25267. * `userData` fields to node objects.
  25268. * ```js
  25269. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  25270. *
  25271. * const material = new THREE.SpriteNodeMaterial();
  25272. * material.rotationNode = userData( 'rotation', 'float' );
  25273. * ```
  25274. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  25275. * will automatically be updated when the `rotation` user data field changes.
  25276. *
  25277. * @augments ReferenceNode
  25278. */
  25279. class UserDataNode extends ReferenceNode {
  25280. static get type() {
  25281. return 'UserDataNode';
  25282. }
  25283. /**
  25284. * Constructs a new user data node.
  25285. *
  25286. * @param {string} property - The property name that should be referenced by the node.
  25287. * @param {string} inputType - The node data type of the reference.
  25288. * @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.
  25289. */
  25290. constructor( property, inputType, userData = null ) {
  25291. super( property, inputType, userData );
  25292. /**
  25293. * A reference to the `userData` object. If not provided, the `userData`
  25294. * property of the 3D object that uses the node material is evaluated.
  25295. *
  25296. * @type {?Object}
  25297. * @default null
  25298. */
  25299. this.userData = userData;
  25300. }
  25301. /**
  25302. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  25303. * `userData` field.
  25304. *
  25305. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  25306. * @return {Object} A reference to the `userData` field.
  25307. */
  25308. updateReference( state ) {
  25309. this.reference = this.userData !== null ? this.userData : state.object.userData;
  25310. return this.reference;
  25311. }
  25312. }
  25313. /**
  25314. * TSL function for creating a user data node.
  25315. *
  25316. * @tsl
  25317. * @function
  25318. * @param {string} name - The property name that should be referenced by the node.
  25319. * @param {string} inputType - The node data type of the reference.
  25320. * @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.
  25321. * @returns {UserDataNode}
  25322. */
  25323. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  25324. const _objectData = new WeakMap();
  25325. /**
  25326. * A node for representing motion or velocity vectors. Foundation
  25327. * for advanced post processing effects like motion blur or TRAA.
  25328. *
  25329. * The node keeps track of the model, view and projection matrices
  25330. * of the previous frame and uses them to compute offsets in NDC space.
  25331. * These offsets represent the final velocity.
  25332. *
  25333. * @augments TempNode
  25334. */
  25335. class VelocityNode extends TempNode {
  25336. static get type() {
  25337. return 'VelocityNode';
  25338. }
  25339. /**
  25340. * Constructs a new vertex color node.
  25341. */
  25342. constructor() {
  25343. super( 'vec2' );
  25344. /**
  25345. * The current projection matrix.
  25346. *
  25347. * @type {?Matrix4}
  25348. * @default null
  25349. */
  25350. this.projectionMatrix = null;
  25351. /**
  25352. * Overwritten since velocity nodes are updated per object.
  25353. *
  25354. * @type {string}
  25355. * @default 'object'
  25356. */
  25357. this.updateType = NodeUpdateType.OBJECT;
  25358. /**
  25359. * Overwritten since velocity nodes save data after the update.
  25360. *
  25361. * @type {string}
  25362. * @default 'object'
  25363. */
  25364. this.updateAfterType = NodeUpdateType.OBJECT;
  25365. /**
  25366. * Uniform node representing the previous model matrix in world space.
  25367. *
  25368. * @type {UniformNode<mat4>}
  25369. * @default null
  25370. */
  25371. this.previousModelWorldMatrix = uniform( new Matrix4() );
  25372. /**
  25373. * Uniform node representing the previous projection matrix.
  25374. *
  25375. * @type {UniformNode<mat4>}
  25376. * @default null
  25377. */
  25378. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  25379. /**
  25380. * Uniform node representing the previous view matrix.
  25381. *
  25382. * @type {UniformNode<mat4>}
  25383. * @default null
  25384. */
  25385. this.previousCameraViewMatrix = uniform( new Matrix4() );
  25386. }
  25387. /**
  25388. * Sets the given projection matrix.
  25389. *
  25390. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  25391. */
  25392. setProjectionMatrix( projectionMatrix ) {
  25393. this.projectionMatrix = projectionMatrix;
  25394. }
  25395. /**
  25396. * Updates velocity specific uniforms.
  25397. *
  25398. * @param {NodeFrame} frame - A reference to the current node frame.
  25399. */
  25400. update( { frameId, camera, object } ) {
  25401. const previousModelMatrix = getPreviousMatrix( object );
  25402. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  25403. //
  25404. const cameraData = getData( camera );
  25405. if ( cameraData.frameId !== frameId ) {
  25406. cameraData.frameId = frameId;
  25407. if ( cameraData.previousProjectionMatrix === undefined ) {
  25408. cameraData.previousProjectionMatrix = new Matrix4();
  25409. cameraData.previousCameraViewMatrix = new Matrix4();
  25410. cameraData.currentProjectionMatrix = new Matrix4();
  25411. cameraData.currentCameraViewMatrix = new Matrix4();
  25412. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25413. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  25414. } else {
  25415. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  25416. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  25417. }
  25418. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25419. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  25420. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  25421. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  25422. }
  25423. }
  25424. /**
  25425. * Overwritten to updated velocity specific uniforms.
  25426. *
  25427. * @param {NodeFrame} frame - A reference to the current node frame.
  25428. */
  25429. updateAfter( { object } ) {
  25430. getPreviousMatrix( object ).copy( object.matrixWorld );
  25431. }
  25432. /**
  25433. * Implements the velocity computation based on the previous and current vertex data.
  25434. *
  25435. * @param {NodeBuilder} builder - A reference to the current node builder.
  25436. * @return {Node<vec2>} The motion vector.
  25437. */
  25438. setup( /*builder*/ ) {
  25439. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  25440. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  25441. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25442. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  25443. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  25444. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  25445. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  25446. return velocity;
  25447. }
  25448. }
  25449. function getData( object ) {
  25450. let objectData = _objectData.get( object );
  25451. if ( objectData === undefined ) {
  25452. objectData = {};
  25453. _objectData.set( object, objectData );
  25454. }
  25455. return objectData;
  25456. }
  25457. function getPreviousMatrix( object, index = 0 ) {
  25458. const objectData = getData( object );
  25459. let matrix = objectData[ index ];
  25460. if ( matrix === undefined ) {
  25461. objectData[ index ] = matrix = new Matrix4();
  25462. objectData[ index ].copy( object.matrixWorld );
  25463. }
  25464. return matrix;
  25465. }
  25466. /**
  25467. * TSL object that represents the velocity of a render pass.
  25468. *
  25469. * @tsl
  25470. * @type {VelocityNode}
  25471. */
  25472. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  25473. /**
  25474. * Computes a grayscale value for the given RGB color value.
  25475. *
  25476. * @tsl
  25477. * @function
  25478. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  25479. * @return {Node<vec3>} The grayscale color.
  25480. */
  25481. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25482. return luminance( color.rgb );
  25483. } );
  25484. /**
  25485. * Super-saturates or desaturates the given RGB color.
  25486. *
  25487. * @tsl
  25488. * @function
  25489. * @param {Node<vec3>} color - The input color.
  25490. * @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.
  25491. * @return {Node<vec3>} The saturated color.
  25492. */
  25493. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25494. return adjustment.mix( luminance( color.rgb ), color.rgb );
  25495. } );
  25496. /**
  25497. * Selectively enhance the intensity of less saturated RGB colors. Can result
  25498. * in a more natural and visually appealing image with enhanced color depth
  25499. * compared to {@link ColorAdjustment#saturation}.
  25500. *
  25501. * @tsl
  25502. * @function
  25503. * @param {Node<vec3>} color - The input color.
  25504. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  25505. * @return {Node<vec3>} The updated color.
  25506. */
  25507. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25508. const average = add( color.r, color.g, color.b ).div( 3.0 );
  25509. const mx = color.r.max( color.g.max( color.b ) );
  25510. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  25511. return mix( color.rgb, mx, amt );
  25512. } );
  25513. /**
  25514. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  25515. *
  25516. * @tsl
  25517. * @function
  25518. * @param {Node<vec3>} color - The input color.
  25519. * @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.
  25520. * @return {Node<vec3>} The updated color.
  25521. */
  25522. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25523. const k = vec3( 0.57735, 0.57735, 0.57735 );
  25524. const cosAngle = adjustment.cos();
  25525. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  25526. } );
  25527. /**
  25528. * Computes the luminance for the given RGB color value.
  25529. *
  25530. * @tsl
  25531. * @function
  25532. * @param {Node<vec3>} color - The color value to compute the luminance for.
  25533. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  25534. * @return {Node<float>} The luminance.
  25535. */
  25536. const luminance = (
  25537. color,
  25538. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  25539. ) => dot( color, luminanceCoefficients );
  25540. /**
  25541. * Color Decision List (CDL) v1.2
  25542. *
  25543. * Compact representation of color grading information, defined by slope, offset, power, and
  25544. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  25545. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  25546. *
  25547. * @tsl
  25548. * @function
  25549. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  25550. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  25551. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  25552. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  25553. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  25554. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  25555. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  25556. *
  25557. * References:
  25558. * - ASC CDL v1.2
  25559. * - {@link https://blender.stackexchange.com/a/55239/43930}
  25560. * - {@link https://docs.acescentral.com/specifications/acescc/}
  25561. */
  25562. const cdl = /*@__PURE__*/ Fn( ( [
  25563. color,
  25564. slope = vec3( 1 ),
  25565. offset = vec3( 0 ),
  25566. power = vec3( 1 ),
  25567. saturation = float( 1 ),
  25568. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  25569. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  25570. ] ) => {
  25571. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  25572. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  25573. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  25574. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  25575. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  25576. const pv = v.pow( power ).toVar();
  25577. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  25578. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  25579. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  25580. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  25581. return vec4( v.rgb, color.a );
  25582. } );
  25583. /**
  25584. * Represents a posterize effect which reduces the number of colors
  25585. * in an image, resulting in a more blocky and stylized appearance.
  25586. *
  25587. * @augments TempNode
  25588. */
  25589. class PosterizeNode extends TempNode {
  25590. static get type() {
  25591. return 'PosterizeNode';
  25592. }
  25593. /**
  25594. * Constructs a new posterize node.
  25595. *
  25596. * @param {Node} sourceNode - The input color.
  25597. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25598. */
  25599. constructor( sourceNode, stepsNode ) {
  25600. super();
  25601. /**
  25602. * The input color.
  25603. *
  25604. * @type {Node}
  25605. */
  25606. this.sourceNode = sourceNode;
  25607. /**
  25608. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25609. *
  25610. * @type {Node}
  25611. */
  25612. this.stepsNode = stepsNode;
  25613. }
  25614. setup() {
  25615. const { sourceNode, stepsNode } = this;
  25616. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  25617. }
  25618. }
  25619. /**
  25620. * TSL function for creating a posterize node.
  25621. *
  25622. * @tsl
  25623. * @function
  25624. * @param {Node} sourceNode - The input color.
  25625. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25626. * @returns {PosterizeNode}
  25627. */
  25628. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  25629. const _size = /*@__PURE__*/ new Vector2();
  25630. /**
  25631. * Represents the texture of a pass node.
  25632. *
  25633. * @augments TextureNode
  25634. */
  25635. class PassTextureNode extends TextureNode {
  25636. static get type() {
  25637. return 'PassTextureNode';
  25638. }
  25639. /**
  25640. * Constructs a new pass texture node.
  25641. *
  25642. * @param {PassNode} passNode - The pass node.
  25643. * @param {Texture} texture - The output texture.
  25644. */
  25645. constructor( passNode, texture ) {
  25646. super( texture );
  25647. /**
  25648. * A reference to the pass node.
  25649. *
  25650. * @type {PassNode}
  25651. */
  25652. this.passNode = passNode;
  25653. this.setUpdateMatrix( false );
  25654. }
  25655. setup( builder ) {
  25656. this.passNode.build( builder );
  25657. return super.setup( builder );
  25658. }
  25659. clone() {
  25660. return new this.constructor( this.passNode, this.value );
  25661. }
  25662. }
  25663. /**
  25664. * An extension of `PassTextureNode` which allows to manage more than one
  25665. * internal texture. Relevant for the `getPreviousTexture()` related API.
  25666. *
  25667. * @augments PassTextureNode
  25668. */
  25669. class PassMultipleTextureNode extends PassTextureNode {
  25670. static get type() {
  25671. return 'PassMultipleTextureNode';
  25672. }
  25673. /**
  25674. * Constructs a new pass texture node.
  25675. *
  25676. * @param {PassNode} passNode - The pass node.
  25677. * @param {string} textureName - The output texture name.
  25678. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  25679. */
  25680. constructor( passNode, textureName, previousTexture = false ) {
  25681. // null is passed to the super call since this class does not
  25682. // use an external texture for rendering pass data into. Instead
  25683. // the texture is managed by the pass node itself
  25684. super( passNode, null );
  25685. /**
  25686. * The output texture name.
  25687. *
  25688. * @type {string}
  25689. */
  25690. this.textureName = textureName;
  25691. /**
  25692. * Whether previous frame data should be used or not.
  25693. *
  25694. * @type {boolean}
  25695. */
  25696. this.previousTexture = previousTexture;
  25697. }
  25698. /**
  25699. * Updates the texture reference of this node.
  25700. */
  25701. updateTexture() {
  25702. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  25703. }
  25704. setup( builder ) {
  25705. this.updateTexture();
  25706. return super.setup( builder );
  25707. }
  25708. clone() {
  25709. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  25710. newNode.uvNode = this.uvNode;
  25711. newNode.levelNode = this.levelNode;
  25712. newNode.biasNode = this.biasNode;
  25713. newNode.sampler = this.sampler;
  25714. newNode.depthNode = this.depthNode;
  25715. newNode.compareNode = this.compareNode;
  25716. newNode.gradNode = this.gradNode;
  25717. newNode.offsetNode = this.offsetNode;
  25718. return newNode;
  25719. }
  25720. }
  25721. /**
  25722. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  25723. * This pass produces a render for the given scene and camera and can provide multiple outputs
  25724. * via MRT for further processing.
  25725. *
  25726. * ```js
  25727. * const postProcessing = new PostProcessing( renderer );
  25728. *
  25729. * const scenePass = pass( scene, camera );
  25730. *
  25731. * postProcessing.outputNode = scenePass;
  25732. * ```
  25733. *
  25734. * @augments TempNode
  25735. */
  25736. class PassNode extends TempNode {
  25737. static get type() {
  25738. return 'PassNode';
  25739. }
  25740. /**
  25741. * Constructs a new pass node.
  25742. *
  25743. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  25744. * @param {Scene} scene - A reference to the scene.
  25745. * @param {Camera} camera - A reference to the camera.
  25746. * @param {Object} options - Options for the internal render target.
  25747. */
  25748. constructor( scope, scene, camera, options = {} ) {
  25749. super( 'vec4' );
  25750. /**
  25751. * The scope of the pass. The scope determines whether the node outputs color or depth.
  25752. *
  25753. * @type {('color'|'depth')}
  25754. */
  25755. this.scope = scope;
  25756. /**
  25757. * A reference to the scene.
  25758. *
  25759. * @type {Scene}
  25760. */
  25761. this.scene = scene;
  25762. /**
  25763. * A reference to the camera.
  25764. *
  25765. * @type {Camera}
  25766. */
  25767. this.camera = camera;
  25768. /**
  25769. * Options for the internal render target.
  25770. *
  25771. * @type {Object}
  25772. */
  25773. this.options = options;
  25774. /**
  25775. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  25776. *
  25777. * @private
  25778. * @type {number}
  25779. * @default 1
  25780. */
  25781. this._pixelRatio = 1;
  25782. /**
  25783. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  25784. * @private
  25785. * @type {number}
  25786. * @default 1
  25787. */
  25788. this._width = 1;
  25789. /**
  25790. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  25791. * @private
  25792. * @type {number}
  25793. * @default 1
  25794. */
  25795. this._height = 1;
  25796. const depthTexture = new DepthTexture();
  25797. depthTexture.isRenderTargetTexture = true;
  25798. //depthTexture.type = FloatType;
  25799. depthTexture.name = 'depth';
  25800. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  25801. renderTarget.texture.name = 'output';
  25802. renderTarget.depthTexture = depthTexture;
  25803. /**
  25804. * The pass's render target.
  25805. *
  25806. * @type {RenderTarget}
  25807. */
  25808. this.renderTarget = renderTarget;
  25809. /**
  25810. * A dictionary holding the internal result textures.
  25811. *
  25812. * @private
  25813. * @type {Object<string, Texture>}
  25814. */
  25815. this._textures = {
  25816. output: renderTarget.texture,
  25817. depth: depthTexture
  25818. };
  25819. /**
  25820. * A dictionary holding the internal texture nodes.
  25821. *
  25822. * @private
  25823. * @type {Object<string, TextureNode>}
  25824. */
  25825. this._textureNodes = {};
  25826. /**
  25827. * A dictionary holding the internal depth nodes.
  25828. *
  25829. * @private
  25830. * @type {Object}
  25831. */
  25832. this._linearDepthNodes = {};
  25833. /**
  25834. * A dictionary holding the internal viewZ nodes.
  25835. *
  25836. * @private
  25837. * @type {Object}
  25838. */
  25839. this._viewZNodes = {};
  25840. /**
  25841. * A dictionary holding the texture data of the previous frame.
  25842. * Used for computing velocity/motion vectors.
  25843. *
  25844. * @private
  25845. * @type {Object<string, Texture>}
  25846. */
  25847. this._previousTextures = {};
  25848. /**
  25849. * A dictionary holding the texture nodes of the previous frame.
  25850. * Used for computing velocity/motion vectors.
  25851. *
  25852. * @private
  25853. * @type {Object<string, TextureNode>}
  25854. */
  25855. this._previousTextureNodes = {};
  25856. /**
  25857. * The `near` property of the camera as a uniform.
  25858. *
  25859. * @private
  25860. * @type {UniformNode}
  25861. */
  25862. this._cameraNear = uniform( 0 );
  25863. /**
  25864. * The `far` property of the camera as a uniform.
  25865. *
  25866. * @private
  25867. * @type {UniformNode}
  25868. */
  25869. this._cameraFar = uniform( 0 );
  25870. /**
  25871. * A MRT node configuring the MRT settings.
  25872. *
  25873. * @private
  25874. * @type {?MRTNode}
  25875. * @default null
  25876. */
  25877. this._mrt = null;
  25878. /**
  25879. * Layer object for configuring the camera that is used
  25880. * to produce the pass.
  25881. *
  25882. * @private
  25883. * @type {?Layers}
  25884. * @default null
  25885. */
  25886. this._layers = null;
  25887. /**
  25888. * Scales the resolution of the internal render target.
  25889. *
  25890. * @private
  25891. * @type {number}
  25892. * @default 1
  25893. */
  25894. this._resolutionScale = 1;
  25895. /**
  25896. * Custom viewport definition.
  25897. *
  25898. * @private
  25899. * @type {?Vector4}
  25900. * @default null
  25901. */
  25902. this._viewport = null;
  25903. /**
  25904. * Custom scissor definition.
  25905. *
  25906. * @private
  25907. * @type {?Vector4}
  25908. * @default null
  25909. */
  25910. this._scissor = null;
  25911. /**
  25912. * This flag can be used for type testing.
  25913. *
  25914. * @type {boolean}
  25915. * @readonly
  25916. * @default true
  25917. */
  25918. this.isPassNode = true;
  25919. /**
  25920. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  25921. * scene once per frame in its {@link PassNode#updateBefore} method.
  25922. *
  25923. * @type {string}
  25924. * @default 'frame'
  25925. */
  25926. this.updateBeforeType = NodeUpdateType.FRAME;
  25927. /**
  25928. * This flag is used for global cache.
  25929. *
  25930. * @type {boolean}
  25931. * @default true
  25932. */
  25933. this.global = true;
  25934. }
  25935. /**
  25936. * Sets the resolution scale for the pass.
  25937. * The resolution scale is a factor that is multiplied with the renderer's width and height.
  25938. *
  25939. * @param {number} resolutionScale - The resolution scale to set. A value of `1` means full resolution.
  25940. * @return {PassNode} A reference to this pass.
  25941. */
  25942. setResolutionScale( resolutionScale ) {
  25943. this._resolutionScale = resolutionScale;
  25944. return this;
  25945. }
  25946. /**
  25947. * Gets the current resolution scale of the pass.
  25948. *
  25949. * @return {number} The current resolution scale. A value of `1` means full resolution.
  25950. */
  25951. getResolutionScale() {
  25952. return this._resolutionScale;
  25953. }
  25954. /**
  25955. * Sets the resolution for the pass.
  25956. * The resolution is a factor that is multiplied with the renderer's width and height.
  25957. *
  25958. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  25959. * @return {PassNode} A reference to this pass.
  25960. * @deprecated since r181. Use {@link PassNode#setResolutionScale `setResolutionScale()`} instead.
  25961. */
  25962. setResolution( resolution ) { // @deprecated, r181
  25963. warn( 'PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead.' );
  25964. return this.setResolutionScale( resolution );
  25965. }
  25966. /**
  25967. * Gets the current resolution of the pass.
  25968. *
  25969. * @return {number} The current resolution. A value of `1` means full resolution.
  25970. * @deprecated since r181. Use {@link PassNode#getResolutionScale `getResolutionScale()`} instead.
  25971. */
  25972. getResolution() { // @deprecated, r181
  25973. warn( 'PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead.' );
  25974. return this.getResolutionScale();
  25975. }
  25976. /**
  25977. * Sets the layer configuration that should be used when rendering the pass.
  25978. *
  25979. * @param {Layers} layers - The layers object to set.
  25980. * @return {PassNode} A reference to this pass.
  25981. */
  25982. setLayers( layers ) {
  25983. this._layers = layers;
  25984. return this;
  25985. }
  25986. /**
  25987. * Gets the current layer configuration of the pass.
  25988. *
  25989. * @return {?Layers} .
  25990. */
  25991. getLayers() {
  25992. return this._layers;
  25993. }
  25994. /**
  25995. * Sets the given MRT node to setup MRT for this pass.
  25996. *
  25997. * @param {MRTNode} mrt - The MRT object.
  25998. * @return {PassNode} A reference to this pass.
  25999. */
  26000. setMRT( mrt ) {
  26001. this._mrt = mrt;
  26002. return this;
  26003. }
  26004. /**
  26005. * Returns the current MRT node.
  26006. *
  26007. * @return {MRTNode} The current MRT node.
  26008. */
  26009. getMRT() {
  26010. return this._mrt;
  26011. }
  26012. /**
  26013. * Returns the texture for the given output name.
  26014. *
  26015. * @param {string} name - The output name to get the texture for.
  26016. * @return {Texture} The texture.
  26017. */
  26018. getTexture( name ) {
  26019. let texture = this._textures[ name ];
  26020. if ( texture === undefined ) {
  26021. const refTexture = this.renderTarget.texture;
  26022. texture = refTexture.clone();
  26023. texture.name = name;
  26024. this._textures[ name ] = texture;
  26025. this.renderTarget.textures.push( texture );
  26026. }
  26027. return texture;
  26028. }
  26029. /**
  26030. * Returns the texture holding the data of the previous frame for the given output name.
  26031. *
  26032. * @param {string} name - The output name to get the texture for.
  26033. * @return {Texture} The texture holding the data of the previous frame.
  26034. */
  26035. getPreviousTexture( name ) {
  26036. let texture = this._previousTextures[ name ];
  26037. if ( texture === undefined ) {
  26038. texture = this.getTexture( name ).clone();
  26039. this._previousTextures[ name ] = texture;
  26040. }
  26041. return texture;
  26042. }
  26043. /**
  26044. * Switches current and previous textures for the given output name.
  26045. *
  26046. * @param {string} name - The output name.
  26047. */
  26048. toggleTexture( name ) {
  26049. const prevTexture = this._previousTextures[ name ];
  26050. if ( prevTexture !== undefined ) {
  26051. const texture = this._textures[ name ];
  26052. const index = this.renderTarget.textures.indexOf( texture );
  26053. this.renderTarget.textures[ index ] = prevTexture;
  26054. this._textures[ name ] = prevTexture;
  26055. this._previousTextures[ name ] = texture;
  26056. this._textureNodes[ name ].updateTexture();
  26057. this._previousTextureNodes[ name ].updateTexture();
  26058. }
  26059. }
  26060. /**
  26061. * Returns the texture node for the given output name.
  26062. *
  26063. * @param {string} [name='output'] - The output name to get the texture node for.
  26064. * @return {TextureNode} The texture node.
  26065. */
  26066. getTextureNode( name = 'output' ) {
  26067. let textureNode = this._textureNodes[ name ];
  26068. if ( textureNode === undefined ) {
  26069. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  26070. textureNode.updateTexture();
  26071. this._textureNodes[ name ] = textureNode;
  26072. }
  26073. return textureNode;
  26074. }
  26075. /**
  26076. * Returns the previous texture node for the given output name.
  26077. *
  26078. * @param {string} [name='output'] - The output name to get the previous texture node for.
  26079. * @return {TextureNode} The previous texture node.
  26080. */
  26081. getPreviousTextureNode( name = 'output' ) {
  26082. let textureNode = this._previousTextureNodes[ name ];
  26083. if ( textureNode === undefined ) {
  26084. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  26085. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  26086. textureNode.updateTexture();
  26087. this._previousTextureNodes[ name ] = textureNode;
  26088. }
  26089. return textureNode;
  26090. }
  26091. /**
  26092. * Returns a viewZ node of this pass.
  26093. *
  26094. * @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.
  26095. * @return {Node} The viewZ node.
  26096. */
  26097. getViewZNode( name = 'depth' ) {
  26098. let viewZNode = this._viewZNodes[ name ];
  26099. if ( viewZNode === undefined ) {
  26100. const cameraNear = this._cameraNear;
  26101. const cameraFar = this._cameraFar;
  26102. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  26103. }
  26104. return viewZNode;
  26105. }
  26106. /**
  26107. * Returns a linear depth node of this pass.
  26108. *
  26109. * @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.
  26110. * @return {Node} The linear depth node.
  26111. */
  26112. getLinearDepthNode( name = 'depth' ) {
  26113. let linearDepthNode = this._linearDepthNodes[ name ];
  26114. if ( linearDepthNode === undefined ) {
  26115. const cameraNear = this._cameraNear;
  26116. const cameraFar = this._cameraFar;
  26117. const viewZNode = this.getViewZNode( name );
  26118. // TODO: just if ( builder.camera.isPerspectiveCamera )
  26119. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  26120. }
  26121. return linearDepthNode;
  26122. }
  26123. /**
  26124. * Precompiles the pass.
  26125. *
  26126. * Note that this method must be called after the pass configuration is complete.
  26127. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  26128. *
  26129. * @async
  26130. * @param {Renderer} renderer - The renderer.
  26131. * @return {Promise} A Promise that resolves when the compile has been finished.
  26132. * @see {@link Renderer#compileAsync}
  26133. */
  26134. async compileAsync( renderer ) {
  26135. const currentRenderTarget = renderer.getRenderTarget();
  26136. const currentMRT = renderer.getMRT();
  26137. renderer.setRenderTarget( this.renderTarget );
  26138. renderer.setMRT( this._mrt );
  26139. await renderer.compileAsync( this.scene, this.camera );
  26140. renderer.setRenderTarget( currentRenderTarget );
  26141. renderer.setMRT( currentMRT );
  26142. }
  26143. setup( { renderer } ) {
  26144. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  26145. this.renderTarget.texture.type = renderer.getColorBufferType();
  26146. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  26147. }
  26148. updateBefore( frame ) {
  26149. const { renderer } = frame;
  26150. const { scene } = this;
  26151. let camera;
  26152. let pixelRatio;
  26153. const outputRenderTarget = renderer.getOutputRenderTarget();
  26154. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  26155. pixelRatio = 1;
  26156. camera = renderer.xr.getCamera();
  26157. renderer.xr.updateCamera( camera );
  26158. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  26159. } else {
  26160. camera = this.camera;
  26161. pixelRatio = renderer.getPixelRatio();
  26162. renderer.getSize( _size );
  26163. }
  26164. this._pixelRatio = pixelRatio;
  26165. this.setSize( _size.width, _size.height );
  26166. const currentRenderTarget = renderer.getRenderTarget();
  26167. const currentMRT = renderer.getMRT();
  26168. const currentMask = camera.layers.mask;
  26169. this._cameraNear.value = camera.near;
  26170. this._cameraFar.value = camera.far;
  26171. if ( this._layers !== null ) {
  26172. camera.layers.mask = this._layers.mask;
  26173. }
  26174. for ( const name in this._previousTextures ) {
  26175. this.toggleTexture( name );
  26176. }
  26177. renderer.setRenderTarget( this.renderTarget );
  26178. renderer.setMRT( this._mrt );
  26179. const currentSceneName = scene.name;
  26180. scene.name = this.name ? this.name : scene.name;
  26181. renderer.render( scene, camera );
  26182. scene.name = currentSceneName;
  26183. renderer.setRenderTarget( currentRenderTarget );
  26184. renderer.setMRT( currentMRT );
  26185. camera.layers.mask = currentMask;
  26186. }
  26187. /**
  26188. * Sets the size of the pass's render target. Honors the pixel ratio.
  26189. *
  26190. * @param {number} width - The width to set.
  26191. * @param {number} height - The height to set.
  26192. */
  26193. setSize( width, height ) {
  26194. this._width = width;
  26195. this._height = height;
  26196. const effectiveWidth = this._width * this._pixelRatio * this._resolutionScale;
  26197. const effectiveHeight = this._height * this._pixelRatio * this._resolutionScale;
  26198. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  26199. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  26200. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  26201. }
  26202. /**
  26203. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  26204. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26205. * with `null` as the single argument.
  26206. *
  26207. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  26208. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  26209. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  26210. * @param {number} width - The width of the scissor box in logical pixel unit.
  26211. * @param {number} height - The height of the scissor box in logical pixel unit.
  26212. */
  26213. setScissor( x, y, width, height ) {
  26214. if ( x === null ) {
  26215. this._scissor = null;
  26216. } else {
  26217. if ( this._scissor === null ) this._scissor = new Vector4();
  26218. if ( x.isVector4 ) {
  26219. this._scissor.copy( x );
  26220. } else {
  26221. this._scissor.set( x, y, width, height );
  26222. }
  26223. this._scissor.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26224. }
  26225. }
  26226. /**
  26227. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  26228. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  26229. * with `null` as the single argument.
  26230. *
  26231. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26232. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  26233. * @param {number} width - The width of the viewport in logical pixel unit.
  26234. * @param {number} height - The height of the viewport in logical pixel unit.
  26235. */
  26236. setViewport( x, y, width, height ) {
  26237. if ( x === null ) {
  26238. this._viewport = null;
  26239. } else {
  26240. if ( this._viewport === null ) this._viewport = new Vector4();
  26241. if ( x.isVector4 ) {
  26242. this._viewport.copy( x );
  26243. } else {
  26244. this._viewport.set( x, y, width, height );
  26245. }
  26246. this._viewport.multiplyScalar( this._pixelRatio * this._resolutionScale ).floor();
  26247. }
  26248. }
  26249. /**
  26250. * Sets the pixel ratio the pass's render target and updates the size.
  26251. *
  26252. * @param {number} pixelRatio - The pixel ratio to set.
  26253. */
  26254. setPixelRatio( pixelRatio ) {
  26255. this._pixelRatio = pixelRatio;
  26256. this.setSize( this._width, this._height );
  26257. }
  26258. /**
  26259. * Frees internal resources. Should be called when the node is no longer in use.
  26260. */
  26261. dispose() {
  26262. this.renderTarget.dispose();
  26263. }
  26264. }
  26265. /**
  26266. * @static
  26267. * @type {'color'}
  26268. * @default 'color'
  26269. */
  26270. PassNode.COLOR = 'color';
  26271. /**
  26272. * @static
  26273. * @type {'depth'}
  26274. * @default 'depth'
  26275. */
  26276. PassNode.DEPTH = 'depth';
  26277. /**
  26278. * TSL function for creating a pass node.
  26279. *
  26280. * @tsl
  26281. * @function
  26282. * @param {Scene} scene - A reference to the scene.
  26283. * @param {Camera} camera - A reference to the camera.
  26284. * @param {Object} options - Options for the internal render target.
  26285. * @returns {PassNode}
  26286. */
  26287. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  26288. /**
  26289. * TSL function for creating a pass texture node.
  26290. *
  26291. * @tsl
  26292. * @function
  26293. * @param {PassNode} pass - The pass node.
  26294. * @param {Texture} texture - The output texture.
  26295. * @returns {PassTextureNode}
  26296. */
  26297. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  26298. /**
  26299. * TSL function for creating a depth pass node.
  26300. *
  26301. * @tsl
  26302. * @function
  26303. * @param {Scene} scene - A reference to the scene.
  26304. * @param {Camera} camera - A reference to the camera.
  26305. * @param {Object} options - Options for the internal render target.
  26306. * @returns {PassNode}
  26307. */
  26308. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  26309. /**
  26310. * Represents a render pass for producing a toon outline effect on compatible objects.
  26311. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  26312. * will receive the outline.
  26313. *
  26314. * ```js
  26315. * const postProcessing = new PostProcessing( renderer );
  26316. *
  26317. * const scenePass = toonOutlinePass( scene, camera );
  26318. *
  26319. * postProcessing.outputNode = scenePass;
  26320. * ```
  26321. * @augments PassNode
  26322. */
  26323. class ToonOutlinePassNode extends PassNode {
  26324. static get type() {
  26325. return 'ToonOutlinePassNode';
  26326. }
  26327. /**
  26328. * Constructs a new outline pass node.
  26329. *
  26330. * @param {Scene} scene - A reference to the scene.
  26331. * @param {Camera} camera - A reference to the camera.
  26332. * @param {Node} colorNode - Defines the outline's color.
  26333. * @param {Node} thicknessNode - Defines the outline's thickness.
  26334. * @param {Node} alphaNode - Defines the outline's alpha.
  26335. */
  26336. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  26337. super( PassNode.COLOR, scene, camera );
  26338. /**
  26339. * Defines the outline's color.
  26340. *
  26341. * @type {Node}
  26342. */
  26343. this.colorNode = colorNode;
  26344. /**
  26345. * Defines the outline's thickness.
  26346. *
  26347. * @type {Node}
  26348. */
  26349. this.thicknessNode = thicknessNode;
  26350. /**
  26351. * Defines the outline's alpha.
  26352. *
  26353. * @type {Node}
  26354. */
  26355. this.alphaNode = alphaNode;
  26356. /**
  26357. * An internal material cache.
  26358. *
  26359. * @private
  26360. * @type {WeakMap<Material, NodeMaterial>}
  26361. */
  26362. this._materialCache = new WeakMap();
  26363. }
  26364. updateBefore( frame ) {
  26365. const { renderer } = frame;
  26366. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26367. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  26368. // only render outline for supported materials
  26369. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  26370. if ( material.wireframe === false ) {
  26371. const outlineMaterial = this._getOutlineMaterial( material );
  26372. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  26373. }
  26374. }
  26375. // default
  26376. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  26377. } );
  26378. super.updateBefore( frame );
  26379. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26380. }
  26381. /**
  26382. * Creates the material used for outline rendering.
  26383. *
  26384. * @private
  26385. * @return {NodeMaterial} The outline material.
  26386. */
  26387. _createMaterial() {
  26388. const material = new NodeMaterial();
  26389. material.isMeshToonOutlineMaterial = true;
  26390. material.name = 'Toon_Outline';
  26391. material.side = BackSide;
  26392. // vertex node
  26393. const outlineNormal = normalLocal.negate();
  26394. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  26395. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  26396. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  26397. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  26398. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  26399. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  26400. // color node
  26401. material.colorNode = vec4( this.colorNode, this.alphaNode );
  26402. return material;
  26403. }
  26404. /**
  26405. * For the given toon material, this method returns a corresponding
  26406. * outline material.
  26407. *
  26408. * @private
  26409. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  26410. * @return {NodeMaterial} The outline material.
  26411. */
  26412. _getOutlineMaterial( originalMaterial ) {
  26413. let outlineMaterial = this._materialCache.get( originalMaterial );
  26414. if ( outlineMaterial === undefined ) {
  26415. outlineMaterial = this._createMaterial();
  26416. this._materialCache.set( originalMaterial, outlineMaterial );
  26417. }
  26418. return outlineMaterial;
  26419. }
  26420. }
  26421. /**
  26422. * TSL function for creating a toon outline pass node.
  26423. *
  26424. * @tsl
  26425. * @function
  26426. * @param {Scene} scene - A reference to the scene.
  26427. * @param {Camera} camera - A reference to the camera.
  26428. * @param {Color} color - Defines the outline's color.
  26429. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  26430. * @param {number} [alpha=1] - Defines the outline's alpha.
  26431. * @returns {ToonOutlinePassNode}
  26432. */
  26433. 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 ) ) );
  26434. /**
  26435. * Linear tone mapping, exposure only.
  26436. *
  26437. * @tsl
  26438. * @function
  26439. * @param {Node<vec3>} color - The color that should be tone mapped.
  26440. * @param {Node<float>} exposure - The exposure.
  26441. * @return {Node<vec3>} The tone mapped color.
  26442. */
  26443. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26444. return color.mul( exposure ).clamp();
  26445. } ).setLayout( {
  26446. name: 'linearToneMapping',
  26447. type: 'vec3',
  26448. inputs: [
  26449. { name: 'color', type: 'vec3' },
  26450. { name: 'exposure', type: 'float' }
  26451. ]
  26452. } );
  26453. /**
  26454. * Reinhard tone mapping.
  26455. *
  26456. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  26457. *
  26458. * @tsl
  26459. * @function
  26460. * @param {Node<vec3>} color - The color that should be tone mapped.
  26461. * @param {Node<float>} exposure - The exposure.
  26462. * @return {Node<vec3>} The tone mapped color.
  26463. */
  26464. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26465. color = color.mul( exposure );
  26466. return color.div( color.add( 1.0 ) ).clamp();
  26467. } ).setLayout( {
  26468. name: 'reinhardToneMapping',
  26469. type: 'vec3',
  26470. inputs: [
  26471. { name: 'color', type: 'vec3' },
  26472. { name: 'exposure', type: 'float' }
  26473. ]
  26474. } );
  26475. /**
  26476. * Cineon tone mapping.
  26477. *
  26478. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  26479. *
  26480. * @tsl
  26481. * @function
  26482. * @param {Node<vec3>} color - The color that should be tone mapped.
  26483. * @param {Node<float>} exposure - The exposure.
  26484. * @return {Node<vec3>} The tone mapped color.
  26485. */
  26486. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26487. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  26488. color = color.mul( exposure );
  26489. color = color.sub( 0.004 ).max( 0.0 );
  26490. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  26491. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  26492. return a.div( b ).pow( 2.2 );
  26493. } ).setLayout( {
  26494. name: 'cineonToneMapping',
  26495. type: 'vec3',
  26496. inputs: [
  26497. { name: 'color', type: 'vec3' },
  26498. { name: 'exposure', type: 'float' }
  26499. ]
  26500. } );
  26501. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  26502. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26503. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  26504. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  26505. return a.div( b );
  26506. } );
  26507. /**
  26508. * ACESFilmic tone mapping.
  26509. *
  26510. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  26511. *
  26512. * @tsl
  26513. * @function
  26514. * @param {Node<vec3>} color - The color that should be tone mapped.
  26515. * @param {Node<float>} exposure - The exposure.
  26516. * @return {Node<vec3>} The tone mapped color.
  26517. */
  26518. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26519. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  26520. const ACESInputMat = mat3(
  26521. 0.59719, 0.35458, 0.04823,
  26522. 0.07600, 0.90834, 0.01566,
  26523. 0.02840, 0.13383, 0.83777
  26524. );
  26525. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  26526. const ACESOutputMat = mat3(
  26527. 1.60475, -0.53108, -0.07367,
  26528. -0.10208, 1.10813, -605e-5,
  26529. -327e-5, -0.07276, 1.07602
  26530. );
  26531. color = color.mul( exposure ).div( 0.6 );
  26532. color = ACESInputMat.mul( color );
  26533. // Apply RRT and ODT
  26534. color = RRTAndODTFit( color );
  26535. color = ACESOutputMat.mul( color );
  26536. // Clamp to [0, 1]
  26537. return color.clamp();
  26538. } ).setLayout( {
  26539. name: 'acesFilmicToneMapping',
  26540. type: 'vec3',
  26541. inputs: [
  26542. { name: 'color', type: 'vec3' },
  26543. { name: 'exposure', type: 'float' }
  26544. ]
  26545. } );
  26546. 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 ) );
  26547. 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 ) );
  26548. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26549. const x = vec3( x_immutable ).toVar();
  26550. const x2 = vec3( x.mul( x ) ).toVar();
  26551. const x4 = vec3( x2.mul( x2 ) ).toVar();
  26552. 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 ) ) ) );
  26553. } );
  26554. /**
  26555. * AgX tone mapping.
  26556. *
  26557. * @tsl
  26558. * @function
  26559. * @param {Node<vec3>} color - The color that should be tone mapped.
  26560. * @param {Node<float>} exposure - The exposure.
  26561. * @return {Node<vec3>} The tone mapped color.
  26562. */
  26563. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26564. const colortone = vec3( color ).toVar();
  26565. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  26566. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  26567. const AgxMinEv = float( -12.47393 );
  26568. const AgxMaxEv = float( 4.026069 );
  26569. colortone.mulAssign( exposure );
  26570. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  26571. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  26572. colortone.assign( max$1( colortone, 1e-10 ) );
  26573. colortone.assign( log2( colortone ) );
  26574. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  26575. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26576. colortone.assign( agxDefaultContrastApprox( colortone ) );
  26577. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  26578. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  26579. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  26580. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26581. return colortone;
  26582. } ).setLayout( {
  26583. name: 'agxToneMapping',
  26584. type: 'vec3',
  26585. inputs: [
  26586. { name: 'color', type: 'vec3' },
  26587. { name: 'exposure', type: 'float' }
  26588. ]
  26589. } );
  26590. /**
  26591. * Neutral tone mapping.
  26592. *
  26593. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  26594. *
  26595. * @tsl
  26596. * @function
  26597. * @param {Node<vec3>} color - The color that should be tone mapped.
  26598. * @param {Node<float>} exposure - The exposure.
  26599. * @return {Node<vec3>} The tone mapped color.
  26600. */
  26601. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26602. const StartCompression = float( 0.8 - 0.04 );
  26603. const Desaturation = float( 0.15 );
  26604. color = color.mul( exposure );
  26605. const x = min$1( color.r, min$1( color.g, color.b ) );
  26606. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  26607. color.subAssign( offset );
  26608. const peak = max$1( color.r, max$1( color.g, color.b ) );
  26609. If( peak.lessThan( StartCompression ), () => {
  26610. return color;
  26611. } );
  26612. const d = sub( 1, StartCompression );
  26613. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  26614. color.mulAssign( newPeak.div( peak ) );
  26615. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  26616. return mix( color, vec3( newPeak ), g );
  26617. } ).setLayout( {
  26618. name: 'neutralToneMapping',
  26619. type: 'vec3',
  26620. inputs: [
  26621. { name: 'color', type: 'vec3' },
  26622. { name: 'exposure', type: 'float' }
  26623. ]
  26624. } );
  26625. /**
  26626. * This class represents native code sections. It is the base
  26627. * class for modules like {@link FunctionNode} which allows to implement
  26628. * functions with native shader languages.
  26629. *
  26630. * @augments Node
  26631. */
  26632. class CodeNode extends Node {
  26633. static get type() {
  26634. return 'CodeNode';
  26635. }
  26636. /**
  26637. * Constructs a new code node.
  26638. *
  26639. * @param {string} [code=''] - The native code.
  26640. * @param {Array<Node>} [includes=[]] - An array of includes.
  26641. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26642. */
  26643. constructor( code = '', includes = [], language = '' ) {
  26644. super( 'code' );
  26645. /**
  26646. * This flag can be used for type testing.
  26647. *
  26648. * @type {boolean}
  26649. * @readonly
  26650. * @default true
  26651. */
  26652. this.isCodeNode = true;
  26653. /**
  26654. * This flag is used for global cache.
  26655. *
  26656. * @type {boolean}
  26657. * @default true
  26658. */
  26659. this.global = true;
  26660. /**
  26661. * The native code.
  26662. *
  26663. * @type {string}
  26664. * @default ''
  26665. */
  26666. this.code = code;
  26667. /**
  26668. * An array of includes
  26669. *
  26670. * @type {Array<Node>}
  26671. * @default []
  26672. */
  26673. this.includes = includes;
  26674. /**
  26675. * The used language.
  26676. *
  26677. * @type {('js'|'wgsl'|'glsl')}
  26678. * @default ''
  26679. */
  26680. this.language = language;
  26681. }
  26682. /**
  26683. * Sets the includes of this code node.
  26684. *
  26685. * @param {Array<Node>} includes - The includes to set.
  26686. * @return {CodeNode} A reference to this node.
  26687. */
  26688. setIncludes( includes ) {
  26689. this.includes = includes;
  26690. return this;
  26691. }
  26692. /**
  26693. * Returns the includes of this code node.
  26694. *
  26695. * @param {NodeBuilder} builder - The current node builder.
  26696. * @return {Array<Node>} The includes.
  26697. */
  26698. getIncludes( /*builder*/ ) {
  26699. return this.includes;
  26700. }
  26701. generate( builder ) {
  26702. const includes = this.getIncludes( builder );
  26703. for ( const include of includes ) {
  26704. include.build( builder );
  26705. }
  26706. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  26707. nodeCode.code = this.code;
  26708. return nodeCode.code;
  26709. }
  26710. serialize( data ) {
  26711. super.serialize( data );
  26712. data.code = this.code;
  26713. data.language = this.language;
  26714. }
  26715. deserialize( data ) {
  26716. super.deserialize( data );
  26717. this.code = data.code;
  26718. this.language = data.language;
  26719. }
  26720. }
  26721. /**
  26722. * TSL function for creating a code node.
  26723. *
  26724. * @tsl
  26725. * @function
  26726. * @param {string} [code] - The native code.
  26727. * @param {?Array<Node>} [includes=[]] - An array of includes.
  26728. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26729. * @returns {CodeNode}
  26730. */
  26731. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  26732. /**
  26733. * TSL function for creating a JS code node.
  26734. *
  26735. * @tsl
  26736. * @function
  26737. * @param {string} src - The native code.
  26738. * @param {Array<Node>} includes - An array of includes.
  26739. * @returns {CodeNode}
  26740. */
  26741. const js = ( src, includes ) => code( src, includes, 'js' );
  26742. /**
  26743. * TSL function for creating a WGSL code node.
  26744. *
  26745. * @tsl
  26746. * @function
  26747. * @param {string} src - The native code.
  26748. * @param {Array<Node>} includes - An array of includes.
  26749. * @returns {CodeNode}
  26750. */
  26751. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  26752. /**
  26753. * TSL function for creating a GLSL code node.
  26754. *
  26755. * @tsl
  26756. * @function
  26757. * @param {string} src - The native code.
  26758. * @param {Array<Node>} includes - An array of includes.
  26759. * @returns {CodeNode}
  26760. */
  26761. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  26762. /**
  26763. * This class represents a native shader function. It can be used to implement
  26764. * certain aspects of a node material with native shader code. There are two predefined
  26765. * TSL functions for easier usage.
  26766. *
  26767. * - `wgslFn`: Creates a WGSL function node.
  26768. * - `glslFn`: Creates a GLSL function node.
  26769. *
  26770. * A basic example with one include looks like so:
  26771. *
  26772. * ```js
  26773. * const desaturateWGSLFn = wgslFn( `
  26774. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  26775. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  26776. * return vec3<f32>( dot( lum, color ) );
  26777. * }`
  26778. *);
  26779. * const someWGSLFn = wgslFn( `
  26780. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  26781. * return desaturate( color );
  26782. * }
  26783. * `, [ desaturateWGSLFn ] );
  26784. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  26785. *```
  26786. * @augments CodeNode
  26787. */
  26788. class FunctionNode extends CodeNode {
  26789. static get type() {
  26790. return 'FunctionNode';
  26791. }
  26792. /**
  26793. * Constructs a new function node.
  26794. *
  26795. * @param {string} [code=''] - The native code.
  26796. * @param {Array<Node>} [includes=[]] - An array of includes.
  26797. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26798. */
  26799. constructor( code = '', includes = [], language = '' ) {
  26800. super( code, includes, language );
  26801. }
  26802. /**
  26803. * Returns the type of this function node.
  26804. *
  26805. * @param {NodeBuilder} builder - The current node builder.
  26806. * @return {string} The type.
  26807. */
  26808. getNodeType( builder ) {
  26809. return this.getNodeFunction( builder ).type;
  26810. }
  26811. /**
  26812. * Returns the type of a member of this function node.
  26813. *
  26814. * @param {NodeBuilder} builder - The current node builder.
  26815. * @param {string} name - The name of the member.
  26816. * @return {string} The type of the member.
  26817. */
  26818. getMemberType( builder, name ) {
  26819. const type = this.getNodeType( builder );
  26820. const structType = builder.getStructTypeNode( type );
  26821. return structType.getMemberType( builder, name );
  26822. }
  26823. /**
  26824. * Returns the inputs of this function node.
  26825. *
  26826. * @param {NodeBuilder} builder - The current node builder.
  26827. * @return {Array<NodeFunctionInput>} The inputs.
  26828. */
  26829. getInputs( builder ) {
  26830. return this.getNodeFunction( builder ).inputs;
  26831. }
  26832. /**
  26833. * Returns the node function for this function node.
  26834. *
  26835. * @param {NodeBuilder} builder - The current node builder.
  26836. * @return {NodeFunction} The node function.
  26837. */
  26838. getNodeFunction( builder ) {
  26839. const nodeData = builder.getDataFromNode( this );
  26840. let nodeFunction = nodeData.nodeFunction;
  26841. if ( nodeFunction === undefined ) {
  26842. nodeFunction = builder.parser.parseFunction( this.code );
  26843. nodeData.nodeFunction = nodeFunction;
  26844. }
  26845. return nodeFunction;
  26846. }
  26847. generate( builder, output ) {
  26848. super.generate( builder );
  26849. const nodeFunction = this.getNodeFunction( builder );
  26850. const name = nodeFunction.name;
  26851. const type = nodeFunction.type;
  26852. const nodeCode = builder.getCodeFromNode( this, type );
  26853. if ( name !== '' ) {
  26854. // use a custom property name
  26855. nodeCode.name = name;
  26856. }
  26857. const propertyName = builder.getPropertyName( nodeCode );
  26858. const code = this.getNodeFunction( builder ).getCode( propertyName );
  26859. nodeCode.code = code + '\n';
  26860. if ( output === 'property' ) {
  26861. return propertyName;
  26862. } else {
  26863. return builder.format( `${ propertyName }()`, type, output );
  26864. }
  26865. }
  26866. }
  26867. const nativeFn = ( code, includes = [], language = '' ) => {
  26868. for ( let i = 0; i < includes.length; i ++ ) {
  26869. const include = includes[ i ];
  26870. // TSL Function: glslFn, wgslFn
  26871. if ( typeof include === 'function' ) {
  26872. includes[ i ] = include.functionNode;
  26873. }
  26874. }
  26875. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  26876. const fn = ( ...params ) => functionNode.call( ...params );
  26877. fn.functionNode = functionNode;
  26878. return fn;
  26879. };
  26880. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  26881. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  26882. /**
  26883. * `ScriptableNode` uses this class to manage script inputs and outputs.
  26884. *
  26885. * @augments Node
  26886. */
  26887. class ScriptableValueNode extends Node {
  26888. static get type() {
  26889. return 'ScriptableValueNode';
  26890. }
  26891. /**
  26892. * Constructs a new scriptable node.
  26893. *
  26894. * @param {any} [value=null] - The value.
  26895. */
  26896. constructor( value = null ) {
  26897. super();
  26898. /**
  26899. * A reference to the value.
  26900. *
  26901. * @private
  26902. * @default null
  26903. */
  26904. this._value = value;
  26905. /**
  26906. * Depending on the type of `_value`, this property might cache parsed data.
  26907. *
  26908. * @private
  26909. * @default null
  26910. */
  26911. this._cache = null;
  26912. /**
  26913. * If this node represents an input, this property represents the input type.
  26914. *
  26915. * @type {?string}
  26916. * @default null
  26917. */
  26918. this.inputType = null;
  26919. /**
  26920. * If this node represents an output, this property represents the output type.
  26921. *
  26922. * @type {?string}
  26923. * @default null
  26924. */
  26925. this.outputType = null;
  26926. /**
  26927. * An event dispatcher for managing events.
  26928. *
  26929. * @type {EventDispatcher}
  26930. */
  26931. this.events = new EventDispatcher();
  26932. /**
  26933. * This flag can be used for type testing.
  26934. *
  26935. * @type {boolean}
  26936. * @readonly
  26937. * @default true
  26938. */
  26939. this.isScriptableValueNode = true;
  26940. }
  26941. /**
  26942. * Whether this node represents an output or not.
  26943. *
  26944. * @type {boolean}
  26945. * @readonly
  26946. * @default true
  26947. */
  26948. get isScriptableOutputNode() {
  26949. return this.outputType !== null;
  26950. }
  26951. set value( val ) {
  26952. if ( this._value === val ) return;
  26953. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  26954. URL.revokeObjectURL( this._cache );
  26955. this._cache = null;
  26956. }
  26957. this._value = val;
  26958. this.events.dispatchEvent( { type: 'change' } );
  26959. this.refresh();
  26960. }
  26961. /**
  26962. * The node's value.
  26963. *
  26964. * @type {any}
  26965. */
  26966. get value() {
  26967. return this._value;
  26968. }
  26969. /**
  26970. * Dispatches the `refresh` event.
  26971. */
  26972. refresh() {
  26973. this.events.dispatchEvent( { type: 'refresh' } );
  26974. }
  26975. /**
  26976. * The `value` property usually represents a node or even binary data in form of array buffers.
  26977. * In this case, this method tries to return the actual value behind the complex type.
  26978. *
  26979. * @return {any} The value.
  26980. */
  26981. getValue() {
  26982. const value = this.value;
  26983. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  26984. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  26985. } else if ( value && value.value !== null && value.value !== undefined && (
  26986. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  26987. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  26988. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  26989. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  26990. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  26991. ( this.inputType === 'Color' && value.value.isColor ) ||
  26992. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  26993. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  26994. ) ) {
  26995. return value.value;
  26996. }
  26997. return this._cache || value;
  26998. }
  26999. /**
  27000. * Overwritten since the node type is inferred from the value.
  27001. *
  27002. * @param {NodeBuilder} builder - The current node builder.
  27003. * @return {string} The node type.
  27004. */
  27005. getNodeType( builder ) {
  27006. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  27007. }
  27008. setup() {
  27009. return this.value && this.value.isNode ? this.value : float();
  27010. }
  27011. serialize( data ) {
  27012. super.serialize( data );
  27013. if ( this.value !== null ) {
  27014. if ( this.inputType === 'ArrayBuffer' ) {
  27015. data.value = arrayBufferToBase64( this.value );
  27016. } else {
  27017. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  27018. }
  27019. } else {
  27020. data.value = null;
  27021. }
  27022. data.inputType = this.inputType;
  27023. data.outputType = this.outputType;
  27024. }
  27025. deserialize( data ) {
  27026. super.deserialize( data );
  27027. let value = null;
  27028. if ( data.value !== null ) {
  27029. if ( data.inputType === 'ArrayBuffer' ) {
  27030. value = base64ToArrayBuffer( data.value );
  27031. } else if ( data.inputType === 'Texture' ) {
  27032. value = data.meta.textures[ data.value ];
  27033. } else {
  27034. value = data.meta.nodes[ data.value ] || null;
  27035. }
  27036. }
  27037. this.value = value;
  27038. this.inputType = data.inputType;
  27039. this.outputType = data.outputType;
  27040. }
  27041. }
  27042. /**
  27043. * TSL function for creating a scriptable value node.
  27044. *
  27045. * @tsl
  27046. * @function
  27047. * @param {any} [value] - The value.
  27048. * @returns {ScriptableValueNode}
  27049. */
  27050. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  27051. /**
  27052. * A Map-like data structure for managing resources of scriptable nodes.
  27053. *
  27054. * @augments Map
  27055. */
  27056. class Resources extends Map {
  27057. get( key, callback = null, ...params ) {
  27058. if ( this.has( key ) ) return super.get( key );
  27059. if ( callback !== null ) {
  27060. const value = callback( ...params );
  27061. this.set( key, value );
  27062. return value;
  27063. }
  27064. }
  27065. }
  27066. class Parameters {
  27067. constructor( scriptableNode ) {
  27068. this.scriptableNode = scriptableNode;
  27069. }
  27070. get parameters() {
  27071. return this.scriptableNode.parameters;
  27072. }
  27073. get layout() {
  27074. return this.scriptableNode.getLayout();
  27075. }
  27076. getInputLayout( id ) {
  27077. return this.scriptableNode.getInputLayout( id );
  27078. }
  27079. get( name ) {
  27080. const param = this.parameters[ name ];
  27081. const value = param ? param.getValue() : null;
  27082. return value;
  27083. }
  27084. }
  27085. /**
  27086. * Defines the resources (e.g. namespaces) of scriptable nodes.
  27087. *
  27088. * @type {Resources}
  27089. */
  27090. const ScriptableNodeResources = new Resources();
  27091. /**
  27092. * This type of node allows to implement nodes with custom scripts. The script
  27093. * section is represented as an instance of `CodeNode` written with JavaScript.
  27094. * The script itself must adhere to a specific structure.
  27095. *
  27096. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  27097. * - layout: The layout object defines the script's interface (inputs and outputs).
  27098. *
  27099. * ```js
  27100. * ScriptableNodeResources.set( 'TSL', TSL );
  27101. *
  27102. * const scriptableNode = scriptable( js( `
  27103. * layout = {
  27104. * outputType: 'node',
  27105. * elements: [
  27106. * { name: 'source', inputType: 'node' },
  27107. * ]
  27108. * };
  27109. *
  27110. * const { mul, oscSine } = TSL;
  27111. *
  27112. * function main() {
  27113. * const source = parameters.get( 'source' ) || float();
  27114. * return mul( source, oscSine() ) );
  27115. * }
  27116. *
  27117. * ` ) );
  27118. *
  27119. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  27120. *
  27121. * const material = new THREE.MeshBasicNodeMaterial();
  27122. * material.colorNode = scriptableNode;
  27123. * ```
  27124. *
  27125. * @augments Node
  27126. */
  27127. class ScriptableNode extends Node {
  27128. static get type() {
  27129. return 'ScriptableNode';
  27130. }
  27131. /**
  27132. * Constructs a new scriptable node.
  27133. *
  27134. * @param {?CodeNode} [codeNode=null] - The code node.
  27135. * @param {Object} [parameters={}] - The parameters definition.
  27136. */
  27137. constructor( codeNode = null, parameters = {} ) {
  27138. super();
  27139. /**
  27140. * The code node.
  27141. *
  27142. * @type {?CodeNode}
  27143. * @default null
  27144. */
  27145. this.codeNode = codeNode;
  27146. /**
  27147. * The parameters definition.
  27148. *
  27149. * @type {Object}
  27150. * @default {}
  27151. */
  27152. this.parameters = parameters;
  27153. this._local = new Resources();
  27154. this._output = scriptableValue( null );
  27155. this._outputs = {};
  27156. this._source = this.source;
  27157. this._method = null;
  27158. this._object = null;
  27159. this._value = null;
  27160. this._needsOutputUpdate = true;
  27161. this.onRefresh = this.onRefresh.bind( this );
  27162. /**
  27163. * This flag can be used for type testing.
  27164. *
  27165. * @type {boolean}
  27166. * @readonly
  27167. * @default true
  27168. */
  27169. this.isScriptableNode = true;
  27170. }
  27171. /**
  27172. * The source code of the scriptable node.
  27173. *
  27174. * @type {string}
  27175. */
  27176. get source() {
  27177. return this.codeNode ? this.codeNode.code : '';
  27178. }
  27179. /**
  27180. * Sets the reference of a local script variable.
  27181. *
  27182. * @param {string} name - The variable name.
  27183. * @param {Object} value - The reference to set.
  27184. * @return {Resources} The resource map
  27185. */
  27186. setLocal( name, value ) {
  27187. return this._local.set( name, value );
  27188. }
  27189. /**
  27190. * Gets the value of a local script variable.
  27191. *
  27192. * @param {string} name - The variable name.
  27193. * @return {Object} The value.
  27194. */
  27195. getLocal( name ) {
  27196. return this._local.get( name );
  27197. }
  27198. /**
  27199. * Event listener for the `refresh` event.
  27200. */
  27201. onRefresh() {
  27202. this._refresh();
  27203. }
  27204. /**
  27205. * Returns an input from the layout with the given id/name.
  27206. *
  27207. * @param {string} id - The id/name of the input.
  27208. * @return {Object} The element entry.
  27209. */
  27210. getInputLayout( id ) {
  27211. for ( const element of this.getLayout() ) {
  27212. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  27213. return element;
  27214. }
  27215. }
  27216. }
  27217. /**
  27218. * Returns an output from the layout with the given id/name.
  27219. *
  27220. * @param {string} id - The id/name of the output.
  27221. * @return {Object} The element entry.
  27222. */
  27223. getOutputLayout( id ) {
  27224. for ( const element of this.getLayout() ) {
  27225. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  27226. return element;
  27227. }
  27228. }
  27229. }
  27230. /**
  27231. * Defines a script output for the given name and value.
  27232. *
  27233. * @param {string} name - The name of the output.
  27234. * @param {Node} value - The node value.
  27235. * @return {ScriptableNode} A reference to this node.
  27236. */
  27237. setOutput( name, value ) {
  27238. const outputs = this._outputs;
  27239. if ( outputs[ name ] === undefined ) {
  27240. outputs[ name ] = scriptableValue( value );
  27241. } else {
  27242. outputs[ name ].value = value;
  27243. }
  27244. return this;
  27245. }
  27246. /**
  27247. * Returns a script output for the given name.
  27248. *
  27249. * @param {string} name - The name of the output.
  27250. * @return {ScriptableValueNode} The node value.
  27251. */
  27252. getOutput( name ) {
  27253. return this._outputs[ name ];
  27254. }
  27255. /**
  27256. * Returns a parameter for the given name
  27257. *
  27258. * @param {string} name - The name of the parameter.
  27259. * @return {ScriptableValueNode} The node value.
  27260. */
  27261. getParameter( name ) {
  27262. return this.parameters[ name ];
  27263. }
  27264. /**
  27265. * Sets a value for the given parameter name.
  27266. *
  27267. * @param {string} name - The parameter name.
  27268. * @param {any} value - The parameter value.
  27269. * @return {ScriptableNode} A reference to this node.
  27270. */
  27271. setParameter( name, value ) {
  27272. const parameters = this.parameters;
  27273. if ( value && value.isScriptableNode ) {
  27274. this.deleteParameter( name );
  27275. parameters[ name ] = value;
  27276. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  27277. } else if ( value && value.isScriptableValueNode ) {
  27278. this.deleteParameter( name );
  27279. parameters[ name ] = value;
  27280. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27281. } else if ( parameters[ name ] === undefined ) {
  27282. parameters[ name ] = scriptableValue( value );
  27283. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27284. } else {
  27285. parameters[ name ].value = value;
  27286. }
  27287. return this;
  27288. }
  27289. /**
  27290. * Returns the value of this node which is the value of
  27291. * the default output.
  27292. *
  27293. * @return {Node} The value.
  27294. */
  27295. getValue() {
  27296. return this.getDefaultOutput().getValue();
  27297. }
  27298. /**
  27299. * Deletes a parameter from the script.
  27300. *
  27301. * @param {string} name - The parameter to remove.
  27302. * @return {ScriptableNode} A reference to this node.
  27303. */
  27304. deleteParameter( name ) {
  27305. let valueNode = this.parameters[ name ];
  27306. if ( valueNode ) {
  27307. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27308. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  27309. }
  27310. return this;
  27311. }
  27312. /**
  27313. * Deletes all parameters from the script.
  27314. *
  27315. * @return {ScriptableNode} A reference to this node.
  27316. */
  27317. clearParameters() {
  27318. for ( const name of Object.keys( this.parameters ) ) {
  27319. this.deleteParameter( name );
  27320. }
  27321. this.needsUpdate = true;
  27322. return this;
  27323. }
  27324. /**
  27325. * Calls a function from the script.
  27326. *
  27327. * @param {string} name - The function name.
  27328. * @param {...any} params - A list of parameters.
  27329. * @return {any} The result of the function call.
  27330. */
  27331. call( name, ...params ) {
  27332. const object = this.getObject();
  27333. const method = object[ name ];
  27334. if ( typeof method === 'function' ) {
  27335. return method( ...params );
  27336. }
  27337. }
  27338. /**
  27339. * Asynchronously calls a function from the script.
  27340. *
  27341. * @param {string} name - The function name.
  27342. * @param {...any} params - A list of parameters.
  27343. * @return {Promise<any>} The result of the function call.
  27344. */
  27345. async callAsync( name, ...params ) {
  27346. const object = this.getObject();
  27347. const method = object[ name ];
  27348. if ( typeof method === 'function' ) {
  27349. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  27350. }
  27351. }
  27352. /**
  27353. * Overwritten since the node types is inferred from the script's output.
  27354. *
  27355. * @param {NodeBuilder} builder - The current node builder
  27356. * @return {string} The node type.
  27357. */
  27358. getNodeType( builder ) {
  27359. return this.getDefaultOutputNode().getNodeType( builder );
  27360. }
  27361. /**
  27362. * Refreshes the script node.
  27363. *
  27364. * @param {?string} [output=null] - An optional output.
  27365. */
  27366. refresh( output = null ) {
  27367. if ( output !== null ) {
  27368. this.getOutput( output ).refresh();
  27369. } else {
  27370. this._refresh();
  27371. }
  27372. }
  27373. /**
  27374. * Returns an object representation of the script.
  27375. *
  27376. * @return {Object} The result object.
  27377. */
  27378. getObject() {
  27379. if ( this.needsUpdate ) this.dispose();
  27380. if ( this._object !== null ) return this._object;
  27381. //
  27382. const refresh = () => this.refresh();
  27383. const setOutput = ( id, value ) => this.setOutput( id, value );
  27384. const parameters = new Parameters( this );
  27385. const THREE = ScriptableNodeResources.get( 'THREE' );
  27386. const TSL = ScriptableNodeResources.get( 'TSL' );
  27387. const method = this.getMethod();
  27388. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  27389. this._object = method( ...params );
  27390. const layout = this._object.layout;
  27391. if ( layout ) {
  27392. if ( layout.cache === false ) {
  27393. this._local.clear();
  27394. }
  27395. // default output
  27396. this._output.outputType = layout.outputType || null;
  27397. if ( Array.isArray( layout.elements ) ) {
  27398. for ( const element of layout.elements ) {
  27399. const id = element.id || element.name;
  27400. if ( element.inputType ) {
  27401. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  27402. this.getParameter( id ).inputType = element.inputType;
  27403. }
  27404. if ( element.outputType ) {
  27405. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  27406. this.getOutput( id ).outputType = element.outputType;
  27407. }
  27408. }
  27409. }
  27410. }
  27411. return this._object;
  27412. }
  27413. deserialize( data ) {
  27414. super.deserialize( data );
  27415. for ( const name in this.parameters ) {
  27416. let valueNode = this.parameters[ name ];
  27417. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27418. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  27419. }
  27420. }
  27421. /**
  27422. * Returns the layout of the script.
  27423. *
  27424. * @return {Object} The script's layout.
  27425. */
  27426. getLayout() {
  27427. return this.getObject().layout;
  27428. }
  27429. /**
  27430. * Returns default node output of the script.
  27431. *
  27432. * @return {Node} The default node output.
  27433. */
  27434. getDefaultOutputNode() {
  27435. const output = this.getDefaultOutput().value;
  27436. if ( output && output.isNode ) {
  27437. return output;
  27438. }
  27439. return float();
  27440. }
  27441. /**
  27442. * Returns default output of the script.
  27443. *
  27444. * @return {ScriptableValueNode} The default output.
  27445. */
  27446. getDefaultOutput() {
  27447. return this._exec()._output;
  27448. }
  27449. /**
  27450. * Returns a function created from the node's script.
  27451. *
  27452. * @return {Function} The function representing the node's code.
  27453. */
  27454. getMethod() {
  27455. if ( this.needsUpdate ) this.dispose();
  27456. if ( this._method !== null ) return this._method;
  27457. //
  27458. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  27459. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  27460. const properties = interfaceProps.join( ', ' );
  27461. const declarations = 'var ' + properties + '; var output = {};\n';
  27462. const returns = '\nreturn { ...output, ' + properties + ' };';
  27463. const code = declarations + this.codeNode.code + returns;
  27464. //
  27465. this._method = new Function( ...parametersProps, code );
  27466. return this._method;
  27467. }
  27468. /**
  27469. * Frees all internal resources.
  27470. */
  27471. dispose() {
  27472. if ( this._method === null ) return;
  27473. if ( this._object && typeof this._object.dispose === 'function' ) {
  27474. this._object.dispose();
  27475. }
  27476. this._method = null;
  27477. this._object = null;
  27478. this._source = null;
  27479. this._value = null;
  27480. this._needsOutputUpdate = true;
  27481. this._output.value = null;
  27482. this._outputs = {};
  27483. }
  27484. setup() {
  27485. return this.getDefaultOutputNode();
  27486. }
  27487. getCacheKey( force ) {
  27488. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  27489. for ( const param in this.parameters ) {
  27490. values.push( this.parameters[ param ].getCacheKey( force ) );
  27491. }
  27492. return hashArray( values );
  27493. }
  27494. set needsUpdate( value ) {
  27495. if ( value === true ) this.dispose();
  27496. }
  27497. get needsUpdate() {
  27498. return this.source !== this._source;
  27499. }
  27500. /**
  27501. * Executes the `main` function of the script.
  27502. *
  27503. * @private
  27504. * @return {ScriptableNode} A reference to this node.
  27505. */
  27506. _exec() {
  27507. if ( this.codeNode === null ) return this;
  27508. if ( this._needsOutputUpdate === true ) {
  27509. this._value = this.call( 'main' );
  27510. this._needsOutputUpdate = false;
  27511. }
  27512. this._output.value = this._value;
  27513. return this;
  27514. }
  27515. /**
  27516. * Executes the refresh.
  27517. *
  27518. * @private
  27519. */
  27520. _refresh() {
  27521. this.needsUpdate = true;
  27522. this._exec();
  27523. this._output.refresh();
  27524. }
  27525. }
  27526. /**
  27527. * TSL function for creating a scriptable node.
  27528. *
  27529. * @tsl
  27530. * @function
  27531. * @param {CodeNode} [codeNode] - The code node.
  27532. * @param {?Object} [parameters={}] - The parameters definition.
  27533. * @returns {ScriptableNode}
  27534. */
  27535. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  27536. /**
  27537. * Returns a node that represents the `z` coordinate in view space
  27538. * for the current fragment. It's a different representation of the
  27539. * default depth value.
  27540. *
  27541. * This value can be part of a computation that defines how the fog
  27542. * density increases when moving away from the camera.
  27543. *
  27544. * @param {NodeBuilder} builder - The current node builder.
  27545. * @return {Node} The viewZ node.
  27546. */
  27547. function getViewZNode( builder ) {
  27548. let viewZ;
  27549. const getViewZ = builder.context.getViewZ;
  27550. if ( getViewZ !== undefined ) {
  27551. viewZ = getViewZ( this );
  27552. }
  27553. return ( viewZ || positionView.z ).negate();
  27554. }
  27555. /**
  27556. * Constructs a new range factor node.
  27557. *
  27558. * @tsl
  27559. * @function
  27560. * @param {Node} near - Defines the near value.
  27561. * @param {Node} far - Defines the far value.
  27562. */
  27563. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  27564. const viewZ = getViewZNode( builder );
  27565. return smoothstep( near, far, viewZ );
  27566. } );
  27567. /**
  27568. * Represents an exponential squared fog. This type of fog gives
  27569. * a clear view near the camera and a faster than exponentially
  27570. * densening fog farther from the camera.
  27571. *
  27572. * @tsl
  27573. * @function
  27574. * @param {Node} density - Defines the fog density.
  27575. */
  27576. const densityFogFactor = Fn( ( [ density ], builder ) => {
  27577. const viewZ = getViewZNode( builder );
  27578. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  27579. } );
  27580. /**
  27581. * This class can be used to configure a fog for the scene.
  27582. * Nodes of this type are assigned to `Scene.fogNode`.
  27583. *
  27584. * @tsl
  27585. * @function
  27586. * @param {Node} color - Defines the color of the fog.
  27587. * @param {Node} factor - Defines how the fog is factored in the scene.
  27588. */
  27589. const fog = Fn( ( [ color, factor ] ) => {
  27590. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  27591. } );
  27592. // Deprecated
  27593. /**
  27594. * @tsl
  27595. * @function
  27596. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  27597. *
  27598. * @param {Node} color
  27599. * @param {Node} near
  27600. * @param {Node} far
  27601. * @returns {Function}
  27602. */
  27603. function rangeFog( color, near, far ) { // @deprecated, r171
  27604. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  27605. return fog( color, rangeFogFactor( near, far ) );
  27606. }
  27607. /**
  27608. * @tsl
  27609. * @function
  27610. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  27611. *
  27612. * @param {Node} color
  27613. * @param {Node} density
  27614. * @returns {Function}
  27615. */
  27616. function densityFog( color, density ) { // @deprecated, r171
  27617. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  27618. return fog( color, densityFogFactor( density ) );
  27619. }
  27620. let min = null;
  27621. let max = null;
  27622. /**
  27623. * `RangeNode` generates random instanced attribute data in a defined range.
  27624. * An exemplary use case for this utility node is to generate random per-instance
  27625. * colors:
  27626. * ```js
  27627. * const material = new MeshBasicNodeMaterial();
  27628. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  27629. * const mesh = new InstancedMesh( geometry, material, count );
  27630. * ```
  27631. * @augments Node
  27632. */
  27633. class RangeNode extends Node {
  27634. static get type() {
  27635. return 'RangeNode';
  27636. }
  27637. /**
  27638. * Constructs a new range node.
  27639. *
  27640. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27641. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27642. */
  27643. constructor( minNode = float(), maxNode = float() ) {
  27644. super();
  27645. /**
  27646. * A node defining the lower bound of the range.
  27647. *
  27648. * @type {Node<any>}
  27649. * @default float()
  27650. */
  27651. this.minNode = minNode;
  27652. /**
  27653. * A node defining the upper bound of the range.
  27654. *
  27655. * @type {Node<any>}
  27656. * @default float()
  27657. */
  27658. this.maxNode = maxNode;
  27659. }
  27660. /**
  27661. * Returns the vector length which is computed based on the range definition.
  27662. *
  27663. * @param {NodeBuilder} builder - The current node builder.
  27664. * @return {number} The vector length.
  27665. */
  27666. getVectorLength( builder ) {
  27667. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  27668. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  27669. return minLength > maxLength ? minLength : maxLength;
  27670. }
  27671. /**
  27672. * This method is overwritten since the node type is inferred from range definition.
  27673. *
  27674. * @param {NodeBuilder} builder - The current node builder.
  27675. * @return {string} The node type.
  27676. */
  27677. getNodeType( builder ) {
  27678. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  27679. }
  27680. setup( builder ) {
  27681. const object = builder.object;
  27682. let output = null;
  27683. if ( object.count > 1 ) {
  27684. const minValue = this.minNode.value;
  27685. const maxValue = this.maxNode.value;
  27686. const minLength = builder.getTypeLength( getValueType( minValue ) );
  27687. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  27688. min = min || new Vector4();
  27689. max = max || new Vector4();
  27690. min.setScalar( 0 );
  27691. max.setScalar( 0 );
  27692. if ( minLength === 1 ) min.setScalar( minValue );
  27693. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  27694. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  27695. if ( maxLength === 1 ) max.setScalar( maxValue );
  27696. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  27697. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  27698. const stride = 4;
  27699. const length = stride * object.count;
  27700. const array = new Float32Array( length );
  27701. for ( let i = 0; i < length; i ++ ) {
  27702. const index = i % stride;
  27703. const minElementValue = min.getComponent( index );
  27704. const maxElementValue = max.getComponent( index );
  27705. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  27706. }
  27707. const nodeType = this.getNodeType( builder );
  27708. if ( object.count <= 4096 ) {
  27709. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  27710. } else {
  27711. // TODO: Improve anonymous buffer attribute creation removing this part
  27712. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  27713. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  27714. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  27715. }
  27716. } else {
  27717. output = float( 0 );
  27718. }
  27719. return output;
  27720. }
  27721. }
  27722. /**
  27723. * TSL function for creating a range node.
  27724. *
  27725. * @tsl
  27726. * @function
  27727. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27728. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27729. * @returns {RangeNode}
  27730. */
  27731. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  27732. /**
  27733. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  27734. * about the currently running dispatch and/or the device it is running on.
  27735. *
  27736. * This node can only be used with a WebGPU backend.
  27737. *
  27738. * @augments Node
  27739. */
  27740. class ComputeBuiltinNode extends Node {
  27741. static get type() {
  27742. return 'ComputeBuiltinNode';
  27743. }
  27744. /**
  27745. * Constructs a new compute builtin node.
  27746. *
  27747. * @param {string} builtinName - The built-in name.
  27748. * @param {string} nodeType - The node type.
  27749. */
  27750. constructor( builtinName, nodeType ) {
  27751. super( nodeType );
  27752. /**
  27753. * The built-in name.
  27754. *
  27755. * @private
  27756. * @type {string}
  27757. */
  27758. this._builtinName = builtinName;
  27759. }
  27760. /**
  27761. * This method is overwritten since hash is derived from the built-in name.
  27762. *
  27763. * @param {NodeBuilder} builder - The current node builder.
  27764. * @return {string} The hash.
  27765. */
  27766. getHash( builder ) {
  27767. return this.getBuiltinName( builder );
  27768. }
  27769. /**
  27770. * This method is overwritten since the node type is simply derived from `nodeType`..
  27771. *
  27772. * @param {NodeBuilder} builder - The current node builder.
  27773. * @return {string} The node type.
  27774. */
  27775. getNodeType( /*builder*/ ) {
  27776. return this.nodeType;
  27777. }
  27778. /**
  27779. * Sets the builtin name.
  27780. *
  27781. * @param {string} builtinName - The built-in name.
  27782. * @return {ComputeBuiltinNode} A reference to this node.
  27783. */
  27784. setBuiltinName( builtinName ) {
  27785. this._builtinName = builtinName;
  27786. return this;
  27787. }
  27788. /**
  27789. * Returns the builtin name.
  27790. *
  27791. * @param {NodeBuilder} builder - The current node builder.
  27792. * @return {string} The builtin name.
  27793. */
  27794. getBuiltinName( /*builder*/ ) {
  27795. return this._builtinName;
  27796. }
  27797. /**
  27798. * Whether the current node builder has the builtin or not.
  27799. *
  27800. * @param {NodeBuilder} builder - The current node builder.
  27801. * @return {boolean} Whether the builder has the builtin or not.
  27802. */
  27803. hasBuiltin( builder ) {
  27804. return builder.hasBuiltin( this._builtinName );
  27805. }
  27806. generate( builder, output ) {
  27807. const builtinName = this.getBuiltinName( builder );
  27808. const nodeType = this.getNodeType( builder );
  27809. if ( builder.shaderStage === 'compute' ) {
  27810. return builder.format( builtinName, nodeType, output );
  27811. } else {
  27812. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  27813. return builder.generateConst( nodeType );
  27814. }
  27815. }
  27816. serialize( data ) {
  27817. super.serialize( data );
  27818. data.global = this.global;
  27819. data._builtinName = this._builtinName;
  27820. }
  27821. deserialize( data ) {
  27822. super.deserialize( data );
  27823. this.global = data.global;
  27824. this._builtinName = data._builtinName;
  27825. }
  27826. }
  27827. /**
  27828. * TSL function for creating a compute builtin node.
  27829. *
  27830. * @tsl
  27831. * @function
  27832. * @param {string} name - The built-in name.
  27833. * @param {string} nodeType - The node type.
  27834. * @returns {ComputeBuiltinNode}
  27835. */
  27836. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  27837. /**
  27838. * Represents the number of workgroups dispatched by the compute shader.
  27839. * ```js
  27840. * // Run 512 invocations/threads with a workgroup size of 128.
  27841. * const computeFn = Fn(() => {
  27842. *
  27843. * // numWorkgroups.x = 4
  27844. * storageBuffer.element(0).assign(numWorkgroups.x)
  27845. *
  27846. * })().compute(512, [128]);
  27847. *
  27848. * // Run 512 invocations/threads with the default workgroup size of 64.
  27849. * const computeFn = Fn(() => {
  27850. *
  27851. * // numWorkgroups.x = 8
  27852. * storageBuffer.element(0).assign(numWorkgroups.x)
  27853. *
  27854. * })().compute(512);
  27855. * ```
  27856. *
  27857. * @tsl
  27858. * @type {ComputeBuiltinNode<uvec3>}
  27859. */
  27860. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  27861. /**
  27862. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  27863. * ```js
  27864. * // Execute 12 compute threads with a workgroup size of 3.
  27865. * const computeFn = Fn( () => {
  27866. *
  27867. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  27868. *
  27869. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  27870. *
  27871. * } ).Else( () => {
  27872. *
  27873. * storageBuffer.element( instanceIndex ).assign( 0 );
  27874. *
  27875. * } );
  27876. *
  27877. * } )().compute( 12, [ 3 ] );
  27878. *
  27879. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  27880. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  27881. * ```
  27882. *
  27883. * @tsl
  27884. * @type {ComputeBuiltinNode<uvec3>}
  27885. */
  27886. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  27887. /**
  27888. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  27889. *
  27890. * @tsl
  27891. * @type {ComputeBuiltinNode<uvec3>}
  27892. */
  27893. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  27894. /**
  27895. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  27896. *
  27897. * @tsl
  27898. * @type {ComputeBuiltinNode<uvec3>}
  27899. */
  27900. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  27901. /**
  27902. * A device dependent variable that exposes the size of the current invocation's subgroup.
  27903. *
  27904. * @tsl
  27905. * @type {ComputeBuiltinNode<uint>}
  27906. */
  27907. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  27908. /**
  27909. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  27910. *
  27911. * This node can only be used with a WebGPU backend.
  27912. *
  27913. * @augments Node
  27914. */
  27915. class BarrierNode extends Node {
  27916. /**
  27917. * Constructs a new barrier node.
  27918. *
  27919. * @param {string} scope - The scope defines the behavior of the node.
  27920. */
  27921. constructor( scope ) {
  27922. super();
  27923. this.scope = scope;
  27924. }
  27925. generate( builder ) {
  27926. const { scope } = this;
  27927. const { renderer } = builder;
  27928. if ( renderer.backend.isWebGLBackend === true ) {
  27929. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  27930. } else {
  27931. builder.addLineFlowCode( `${scope}Barrier()`, this );
  27932. }
  27933. }
  27934. }
  27935. /**
  27936. * TSL function for creating a barrier node.
  27937. *
  27938. * @tsl
  27939. * @function
  27940. * @param {string} scope - The scope defines the behavior of the node..
  27941. * @returns {BarrierNode}
  27942. */
  27943. const barrier = nodeProxy( BarrierNode );
  27944. /**
  27945. * TSL function for creating a workgroup barrier. All compute shader
  27946. * invocations must wait for each invocation within a workgroup to
  27947. * complete before the barrier can be surpassed.
  27948. *
  27949. * @tsl
  27950. * @function
  27951. * @returns {BarrierNode}
  27952. */
  27953. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  27954. /**
  27955. * TSL function for creating a storage barrier. All invocations must
  27956. * wait for each access to variables within the 'storage' address space
  27957. * to complete before the barrier can be passed.
  27958. *
  27959. * @tsl
  27960. * @function
  27961. * @returns {BarrierNode}
  27962. */
  27963. const storageBarrier = () => barrier( 'storage' ).toStack();
  27964. /**
  27965. * TSL function for creating a texture barrier. All invocations must
  27966. * wait for each access to variables within the 'texture' address space
  27967. * to complete before the barrier can be passed.
  27968. *
  27969. * @tsl
  27970. * @function
  27971. * @returns {BarrierNode}
  27972. */
  27973. const textureBarrier = () => barrier( 'texture' ).toStack();
  27974. /**
  27975. * Represents an element of a 'workgroup' scoped buffer.
  27976. *
  27977. * @augments ArrayElementNode
  27978. */
  27979. class WorkgroupInfoElementNode extends ArrayElementNode {
  27980. /**
  27981. * Constructs a new workgroup info element node.
  27982. *
  27983. * @param {Node} workgroupInfoNode - The workgroup info node.
  27984. * @param {Node} indexNode - The index node that defines the element access.
  27985. */
  27986. constructor( workgroupInfoNode, indexNode ) {
  27987. super( workgroupInfoNode, indexNode );
  27988. /**
  27989. * This flag can be used for type testing.
  27990. *
  27991. * @type {boolean}
  27992. * @readonly
  27993. * @default true
  27994. */
  27995. this.isWorkgroupInfoElementNode = true;
  27996. }
  27997. generate( builder, output ) {
  27998. let snippet;
  27999. const isAssignContext = builder.context.assign;
  28000. snippet = super.generate( builder );
  28001. if ( isAssignContext !== true ) {
  28002. const type = this.getNodeType( builder );
  28003. snippet = builder.format( snippet, type, output );
  28004. }
  28005. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  28006. return snippet;
  28007. }
  28008. }
  28009. /**
  28010. * A node allowing the user to create a 'workgroup' scoped buffer within the
  28011. * context of a compute shader. Typically, workgroup scoped buffers are
  28012. * created to hold data that is transferred from a global storage scope into
  28013. * a local workgroup scope. For invocations within a workgroup, data
  28014. * access speeds on 'workgroup' scoped buffers can be significantly faster
  28015. * than similar access operations on globally accessible storage buffers.
  28016. *
  28017. * This node can only be used with a WebGPU backend.
  28018. *
  28019. * @augments Node
  28020. */
  28021. class WorkgroupInfoNode extends Node {
  28022. /**
  28023. * Constructs a new buffer scoped to type scope.
  28024. *
  28025. * @param {string} scope - TODO.
  28026. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  28027. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  28028. */
  28029. constructor( scope, bufferType, bufferCount = 0 ) {
  28030. super( bufferType );
  28031. /**
  28032. * The buffer type.
  28033. *
  28034. * @type {string}
  28035. */
  28036. this.bufferType = bufferType;
  28037. /**
  28038. * The buffer count.
  28039. *
  28040. * @type {number}
  28041. * @default 0
  28042. */
  28043. this.bufferCount = bufferCount;
  28044. /**
  28045. * This flag can be used for type testing.
  28046. *
  28047. * @type {boolean}
  28048. * @readonly
  28049. * @default true
  28050. */
  28051. this.isWorkgroupInfoNode = true;
  28052. /**
  28053. * The data type of the array buffer.
  28054. *
  28055. * @type {string}
  28056. */
  28057. this.elementType = bufferType;
  28058. /**
  28059. * TODO.
  28060. *
  28061. * @type {string}
  28062. */
  28063. this.scope = scope;
  28064. /**
  28065. * The name of the workgroup scoped buffer.
  28066. *
  28067. * @type {string}
  28068. * @default ''
  28069. */
  28070. this.name = '';
  28071. }
  28072. /**
  28073. * Sets the name of this node.
  28074. *
  28075. * @param {string} name - The name to set.
  28076. * @return {WorkgroupInfoNode} A reference to this node.
  28077. */
  28078. setName( name ) {
  28079. this.name = name;
  28080. return this;
  28081. }
  28082. /**
  28083. * Sets the name/label of this node.
  28084. *
  28085. * @deprecated
  28086. * @param {string} name - The name to set.
  28087. * @return {WorkgroupInfoNode} A reference to this node.
  28088. */
  28089. label( name ) {
  28090. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  28091. return this.setName( name );
  28092. }
  28093. /**
  28094. * Sets the scope of this node.
  28095. *
  28096. * @param {string} scope - The scope to set.
  28097. * @return {WorkgroupInfoNode} A reference to this node.
  28098. */
  28099. setScope( scope ) {
  28100. this.scope = scope;
  28101. return this;
  28102. }
  28103. /**
  28104. * The data type of the array buffer.
  28105. *
  28106. * @return {string} The element type.
  28107. */
  28108. getElementType() {
  28109. return this.elementType;
  28110. }
  28111. /**
  28112. * Overwrites the default implementation since the input type
  28113. * is inferred from the scope.
  28114. *
  28115. * @param {NodeBuilder} builder - The current node builder.
  28116. * @return {string} The input type.
  28117. */
  28118. getInputType( /*builder*/ ) {
  28119. return `${this.scope}Array`;
  28120. }
  28121. /**
  28122. * This method can be used to access elements via an index node.
  28123. *
  28124. * @param {IndexNode} indexNode - indexNode.
  28125. * @return {WorkgroupInfoElementNode} A reference to an element.
  28126. */
  28127. element( indexNode ) {
  28128. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  28129. }
  28130. generate( builder ) {
  28131. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  28132. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  28133. }
  28134. }
  28135. /**
  28136. * TSL function for creating a workgroup info node.
  28137. * Creates a new 'workgroup' scoped array buffer.
  28138. *
  28139. * @tsl
  28140. * @function
  28141. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  28142. * @param {number} [count=0] - The number of elements in the buffer.
  28143. * @returns {WorkgroupInfoNode}
  28144. */
  28145. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  28146. /**
  28147. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  28148. * within a shader. In an atomic function, any modification to an atomic variable will
  28149. * occur as an indivisible step with a defined order relative to other modifications.
  28150. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  28151. * atomic operations will not interfere with each other.
  28152. *
  28153. * This node can only be used with a WebGPU backend.
  28154. *
  28155. * @augments Node
  28156. */
  28157. class AtomicFunctionNode extends Node {
  28158. static get type() {
  28159. return 'AtomicFunctionNode';
  28160. }
  28161. /**
  28162. * Constructs a new atomic function node.
  28163. *
  28164. * @param {string} method - The signature of the atomic function to construct.
  28165. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28166. * @param {Node} valueNode - The value that mutates the atomic variable.
  28167. */
  28168. constructor( method, pointerNode, valueNode ) {
  28169. super( 'uint' );
  28170. /**
  28171. * The signature of the atomic function to construct.
  28172. *
  28173. * @type {string}
  28174. */
  28175. this.method = method;
  28176. /**
  28177. * An atomic variable or element of an atomic buffer.
  28178. *
  28179. * @type {Node}
  28180. */
  28181. this.pointerNode = pointerNode;
  28182. /**
  28183. * A value that modifies the atomic variable.
  28184. *
  28185. * @type {Node}
  28186. */
  28187. this.valueNode = valueNode;
  28188. /**
  28189. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  28190. *
  28191. * @type {boolean}
  28192. * @default true
  28193. */
  28194. this.parents = true;
  28195. }
  28196. /**
  28197. * Overwrites the default implementation to return the type of
  28198. * the pointer node.
  28199. *
  28200. * @param {NodeBuilder} builder - The current node builder.
  28201. * @return {string} The input type.
  28202. */
  28203. getInputType( builder ) {
  28204. return this.pointerNode.getNodeType( builder );
  28205. }
  28206. /**
  28207. * Overwritten since the node type is inferred from the input type.
  28208. *
  28209. * @param {NodeBuilder} builder - The current node builder.
  28210. * @return {string} The node type.
  28211. */
  28212. getNodeType( builder ) {
  28213. return this.getInputType( builder );
  28214. }
  28215. generate( builder ) {
  28216. const properties = builder.getNodeProperties( this );
  28217. const parents = properties.parents;
  28218. const method = this.method;
  28219. const type = this.getNodeType( builder );
  28220. const inputType = this.getInputType( builder );
  28221. const a = this.pointerNode;
  28222. const b = this.valueNode;
  28223. const params = [];
  28224. params.push( `&${ a.build( builder, inputType ) }` );
  28225. if ( b !== null ) {
  28226. params.push( b.build( builder, inputType ) );
  28227. }
  28228. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  28229. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  28230. if ( isVoid ) {
  28231. builder.addLineFlowCode( methodSnippet, this );
  28232. } else {
  28233. if ( properties.constNode === undefined ) {
  28234. properties.constNode = expression( methodSnippet, type ).toConst();
  28235. }
  28236. return properties.constNode.build( builder );
  28237. }
  28238. }
  28239. }
  28240. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  28241. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  28242. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  28243. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  28244. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  28245. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  28246. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  28247. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  28248. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  28249. /**
  28250. * TSL function for creating an atomic function node.
  28251. *
  28252. * @tsl
  28253. * @function
  28254. * @param {string} method - The signature of the atomic function to construct.
  28255. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28256. * @param {Node} valueNode - The value that mutates the atomic variable.
  28257. * @returns {AtomicFunctionNode}
  28258. */
  28259. const atomicNode = nodeProxy( AtomicFunctionNode );
  28260. /**
  28261. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  28262. *
  28263. * @tsl
  28264. * @function
  28265. * @param {string} method - The signature of the atomic function to construct.
  28266. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28267. * @param {Node} valueNode - The value that mutates the atomic variable.
  28268. * @returns {AtomicFunctionNode}
  28269. */
  28270. const atomicFunc = ( method, pointerNode, valueNode ) => {
  28271. return atomicNode( method, pointerNode, valueNode ).toStack();
  28272. };
  28273. /**
  28274. * Loads the value stored in the atomic variable.
  28275. *
  28276. * @tsl
  28277. * @function
  28278. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28279. * @returns {AtomicFunctionNode}
  28280. */
  28281. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  28282. /**
  28283. * Stores a value in the atomic variable.
  28284. *
  28285. * @tsl
  28286. * @function
  28287. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28288. * @param {Node} valueNode - The value that mutates the atomic variable.
  28289. * @returns {AtomicFunctionNode}
  28290. */
  28291. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  28292. /**
  28293. * Increments the value stored in the atomic variable.
  28294. *
  28295. * @tsl
  28296. * @function
  28297. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28298. * @param {Node} valueNode - The value that mutates the atomic variable.
  28299. * @returns {AtomicFunctionNode}
  28300. */
  28301. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  28302. /**
  28303. * Decrements the value stored in the atomic variable.
  28304. *
  28305. * @tsl
  28306. * @function
  28307. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28308. * @param {Node} valueNode - The value that mutates the atomic variable.
  28309. * @returns {AtomicFunctionNode}
  28310. */
  28311. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  28312. /**
  28313. * Stores in an atomic variable the maximum between its current value and a parameter.
  28314. *
  28315. * @tsl
  28316. * @function
  28317. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28318. * @param {Node} valueNode - The value that mutates the atomic variable.
  28319. * @returns {AtomicFunctionNode}
  28320. */
  28321. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  28322. /**
  28323. * Stores in an atomic variable the minimum between its current value and a parameter.
  28324. *
  28325. * @tsl
  28326. * @function
  28327. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28328. * @param {Node} valueNode - The value that mutates the atomic variable.
  28329. * @returns {AtomicFunctionNode}
  28330. */
  28331. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  28332. /**
  28333. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  28334. *
  28335. * @tsl
  28336. * @function
  28337. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28338. * @param {Node} valueNode - The value that mutates the atomic variable.
  28339. * @returns {AtomicFunctionNode}
  28340. */
  28341. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  28342. /**
  28343. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  28344. *
  28345. * @tsl
  28346. * @function
  28347. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28348. * @param {Node} valueNode - The value that mutates the atomic variable.
  28349. * @returns {AtomicFunctionNode}
  28350. */
  28351. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  28352. /**
  28353. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  28354. *
  28355. * @tsl
  28356. * @function
  28357. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28358. * @param {Node} valueNode - The value that mutates the atomic variable.
  28359. * @returns {AtomicFunctionNode}
  28360. */
  28361. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  28362. /**
  28363. * This class represents a set of built in WGSL shader functions that sync
  28364. * synchronously execute an operation across a subgroup, or 'warp', of compute
  28365. * or fragment shader invocations within a workgroup. Typically, these functions
  28366. * will synchronously execute an operation using data from all active invocations
  28367. * within the subgroup, then broadcast that result to all active invocations. In
  28368. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  28369. * (DirectX/HLSL) or warp intrinsics (CUDA).
  28370. *
  28371. * @augments TempNode
  28372. */
  28373. class SubgroupFunctionNode extends TempNode {
  28374. static get type() {
  28375. return 'SubgroupFunctionNode';
  28376. }
  28377. /**
  28378. * Constructs a new function node.
  28379. *
  28380. * @param {string} method - The subgroup/wave intrinsic method to construct.
  28381. * @param {Node} [aNode=null] - The method's first argument.
  28382. * @param {Node} [bNode=null] - The method's second argument.
  28383. */
  28384. constructor( method, aNode = null, bNode = null ) {
  28385. super();
  28386. /**
  28387. * The subgroup/wave intrinsic method to construct.
  28388. *
  28389. * @type {String}
  28390. */
  28391. this.method = method;
  28392. /**
  28393. * The method's first argument.
  28394. *
  28395. * @type {Node}
  28396. */
  28397. this.aNode = aNode;
  28398. /**
  28399. * The method's second argument.
  28400. *
  28401. * @type {Node}
  28402. */
  28403. this.bNode = bNode;
  28404. }
  28405. getInputType( builder ) {
  28406. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  28407. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  28408. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  28409. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  28410. if ( aLen > bLen ) {
  28411. return aType;
  28412. } else {
  28413. return bType;
  28414. }
  28415. }
  28416. getNodeType( builder ) {
  28417. const method = this.method;
  28418. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  28419. return 'bool';
  28420. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  28421. return 'uvec4';
  28422. } else {
  28423. return this.getInputType( builder );
  28424. }
  28425. }
  28426. generate( builder, output ) {
  28427. const method = this.method;
  28428. const type = this.getNodeType( builder );
  28429. const inputType = this.getInputType( builder );
  28430. const a = this.aNode;
  28431. const b = this.bNode;
  28432. const params = [];
  28433. if (
  28434. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  28435. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  28436. method === SubgroupFunctionNode.QUAD_BROADCAST
  28437. ) {
  28438. const bType = b.getNodeType( builder );
  28439. params.push(
  28440. a.build( builder, type ),
  28441. b.build( builder, bType === 'float' ? 'int' : type )
  28442. );
  28443. } else if (
  28444. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  28445. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  28446. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  28447. ) {
  28448. params.push(
  28449. a.build( builder, type ),
  28450. b.build( builder, 'uint' )
  28451. );
  28452. } else {
  28453. if ( a !== null ) params.push( a.build( builder, inputType ) );
  28454. if ( b !== null ) params.push( b.build( builder, inputType ) );
  28455. }
  28456. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  28457. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  28458. }
  28459. serialize( data ) {
  28460. super.serialize( data );
  28461. data.method = this.method;
  28462. }
  28463. deserialize( data ) {
  28464. super.deserialize( data );
  28465. this.method = data.method;
  28466. }
  28467. }
  28468. // 0 inputs
  28469. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  28470. // 1 input
  28471. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  28472. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  28473. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  28474. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  28475. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  28476. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  28477. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  28478. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  28479. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  28480. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  28481. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  28482. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  28483. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  28484. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  28485. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  28486. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  28487. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  28488. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  28489. // 2 inputs
  28490. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  28491. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  28492. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  28493. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  28494. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  28495. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  28496. /**
  28497. * Returns true if this invocation has the lowest subgroup_invocation_id
  28498. * among active invocations in the subgroup.
  28499. *
  28500. * @method
  28501. * @return {bool} The result of the computation.
  28502. */
  28503. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  28504. /**
  28505. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  28506. * is 1 if pred is true for that active invocation and 0 otherwise.
  28507. *
  28508. * @method
  28509. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  28510. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  28511. */
  28512. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  28513. /**
  28514. * A reduction that adds e among all active invocations and returns that result.
  28515. *
  28516. * @method
  28517. * @param {number} e - The value provided to the reduction by the current invocation.
  28518. * @return {number} The accumulated result of the reduction operation.
  28519. */
  28520. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  28521. /**
  28522. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28523. *
  28524. * @method
  28525. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28526. * @return {number} The accumulated result of the inclusive scan operation.
  28527. */
  28528. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  28529. /**
  28530. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  28531. *
  28532. * @method
  28533. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28534. * @return {number} The accumulated result of the exclusive scan operation.
  28535. */
  28536. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  28537. /**
  28538. * A reduction that multiplies e among all active invocations and returns that result.
  28539. *
  28540. * @method
  28541. * @param {number} e - The value provided to the reduction by the current invocation.
  28542. * @return {number} The accumulated result of the reduction operation.
  28543. */
  28544. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  28545. /**
  28546. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28547. *
  28548. * @method
  28549. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28550. * @return {number} The accumulated result of the inclusive scan operation.
  28551. */
  28552. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  28553. /**
  28554. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  28555. *
  28556. * @method
  28557. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28558. * @return {number} The accumulated result of the exclusive scan operation.
  28559. */
  28560. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  28561. /**
  28562. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  28563. *
  28564. * @method
  28565. * @param {number} e - The value provided to the reduction by the current invocation.
  28566. * @return {number} The result of the reduction operation.
  28567. */
  28568. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  28569. /**
  28570. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  28571. *
  28572. * @method
  28573. * @param {number} e - The value provided to the reduction by the current invocation.
  28574. * @return {number} The result of the reduction operation.
  28575. */
  28576. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  28577. /**
  28578. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  28579. *
  28580. * @method
  28581. * @param {number} e - The value provided to the reduction by the current invocation.
  28582. * @return {number} The result of the reduction operation.
  28583. */
  28584. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  28585. /**
  28586. * A reduction that performs a min of e among all active invocations and returns that result.
  28587. *
  28588. * @method
  28589. * @param {number} e - The value provided to the reduction by the current invocation.
  28590. * @return {number} The result of the reduction operation.
  28591. */
  28592. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  28593. /**
  28594. * A reduction that performs a max of e among all active invocations and returns that result.
  28595. *
  28596. * @method
  28597. * @param {number} e - The value provided to the reduction by the current invocation.
  28598. * @return {number} The result of the reduction operation.
  28599. */
  28600. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  28601. /**
  28602. * Returns true if e is true for all active invocations in the subgroup.
  28603. *
  28604. * @method
  28605. * @return {bool} The result of the computation.
  28606. */
  28607. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  28608. /**
  28609. * Returns true if e is true for any active invocation in the subgroup
  28610. *
  28611. * @method
  28612. * @return {bool} The result of the computation.
  28613. */
  28614. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  28615. /**
  28616. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  28617. *
  28618. * @method
  28619. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  28620. * @param {number} id - The subgroup invocation to broadcast from.
  28621. * @return {number} The broadcast value.
  28622. */
  28623. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  28624. /**
  28625. * Swaps e between invocations in the quad in the X direction.
  28626. *
  28627. * @method
  28628. * @param {number} e - The value to swap from the current invocation.
  28629. * @return {number} The value received from the swap operation.
  28630. */
  28631. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  28632. /**
  28633. * Swaps e between invocations in the quad in the Y direction.
  28634. *
  28635. * @method
  28636. * @param {number} e - The value to swap from the current invocation.
  28637. * @return {number} The value received from the swap operation.
  28638. */
  28639. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  28640. /**
  28641. * Swaps e between invocations in the quad diagonally.
  28642. *
  28643. * @method
  28644. * @param {number} e - The value to swap from the current invocation.
  28645. * @return {number} The value received from the swap operation.
  28646. */
  28647. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  28648. /**
  28649. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  28650. *
  28651. * @method
  28652. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  28653. * @param {number} id - The subgroup invocation to broadcast from.
  28654. * @return {number} The broadcast value.
  28655. */
  28656. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  28657. /**
  28658. * Returns v from the active invocation whose subgroup_invocation_id matches id
  28659. *
  28660. * @method
  28661. * @param {number} v - The value to return from subgroup invocation id^mask.
  28662. * @param {number} id - The subgroup invocation which returns the value v.
  28663. * @return {number} The broadcast value.
  28664. */
  28665. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  28666. /**
  28667. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  28668. *
  28669. * @method
  28670. * @param {number} v - The value to return from subgroup invocation id^mask.
  28671. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  28672. * @return {number} The broadcast value.
  28673. */
  28674. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  28675. /**
  28676. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  28677. *
  28678. * @method
  28679. * @param {number} v - The value to return from subgroup invocation id^mask.
  28680. * @param {number} delta - A value that offsets the current in.
  28681. * @return {number} The broadcast value.
  28682. */
  28683. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  28684. /**
  28685. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  28686. *
  28687. * @method
  28688. * @param {number} v - The value to return from subgroup invocation id^mask.
  28689. * @param {number} delta - A value that offsets the current subgroup invocation.
  28690. * @return {number} The broadcast value.
  28691. */
  28692. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  28693. /**
  28694. * Broadcasts e from the quad invocation with id equal to id.
  28695. *
  28696. * @method
  28697. * @param {number} e - The value to broadcast.
  28698. * @return {number} The broadcast value.
  28699. */
  28700. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  28701. let uniformsLib;
  28702. function getLightData( light ) {
  28703. uniformsLib = uniformsLib || new WeakMap();
  28704. let uniforms = uniformsLib.get( light );
  28705. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  28706. return uniforms;
  28707. }
  28708. /**
  28709. * TSL function for getting a shadow matrix uniform node for the given light.
  28710. *
  28711. * @tsl
  28712. * @function
  28713. * @param {Light} light -The light source.
  28714. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  28715. */
  28716. function lightShadowMatrix( light ) {
  28717. const data = getLightData( light );
  28718. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  28719. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  28720. light.shadow.updateMatrices( light );
  28721. }
  28722. return light.shadow.matrix;
  28723. } ) );
  28724. }
  28725. /**
  28726. * TSL function for getting projected uv coordinates for the given light.
  28727. * Relevant when using maps with spot lights.
  28728. *
  28729. * @tsl
  28730. * @function
  28731. * @param {Light} light -The light source.
  28732. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  28733. * @returns {Node<vec3>} The projected uvs.
  28734. */
  28735. function lightProjectionUV( light, position = positionWorld ) {
  28736. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  28737. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  28738. return projectionUV;
  28739. }
  28740. /**
  28741. * TSL function for getting the position in world space for the given light.
  28742. *
  28743. * @tsl
  28744. * @function
  28745. * @param {Light} light -The light source.
  28746. * @returns {UniformNode<vec3>} The light's position in world space.
  28747. */
  28748. function lightPosition( light ) {
  28749. const data = getLightData( light );
  28750. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  28751. }
  28752. /**
  28753. * TSL function for getting the light target position in world space for the given light.
  28754. *
  28755. * @tsl
  28756. * @function
  28757. * @param {Light} light -The light source.
  28758. * @returns {UniformNode<vec3>} The light target position in world space.
  28759. */
  28760. function lightTargetPosition( light ) {
  28761. const data = getLightData( light );
  28762. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  28763. }
  28764. /**
  28765. * TSL function for getting the position in view space for the given light.
  28766. *
  28767. * @tsl
  28768. * @function
  28769. * @param {Light} light - The light source.
  28770. * @returns {UniformNode<vec3>} The light's position in view space.
  28771. */
  28772. function lightViewPosition( light ) {
  28773. const data = getLightData( light );
  28774. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  28775. self.value = self.value || new Vector3();
  28776. self.value.setFromMatrixPosition( light.matrixWorld );
  28777. self.value.applyMatrix4( camera.matrixWorldInverse );
  28778. } ) );
  28779. }
  28780. /**
  28781. * TSL function for getting the light target direction for the given light.
  28782. *
  28783. * @tsl
  28784. * @function
  28785. * @param {Light} light -The light source.
  28786. * @returns {Node<vec3>} The light's target direction.
  28787. */
  28788. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  28789. const sortLights = ( lights ) => {
  28790. return lights.sort( ( a, b ) => a.id - b.id );
  28791. };
  28792. const getLightNodeById = ( id, lightNodes ) => {
  28793. for ( const lightNode of lightNodes ) {
  28794. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  28795. return lightNode;
  28796. }
  28797. }
  28798. return null;
  28799. };
  28800. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  28801. const _hashData = [];
  28802. /**
  28803. * This node represents the scene's lighting and manages the lighting model's life cycle
  28804. * for the current build 3D object. It is responsible for computing the total outgoing
  28805. * light in a given lighting context.
  28806. *
  28807. * @augments Node
  28808. */
  28809. class LightsNode extends Node {
  28810. static get type() {
  28811. return 'LightsNode';
  28812. }
  28813. /**
  28814. * Constructs a new lights node.
  28815. */
  28816. constructor() {
  28817. super( 'vec3' );
  28818. /**
  28819. * A node representing the total diffuse light.
  28820. *
  28821. * @type {Node<vec3>}
  28822. */
  28823. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  28824. /**
  28825. * A node representing the total specular light.
  28826. *
  28827. * @type {Node<vec3>}
  28828. */
  28829. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  28830. /**
  28831. * A node representing the outgoing light.
  28832. *
  28833. * @type {Node<vec3>}
  28834. */
  28835. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  28836. /**
  28837. * An array representing the lights in the scene.
  28838. *
  28839. * @private
  28840. * @type {Array<Light>}
  28841. */
  28842. this._lights = [];
  28843. /**
  28844. * For each light in the scene, this node will create a
  28845. * corresponding light node.
  28846. *
  28847. * @private
  28848. * @type {?Array<LightingNode>}
  28849. * @default null
  28850. */
  28851. this._lightNodes = null;
  28852. /**
  28853. * A hash for identifying the current light nodes setup.
  28854. *
  28855. * @private
  28856. * @type {?string}
  28857. * @default null
  28858. */
  28859. this._lightNodesHash = null;
  28860. /**
  28861. * `LightsNode` sets this property to `true` by default.
  28862. *
  28863. * @type {boolean}
  28864. * @default true
  28865. */
  28866. this.global = true;
  28867. }
  28868. /**
  28869. * Overwrites the default {@link Node#customCacheKey} implementation by including
  28870. * light data into the cache key.
  28871. *
  28872. * @return {number} The custom cache key.
  28873. */
  28874. customCacheKey() {
  28875. const lights = this._lights;
  28876. for ( let i = 0; i < lights.length; i ++ ) {
  28877. const light = lights[ i ];
  28878. _hashData.push( light.id );
  28879. _hashData.push( light.castShadow ? 1 : 0 );
  28880. if ( light.isSpotLight === true ) {
  28881. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  28882. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  28883. _hashData.push( hashMap, hashColorNode );
  28884. }
  28885. }
  28886. const cacheKey = hashArray( _hashData );
  28887. _hashData.length = 0;
  28888. return cacheKey;
  28889. }
  28890. /**
  28891. * Computes a hash value for identifying the current light nodes setup.
  28892. *
  28893. * @param {NodeBuilder} builder - A reference to the current node builder.
  28894. * @return {string} The computed hash.
  28895. */
  28896. getHash( builder ) {
  28897. if ( this._lightNodesHash === null ) {
  28898. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28899. const hash = [];
  28900. for ( const lightNode of this._lightNodes ) {
  28901. hash.push( lightNode.getHash() );
  28902. }
  28903. this._lightNodesHash = 'lights-' + hash.join( ',' );
  28904. }
  28905. return this._lightNodesHash;
  28906. }
  28907. analyze( builder ) {
  28908. const properties = builder.getNodeProperties( this );
  28909. for ( const node of properties.nodes ) {
  28910. node.build( builder );
  28911. }
  28912. properties.outputNode.build( builder );
  28913. }
  28914. /**
  28915. * Creates lighting nodes for each scene light. This makes it possible to further
  28916. * process lights in the node system.
  28917. *
  28918. * @param {NodeBuilder} builder - A reference to the current node builder.
  28919. */
  28920. setupLightsNode( builder ) {
  28921. const lightNodes = [];
  28922. const previousLightNodes = this._lightNodes;
  28923. const lights = sortLights( this._lights );
  28924. const nodeLibrary = builder.renderer.library;
  28925. for ( const light of lights ) {
  28926. if ( light.isNode ) {
  28927. lightNodes.push( nodeObject( light ) );
  28928. } else {
  28929. let lightNode = null;
  28930. if ( previousLightNodes !== null ) {
  28931. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  28932. }
  28933. if ( lightNode === null ) {
  28934. // find the corresponding node type for a given light
  28935. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  28936. if ( lightNodeClass === null ) {
  28937. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  28938. continue;
  28939. }
  28940. let lightNode = null;
  28941. if ( ! _lightsNodeRef.has( light ) ) {
  28942. lightNode = nodeObject( new lightNodeClass( light ) );
  28943. _lightsNodeRef.set( light, lightNode );
  28944. } else {
  28945. lightNode = _lightsNodeRef.get( light );
  28946. }
  28947. lightNodes.push( lightNode );
  28948. }
  28949. }
  28950. }
  28951. this._lightNodes = lightNodes;
  28952. }
  28953. /**
  28954. * Sets up a direct light in the lighting model.
  28955. *
  28956. * @param {Object} builder - The builder object containing the context and stack.
  28957. * @param {Object} lightNode - The light node.
  28958. * @param {Object} lightData - The light object containing color and direction properties.
  28959. */
  28960. setupDirectLight( builder, lightNode, lightData ) {
  28961. const { lightingModel, reflectedLight } = builder.context;
  28962. lightingModel.direct( {
  28963. ...lightData,
  28964. lightNode,
  28965. reflectedLight
  28966. }, builder );
  28967. }
  28968. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  28969. const { lightingModel, reflectedLight } = builder.context;
  28970. lightingModel.directRectArea( {
  28971. ...lightData,
  28972. lightNode,
  28973. reflectedLight
  28974. }, builder );
  28975. }
  28976. /**
  28977. * Setups the internal lights by building all respective
  28978. * light nodes.
  28979. *
  28980. * @param {NodeBuilder} builder - A reference to the current node builder.
  28981. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  28982. */
  28983. setupLights( builder, lightNodes ) {
  28984. for ( const lightNode of lightNodes ) {
  28985. lightNode.build( builder );
  28986. }
  28987. }
  28988. getLightNodes( builder ) {
  28989. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28990. return this._lightNodes;
  28991. }
  28992. /**
  28993. * The implementation makes sure that for each light in the scene
  28994. * there is a corresponding light node. By building the light nodes
  28995. * and evaluating the lighting model the outgoing light is computed.
  28996. *
  28997. * @param {NodeBuilder} builder - A reference to the current node builder.
  28998. * @return {Node<vec3>} A node representing the outgoing light.
  28999. */
  29000. setup( builder ) {
  29001. const currentLightsNode = builder.lightsNode;
  29002. builder.lightsNode = this;
  29003. //
  29004. let outgoingLightNode = this.outgoingLightNode;
  29005. const context = builder.context;
  29006. const lightingModel = context.lightingModel;
  29007. const properties = builder.getNodeProperties( this );
  29008. if ( lightingModel ) {
  29009. const { totalDiffuseNode, totalSpecularNode } = this;
  29010. context.outgoingLight = outgoingLightNode;
  29011. const stack = builder.addStack();
  29012. //
  29013. properties.nodes = stack.nodes;
  29014. //
  29015. lightingModel.start( builder );
  29016. //
  29017. const { backdrop, backdropAlpha } = context;
  29018. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  29019. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  29020. if ( backdrop !== null ) {
  29021. if ( backdropAlpha !== null ) {
  29022. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  29023. } else {
  29024. totalDiffuse = vec3( backdrop );
  29025. }
  29026. context.material.transparent = true;
  29027. }
  29028. totalDiffuseNode.assign( totalDiffuse );
  29029. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  29030. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  29031. //
  29032. lightingModel.finish( builder );
  29033. //
  29034. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  29035. } else {
  29036. properties.nodes = [];
  29037. }
  29038. //
  29039. builder.lightsNode = currentLightsNode;
  29040. return outgoingLightNode;
  29041. }
  29042. /**
  29043. * Configures this node with an array of lights.
  29044. *
  29045. * @param {Array<Light>} lights - An array of lights.
  29046. * @return {LightsNode} A reference to this node.
  29047. */
  29048. setLights( lights ) {
  29049. this._lights = lights;
  29050. this._lightNodes = null;
  29051. this._lightNodesHash = null;
  29052. return this;
  29053. }
  29054. /**
  29055. * Returns an array of the scene's lights.
  29056. *
  29057. * @return {Array<Light>} The scene's lights.
  29058. */
  29059. getLights() {
  29060. return this._lights;
  29061. }
  29062. /**
  29063. * Whether the scene has lights or not.
  29064. *
  29065. * @type {boolean}
  29066. */
  29067. get hasLights() {
  29068. return this._lights.length > 0;
  29069. }
  29070. }
  29071. /**
  29072. * TSL function for creating an instance of `LightsNode` and configuring
  29073. * it with the given array of lights.
  29074. *
  29075. * @tsl
  29076. * @function
  29077. * @param {Array<Light>} lights - An array of lights.
  29078. * @return {LightsNode} The created lights node.
  29079. */
  29080. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  29081. /**
  29082. * Base class for all shadow nodes.
  29083. *
  29084. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  29085. * Lighting nodes might share the same shadow node type or use specific ones depending on
  29086. * their requirements.
  29087. *
  29088. * @augments Node
  29089. */
  29090. class ShadowBaseNode extends Node {
  29091. static get type() {
  29092. return 'ShadowBaseNode';
  29093. }
  29094. /**
  29095. * Constructs a new shadow base node.
  29096. *
  29097. * @param {Light} light - The shadow casting light.
  29098. */
  29099. constructor( light ) {
  29100. super();
  29101. /**
  29102. * The shadow casting light.
  29103. *
  29104. * @type {Light}
  29105. */
  29106. this.light = light;
  29107. /**
  29108. * Overwritten since shadows are updated by default per render.
  29109. *
  29110. * @type {string}
  29111. * @default 'render'
  29112. */
  29113. this.updateBeforeType = NodeUpdateType.RENDER;
  29114. /**
  29115. * This flag can be used for type testing.
  29116. *
  29117. * @type {boolean}
  29118. * @readonly
  29119. * @default true
  29120. */
  29121. this.isShadowBaseNode = true;
  29122. }
  29123. /**
  29124. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  29125. *
  29126. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  29127. */
  29128. setupShadowPosition( { context, material } ) {
  29129. // Use assign inside an Fn()
  29130. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  29131. }
  29132. }
  29133. /**
  29134. * TSL object that represents the vertex position in world space during the shadow pass.
  29135. *
  29136. * @tsl
  29137. * @type {Node<vec3>}
  29138. */
  29139. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  29140. /**
  29141. * Saves the state of the given renderer and stores it into the given state object.
  29142. *
  29143. * If not state object is provided, the function creates one.
  29144. *
  29145. * @function
  29146. * @param {Renderer} renderer - The renderer.
  29147. * @param {Object} [state={}] - The state.
  29148. * @return {Object} The state.
  29149. */
  29150. function saveRendererState( renderer, state = {} ) {
  29151. state.toneMapping = renderer.toneMapping;
  29152. state.toneMappingExposure = renderer.toneMappingExposure;
  29153. state.outputColorSpace = renderer.outputColorSpace;
  29154. state.renderTarget = renderer.getRenderTarget();
  29155. state.activeCubeFace = renderer.getActiveCubeFace();
  29156. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  29157. state.renderObjectFunction = renderer.getRenderObjectFunction();
  29158. state.pixelRatio = renderer.getPixelRatio();
  29159. state.mrt = renderer.getMRT();
  29160. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  29161. state.clearAlpha = renderer.getClearAlpha();
  29162. state.autoClear = renderer.autoClear;
  29163. state.scissorTest = renderer.getScissorTest();
  29164. return state;
  29165. }
  29166. /**
  29167. * Saves the state of the given renderer and stores it into the given state object.
  29168. * Besides, the function also resets the state of the renderer to its default values.
  29169. *
  29170. * If not state object is provided, the function creates one.
  29171. *
  29172. * @function
  29173. * @param {Renderer} renderer - The renderer.
  29174. * @param {Object} [state={}] - The state.
  29175. * @return {Object} The state.
  29176. */
  29177. function resetRendererState( renderer, state ) {
  29178. state = saveRendererState( renderer, state );
  29179. renderer.setMRT( null );
  29180. renderer.setRenderObjectFunction( null );
  29181. renderer.setClearColor( 0x000000, 1 );
  29182. renderer.autoClear = true;
  29183. return state;
  29184. }
  29185. /**
  29186. * Restores the state of the given renderer from the given state object.
  29187. *
  29188. * @function
  29189. * @param {Renderer} renderer - The renderer.
  29190. * @param {Object} state - The state to restore.
  29191. */
  29192. function restoreRendererState( renderer, state ) {
  29193. renderer.toneMapping = state.toneMapping;
  29194. renderer.toneMappingExposure = state.toneMappingExposure;
  29195. renderer.outputColorSpace = state.outputColorSpace;
  29196. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  29197. renderer.setRenderObjectFunction( state.renderObjectFunction );
  29198. renderer.setPixelRatio( state.pixelRatio );
  29199. renderer.setMRT( state.mrt );
  29200. renderer.setClearColor( state.clearColor, state.clearAlpha );
  29201. renderer.autoClear = state.autoClear;
  29202. renderer.setScissorTest( state.scissorTest );
  29203. }
  29204. /**
  29205. * Saves the state of the given scene and stores it into the given state object.
  29206. *
  29207. * If not state object is provided, the function creates one.
  29208. *
  29209. * @function
  29210. * @param {Scene} scene - The scene.
  29211. * @param {Object} [state={}] - The state.
  29212. * @return {Object} The state.
  29213. */
  29214. function saveSceneState( scene, state = {} ) {
  29215. state.background = scene.background;
  29216. state.backgroundNode = scene.backgroundNode;
  29217. state.overrideMaterial = scene.overrideMaterial;
  29218. return state;
  29219. }
  29220. /**
  29221. * Saves the state of the given scene and stores it into the given state object.
  29222. * Besides, the function also resets the state of the scene to its default values.
  29223. *
  29224. * If not state object is provided, the function creates one.
  29225. *
  29226. * @function
  29227. * @param {Scene} scene - The scene.
  29228. * @param {Object} [state={}] - The state.
  29229. * @return {Object} The state.
  29230. */
  29231. function resetSceneState( scene, state ) {
  29232. state = saveSceneState( scene, state );
  29233. scene.background = null;
  29234. scene.backgroundNode = null;
  29235. scene.overrideMaterial = null;
  29236. return state;
  29237. }
  29238. /**
  29239. * Restores the state of the given scene from the given state object.
  29240. *
  29241. * @function
  29242. * @param {Scene} scene - The scene.
  29243. * @param {Object} state - The state to restore.
  29244. */
  29245. function restoreSceneState( scene, state ) {
  29246. scene.background = state.background;
  29247. scene.backgroundNode = state.backgroundNode;
  29248. scene.overrideMaterial = state.overrideMaterial;
  29249. }
  29250. /**
  29251. * Saves the state of the given renderer and scene and stores it into the given state object.
  29252. *
  29253. * If not state object is provided, the function creates one.
  29254. *
  29255. * @function
  29256. * @param {Renderer} renderer - The renderer.
  29257. * @param {Scene} scene - The scene.
  29258. * @param {Object} [state={}] - The state.
  29259. * @return {Object} The state.
  29260. */
  29261. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  29262. state = saveRendererState( renderer, state );
  29263. state = saveSceneState( scene, state );
  29264. return state;
  29265. }
  29266. /**
  29267. * Saves the state of the given renderer and scene and stores it into the given state object.
  29268. * Besides, the function also resets the state of the renderer and scene to its default values.
  29269. *
  29270. * If not state object is provided, the function creates one.
  29271. *
  29272. * @function
  29273. * @param {Renderer} renderer - The renderer.
  29274. * @param {Scene} scene - The scene.
  29275. * @param {Object} [state={}] - The state.
  29276. * @return {Object} The state.
  29277. */
  29278. function resetRendererAndSceneState( renderer, scene, state ) {
  29279. state = resetRendererState( renderer, state );
  29280. state = resetSceneState( scene, state );
  29281. return state;
  29282. }
  29283. /**
  29284. * Restores the state of the given renderer and scene from the given state object.
  29285. *
  29286. * @function
  29287. * @param {Renderer} renderer - The renderer.
  29288. * @param {Scene} scene - The scene.
  29289. * @param {Object} state - The state to restore.
  29290. */
  29291. function restoreRendererAndSceneState( renderer, scene, state ) {
  29292. restoreRendererState( renderer, state );
  29293. restoreSceneState( scene, state );
  29294. }
  29295. var RendererUtils = /*#__PURE__*/Object.freeze({
  29296. __proto__: null,
  29297. resetRendererAndSceneState: resetRendererAndSceneState,
  29298. resetRendererState: resetRendererState,
  29299. resetSceneState: resetSceneState,
  29300. restoreRendererAndSceneState: restoreRendererAndSceneState,
  29301. restoreRendererState: restoreRendererState,
  29302. restoreSceneState: restoreSceneState,
  29303. saveRendererAndSceneState: saveRendererAndSceneState,
  29304. saveRendererState: saveRendererState,
  29305. saveSceneState: saveSceneState
  29306. });
  29307. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  29308. /**
  29309. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  29310. * with a binary `[0,1]` result.
  29311. *
  29312. * @method
  29313. * @param {Object} inputs - The input parameter object.
  29314. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29315. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29316. * @return {Node<float>} The filtering result.
  29317. */
  29318. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29319. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  29320. if ( depthTexture.isArrayTexture ) {
  29321. basic = basic.depth( depthLayer );
  29322. }
  29323. return basic.compare( shadowCoord.z );
  29324. } );
  29325. /**
  29326. * A shadow filtering function performing PCF filtering.
  29327. *
  29328. * @method
  29329. * @param {Object} inputs - The input parameter object.
  29330. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29331. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29332. * @param {LightShadow} inputs.shadow - The light shadow.
  29333. * @return {Node<float>} The filtering result.
  29334. */
  29335. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29336. const depthCompare = ( uv, compare ) => {
  29337. let depth = texture( depthTexture, uv );
  29338. if ( depthTexture.isArrayTexture ) {
  29339. depth = depth.depth( depthLayer );
  29340. }
  29341. return depth.compare( compare );
  29342. };
  29343. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29344. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29345. const texelSize = vec2( 1 ).div( mapSize );
  29346. const dx0 = texelSize.x.negate().mul( radius );
  29347. const dy0 = texelSize.y.negate().mul( radius );
  29348. const dx1 = texelSize.x.mul( radius );
  29349. const dy1 = texelSize.y.mul( radius );
  29350. const dx2 = dx0.div( 2 );
  29351. const dy2 = dy0.div( 2 );
  29352. const dx3 = dx1.div( 2 );
  29353. const dy3 = dy1.div( 2 );
  29354. return add(
  29355. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  29356. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  29357. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  29358. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  29359. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  29360. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  29361. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  29362. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  29363. depthCompare( shadowCoord.xy, shadowCoord.z ),
  29364. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  29365. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  29366. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  29367. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  29368. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  29369. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  29370. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  29371. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  29372. ).mul( 1 / 17 );
  29373. } );
  29374. /**
  29375. * A shadow filtering function performing PCF soft filtering.
  29376. *
  29377. * @method
  29378. * @param {Object} inputs - The input parameter object.
  29379. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29380. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29381. * @param {LightShadow} inputs.shadow - The light shadow.
  29382. * @return {Node<float>} The filtering result.
  29383. */
  29384. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29385. const depthCompare = ( uv, compare ) => {
  29386. let depth = texture( depthTexture, uv );
  29387. if ( depthTexture.isArrayTexture ) {
  29388. depth = depth.depth( depthLayer );
  29389. }
  29390. return depth.compare( compare );
  29391. };
  29392. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29393. const texelSize = vec2( 1 ).div( mapSize );
  29394. const dx = texelSize.x;
  29395. const dy = texelSize.y;
  29396. const uv = shadowCoord.xy;
  29397. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  29398. uv.subAssign( f.mul( texelSize ) );
  29399. return add(
  29400. depthCompare( uv, shadowCoord.z ),
  29401. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  29402. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  29403. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  29404. mix(
  29405. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  29406. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  29407. f.x
  29408. ),
  29409. mix(
  29410. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  29411. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  29412. f.x
  29413. ),
  29414. mix(
  29415. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  29416. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  29417. f.y
  29418. ),
  29419. mix(
  29420. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  29421. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  29422. f.y
  29423. ),
  29424. mix(
  29425. mix(
  29426. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  29427. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  29428. f.x
  29429. ),
  29430. mix(
  29431. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  29432. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  29433. f.x
  29434. ),
  29435. f.y
  29436. )
  29437. ).mul( 1 / 9 );
  29438. } );
  29439. /**
  29440. * A shadow filtering function performing VSM filtering.
  29441. *
  29442. * @method
  29443. * @param {Object} inputs - The input parameter object.
  29444. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29445. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29446. * @return {Node<float>} The filtering result.
  29447. */
  29448. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29449. const occlusion = float( 1 ).toVar();
  29450. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  29451. if ( depthTexture.isArrayTexture ) {
  29452. distribution = distribution.depth( depthLayer );
  29453. }
  29454. distribution = distribution.rg;
  29455. const hardShadow = step( shadowCoord.z, distribution.x );
  29456. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  29457. const distance = shadowCoord.z.sub( distribution.x );
  29458. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  29459. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  29460. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  29461. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  29462. } );
  29463. return occlusion;
  29464. } );
  29465. //
  29466. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  29467. let dist = positionWorld.sub( position ).length();
  29468. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  29469. dist = dist.saturate(); // clamp to [ 0, 1 ]
  29470. return dist;
  29471. } );
  29472. const linearShadowDistance = ( light ) => {
  29473. const camera = light.shadow.camera;
  29474. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  29475. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  29476. const referencePosition = objectPosition( light );
  29477. return linearDistance( referencePosition, nearDistance, farDistance );
  29478. };
  29479. /**
  29480. * Retrieves or creates a shadow material for the given light source.
  29481. *
  29482. * This function checks if a shadow material already exists for the provided light.
  29483. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  29484. * in the `shadowMaterialLib` for future use.
  29485. *
  29486. * @param {Light} light - The light source for which the shadow material is needed.
  29487. * If the light is a point light, a depth node is calculated
  29488. * using the linear shadow distance.
  29489. * @returns {NodeMaterial} The shadow material associated with the given light.
  29490. */
  29491. const getShadowMaterial = ( light ) => {
  29492. let material = shadowMaterialLib.get( light );
  29493. if ( material === undefined ) {
  29494. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  29495. material = new NodeMaterial();
  29496. material.colorNode = vec4( 0, 0, 0, 1 );
  29497. material.depthNode = depthNode;
  29498. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  29499. material.name = 'ShadowMaterial';
  29500. material.fog = false;
  29501. shadowMaterialLib.set( light, material );
  29502. }
  29503. return material;
  29504. };
  29505. //
  29506. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  29507. const _shadowRenderObjectKeys = [];
  29508. /**
  29509. * Creates a function to render shadow objects in a scene.
  29510. *
  29511. * @param {Renderer} renderer - The renderer.
  29512. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  29513. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  29514. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  29515. * @return {Function} A function that renders shadow objects.
  29516. *
  29517. * The returned function has the following parameters:
  29518. * @param {Object3D} object - The 3D object to render.
  29519. * @param {Scene} scene - The scene containing the object.
  29520. * @param {Camera} _camera - The camera used for rendering.
  29521. * @param {BufferGeometry} geometry - The geometry of the object.
  29522. * @param {Material} material - The material of the object.
  29523. * @param {Group} group - The group the object belongs to.
  29524. * @param {...any} params - Additional parameters for rendering.
  29525. */
  29526. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  29527. _shadowRenderObjectKeys[ 0 ] = renderer;
  29528. _shadowRenderObjectKeys[ 1 ] = shadow;
  29529. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  29530. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  29531. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  29532. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  29533. if ( useVelocity ) {
  29534. getDataFromObject( object ).useVelocity = true;
  29535. }
  29536. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29537. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  29538. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29539. }
  29540. };
  29541. renderObjectFunction.shadowType = shadowType;
  29542. renderObjectFunction.useVelocity = useVelocity;
  29543. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  29544. }
  29545. _shadowRenderObjectKeys[ 0 ] = null;
  29546. _shadowRenderObjectKeys[ 1 ] = null;
  29547. return renderObjectFunction;
  29548. };
  29549. /**
  29550. * Represents the shader code for the first VSM render pass.
  29551. *
  29552. * @method
  29553. * @param {Object} inputs - The input parameter object.
  29554. * @param {Node<float>} inputs.samples - The number of samples
  29555. * @param {Node<float>} inputs.radius - The radius.
  29556. * @param {Node<float>} inputs.size - The size.
  29557. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  29558. * @return {Node<vec2>} The VSM output.
  29559. */
  29560. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29561. const mean = float( 0 ).toVar( 'meanVertical' );
  29562. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  29563. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29564. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29565. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29566. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29567. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  29568. if ( shadowPass.value.isArrayTexture ) {
  29569. depth = depth.depth( depthLayer );
  29570. }
  29571. depth = depth.x;
  29572. mean.addAssign( depth );
  29573. squaredMean.addAssign( depth.mul( depth ) );
  29574. } );
  29575. mean.divAssign( samples );
  29576. squaredMean.divAssign( samples );
  29577. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29578. return vec2( mean, std_dev );
  29579. } );
  29580. /**
  29581. * Represents the shader code for the second VSM render pass.
  29582. *
  29583. * @method
  29584. * @param {Object} inputs - The input parameter object.
  29585. * @param {Node<float>} inputs.samples - The number of samples
  29586. * @param {Node<float>} inputs.radius - The radius.
  29587. * @param {Node<float>} inputs.size - The size.
  29588. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  29589. * @return {Node<vec2>} The VSM output.
  29590. */
  29591. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29592. const mean = float( 0 ).toVar( 'meanHorizontal' );
  29593. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  29594. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29595. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29596. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29597. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29598. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  29599. if ( shadowPass.value.isArrayTexture ) {
  29600. distribution = distribution.depth( depthLayer );
  29601. }
  29602. mean.addAssign( distribution.x );
  29603. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  29604. } );
  29605. mean.divAssign( samples );
  29606. squaredMean.divAssign( samples );
  29607. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29608. return vec2( mean, std_dev );
  29609. } );
  29610. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  29611. //
  29612. let _rendererState;
  29613. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  29614. /**
  29615. * Represents the default shadow implementation for lighting nodes.
  29616. *
  29617. * @augments ShadowBaseNode
  29618. */
  29619. class ShadowNode extends ShadowBaseNode {
  29620. static get type() {
  29621. return 'ShadowNode';
  29622. }
  29623. /**
  29624. * Constructs a new shadow node.
  29625. *
  29626. * @param {Light} light - The shadow casting light.
  29627. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  29628. */
  29629. constructor( light, shadow = null ) {
  29630. super( light );
  29631. /**
  29632. * The light shadow which defines the properties light's
  29633. * shadow.
  29634. *
  29635. * @type {?LightShadow}
  29636. * @default null
  29637. */
  29638. this.shadow = shadow || light.shadow;
  29639. /**
  29640. * A reference to the shadow map which is a render target.
  29641. *
  29642. * @type {?RenderTarget}
  29643. * @default null
  29644. */
  29645. this.shadowMap = null;
  29646. /**
  29647. * Only relevant for VSM shadows. Render target for the
  29648. * first VSM render pass.
  29649. *
  29650. * @type {?RenderTarget}
  29651. * @default null
  29652. */
  29653. this.vsmShadowMapVertical = null;
  29654. /**
  29655. * Only relevant for VSM shadows. Render target for the
  29656. * second VSM render pass.
  29657. *
  29658. * @type {?RenderTarget}
  29659. * @default null
  29660. */
  29661. this.vsmShadowMapHorizontal = null;
  29662. /**
  29663. * Only relevant for VSM shadows. Node material which
  29664. * is used to render the first VSM pass.
  29665. *
  29666. * @type {?NodeMaterial}
  29667. * @default null
  29668. */
  29669. this.vsmMaterialVertical = null;
  29670. /**
  29671. * Only relevant for VSM shadows. Node material which
  29672. * is used to render the second VSM pass.
  29673. *
  29674. * @type {?NodeMaterial}
  29675. * @default null
  29676. */
  29677. this.vsmMaterialHorizontal = null;
  29678. /**
  29679. * A reference to the output node which defines the
  29680. * final result of this shadow node.
  29681. *
  29682. * @type {?Node}
  29683. * @private
  29684. * @default null
  29685. */
  29686. this._node = null;
  29687. this._cameraFrameId = new WeakMap();
  29688. /**
  29689. * This flag can be used for type testing.
  29690. *
  29691. * @type {boolean}
  29692. * @readonly
  29693. * @default true
  29694. */
  29695. this.isShadowNode = true;
  29696. /**
  29697. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  29698. *
  29699. * @type {number}
  29700. * @readonly
  29701. * @default true
  29702. */
  29703. this.depthLayer = 0;
  29704. }
  29705. /**
  29706. * Setups the shadow filtering.
  29707. *
  29708. * @param {NodeBuilder} builder - A reference to the current node builder.
  29709. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29710. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29711. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29712. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29713. * @param {LightShadow} inputs.shadow - The light shadow.
  29714. * @return {Node<float>} The result node of the shadow filtering.
  29715. */
  29716. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  29717. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  29718. .and( shadowCoord.x.lessThanEqual( 1 ) )
  29719. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  29720. .and( shadowCoord.y.lessThanEqual( 1 ) )
  29721. .and( shadowCoord.z.lessThanEqual( 1 ) );
  29722. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  29723. return frustumTest.select( shadowNode, float( 1 ) );
  29724. }
  29725. /**
  29726. * Setups the shadow coordinates.
  29727. *
  29728. * @param {NodeBuilder} builder - A reference to the current node builder.
  29729. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29730. * @return {Node<vec3>} The shadow coordinates.
  29731. */
  29732. setupShadowCoord( builder, shadowPosition ) {
  29733. const { shadow } = this;
  29734. const { renderer } = builder;
  29735. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29736. let shadowCoord = shadowPosition;
  29737. let coordZ;
  29738. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  29739. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  29740. coordZ = shadowCoord.z;
  29741. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  29742. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  29743. }
  29744. } else {
  29745. const w = shadowCoord.w;
  29746. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  29747. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  29748. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  29749. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  29750. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  29751. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  29752. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  29753. }
  29754. shadowCoord = vec3(
  29755. shadowCoord.x,
  29756. shadowCoord.y.oneMinus(), // follow webgpu standards
  29757. coordZ.add( bias )
  29758. );
  29759. return shadowCoord;
  29760. }
  29761. /**
  29762. * Returns the shadow filtering function for the given shadow type.
  29763. *
  29764. * @param {number} type - The shadow type.
  29765. * @return {Function} The filtering function.
  29766. */
  29767. getShadowFilterFn( type ) {
  29768. return _shadowFilterLib[ type ];
  29769. }
  29770. setupRenderTarget( shadow, builder ) {
  29771. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  29772. depthTexture.name = 'ShadowDepthTexture';
  29773. depthTexture.compareFunction = LessCompare;
  29774. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  29775. shadowMap.texture.name = 'ShadowMap';
  29776. shadowMap.texture.type = shadow.mapType;
  29777. shadowMap.depthTexture = depthTexture;
  29778. return { shadowMap, depthTexture };
  29779. }
  29780. /**
  29781. * Setups the shadow output node.
  29782. *
  29783. * @param {NodeBuilder} builder - A reference to the current node builder.
  29784. * @return {Node<vec3>} The shadow output node.
  29785. */
  29786. setupShadow( builder ) {
  29787. const { renderer } = builder;
  29788. const { light, shadow } = this;
  29789. const shadowMapType = renderer.shadowMap.type;
  29790. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  29791. shadow.camera.updateProjectionMatrix();
  29792. // VSM
  29793. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29794. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  29795. if ( shadowMap.depth > 1 ) {
  29796. if ( ! shadowMap._vsmShadowMapVertical ) {
  29797. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29798. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  29799. }
  29800. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  29801. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  29802. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29803. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  29804. }
  29805. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  29806. } else {
  29807. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29808. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29809. }
  29810. let shadowPassVertical = texture( depthTexture );
  29811. if ( depthTexture.isArrayTexture ) {
  29812. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  29813. }
  29814. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  29815. if ( depthTexture.isArrayTexture ) {
  29816. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  29817. }
  29818. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  29819. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29820. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29821. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  29822. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29823. material.name = 'VSMVertical';
  29824. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  29825. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29826. material.name = 'VSMHorizontal';
  29827. }
  29828. //
  29829. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  29830. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  29831. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  29832. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  29833. //
  29834. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  29835. if ( filterFn === null ) {
  29836. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  29837. }
  29838. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  29839. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  29840. let shadowColor = texture( shadowMap.texture, shadowCoord );
  29841. if ( depthTexture.isArrayTexture ) {
  29842. shadowColor = shadowColor.depth( this.depthLayer );
  29843. }
  29844. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  29845. this.shadowMap = shadowMap;
  29846. this.shadow.map = shadowMap;
  29847. // Shadow Output + Inspector
  29848. const inspectName = `${ this.light.type } Shadow [ ${ this.light.name || 'ID: ' + this.light.id } ]`;
  29849. return shadowOutput.toInspector( `${ inspectName } / Color`, () => {
  29850. return texture( this.shadowMap.texture );
  29851. } ).toInspector( `${ inspectName } / Depth`, () => {
  29852. return textureLoad( this.shadowMap.depthTexture, uv$1().mul( textureSize( texture( this.shadowMap.depthTexture ) ) ) ).x.oneMinus();
  29853. } );
  29854. }
  29855. /**
  29856. * The implementation performs the setup of the output node. An output is only
  29857. * produces if shadow mapping is globally enabled in the renderer.
  29858. *
  29859. * @param {NodeBuilder} builder - A reference to the current node builder.
  29860. * @return {ShaderCallNodeInternal} The output node.
  29861. */
  29862. setup( builder ) {
  29863. if ( builder.renderer.shadowMap.enabled === false ) return;
  29864. return Fn( () => {
  29865. let node = this._node;
  29866. this.setupShadowPosition( builder );
  29867. if ( node === null ) {
  29868. this._node = node = this.setupShadow( builder );
  29869. }
  29870. if ( builder.material.shadowNode ) { // @deprecated, r171
  29871. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  29872. }
  29873. if ( builder.material.receivedShadowNode ) {
  29874. node = builder.material.receivedShadowNode( node );
  29875. }
  29876. return node;
  29877. } )();
  29878. }
  29879. /**
  29880. * Renders the shadow. The logic of this function could be included
  29881. * into {@link ShadowNode#updateShadow} however more specialized shadow
  29882. * nodes might require a custom shadow map rendering. By having a
  29883. * dedicated method, it's easier to overwrite the default behavior.
  29884. *
  29885. * @param {NodeFrame} frame - A reference to the current node frame.
  29886. */
  29887. renderShadow( frame ) {
  29888. const { shadow, shadowMap, light } = this;
  29889. const { renderer, scene } = frame;
  29890. shadow.updateMatrices( light );
  29891. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  29892. const currentSceneName = scene.name;
  29893. scene.name = `Shadow Map [ ${ light.name || 'ID: ' + light.id } ]`;
  29894. renderer.render( scene, shadow.camera );
  29895. scene.name = currentSceneName;
  29896. }
  29897. /**
  29898. * Updates the shadow.
  29899. *
  29900. * @param {NodeFrame} frame - A reference to the current node frame.
  29901. */
  29902. updateShadow( frame ) {
  29903. const { shadowMap, light, shadow } = this;
  29904. const { renderer, scene, camera } = frame;
  29905. const shadowType = renderer.shadowMap.type;
  29906. const depthVersion = shadowMap.depthTexture.version;
  29907. this._depthVersionCached = depthVersion;
  29908. const _shadowCameraLayer = shadow.camera.layers.mask;
  29909. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  29910. shadow.camera.layers.mask = camera.layers.mask;
  29911. }
  29912. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  29913. const currentMRT = renderer.getMRT();
  29914. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  29915. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  29916. scene.overrideMaterial = getShadowMaterial( light );
  29917. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  29918. renderer.setClearColor( 0x000000, 0 );
  29919. renderer.setRenderTarget( shadowMap );
  29920. this.renderShadow( frame );
  29921. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  29922. // vsm blur pass
  29923. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29924. this.vsmPass( renderer );
  29925. }
  29926. shadow.camera.layers.mask = _shadowCameraLayer;
  29927. restoreRendererAndSceneState( renderer, scene, _rendererState );
  29928. }
  29929. /**
  29930. * For VSM additional render passes are required.
  29931. *
  29932. * @param {Renderer} renderer - A reference to the current renderer.
  29933. */
  29934. vsmPass( renderer ) {
  29935. const { shadow } = this;
  29936. const depth = this.shadowMap.depth;
  29937. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29938. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29939. renderer.setRenderTarget( this.vsmShadowMapVertical );
  29940. _quadMesh.material = this.vsmMaterialVertical;
  29941. _quadMesh.render( renderer );
  29942. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  29943. _quadMesh.material = this.vsmMaterialHorizontal;
  29944. _quadMesh.render( renderer );
  29945. }
  29946. /**
  29947. * Frees the internal resources of this shadow node.
  29948. */
  29949. dispose() {
  29950. this.shadowMap.dispose();
  29951. this.shadowMap = null;
  29952. if ( this.vsmShadowMapVertical !== null ) {
  29953. this.vsmShadowMapVertical.dispose();
  29954. this.vsmShadowMapVertical = null;
  29955. this.vsmMaterialVertical.dispose();
  29956. this.vsmMaterialVertical = null;
  29957. }
  29958. if ( this.vsmShadowMapHorizontal !== null ) {
  29959. this.vsmShadowMapHorizontal.dispose();
  29960. this.vsmShadowMapHorizontal = null;
  29961. this.vsmMaterialHorizontal.dispose();
  29962. this.vsmMaterialHorizontal = null;
  29963. }
  29964. super.dispose();
  29965. }
  29966. /**
  29967. * The implementation performs the update of the shadow map if necessary.
  29968. *
  29969. * @param {NodeFrame} frame - A reference to the current node frame.
  29970. */
  29971. updateBefore( frame ) {
  29972. const { shadow } = this;
  29973. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  29974. if ( needsUpdate ) {
  29975. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  29976. needsUpdate = false;
  29977. }
  29978. this._cameraFrameId[ frame.camera ] = frame.frameId;
  29979. }
  29980. if ( needsUpdate ) {
  29981. this.updateShadow( frame );
  29982. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  29983. shadow.needsUpdate = false;
  29984. }
  29985. }
  29986. }
  29987. }
  29988. /**
  29989. * TSL function for creating an instance of `ShadowNode`.
  29990. *
  29991. * @tsl
  29992. * @function
  29993. * @param {Light} light - The shadow casting light.
  29994. * @param {?LightShadow} [shadow] - The light shadow.
  29995. * @return {ShadowNode} The created shadow node.
  29996. */
  29997. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  29998. const _clearColor$1 = /*@__PURE__*/ new Color();
  29999. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  30000. // vector suitable for 2D texture mapping. This code uses the following layout for the
  30001. // 2D texture:
  30002. //
  30003. // xzXZ
  30004. // y Y
  30005. //
  30006. // Y - Positive y direction
  30007. // y - Negative y direction
  30008. // X - Positive x direction
  30009. // x - Negative x direction
  30010. // Z - Positive z direction
  30011. // z - Negative z direction
  30012. //
  30013. // Source and test bed:
  30014. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  30015. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  30016. const v = pos.toVar();
  30017. // Number of texels to avoid at the edge of each square
  30018. const absV = abs( v );
  30019. // Intersect unit cube
  30020. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  30021. absV.mulAssign( scaleToCube );
  30022. // Apply scale to avoid seams
  30023. // two texels less per square (one texel will do for NEAREST)
  30024. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  30025. // Unwrap
  30026. // space: -1 ... 1 range for each square
  30027. //
  30028. // #X## dim := ( 4 , 2 )
  30029. // # # center := ( 1 , 1 )
  30030. const planar = vec2( v.xy ).toVar();
  30031. const almostATexel = texelSizeY.mul( 1.5 );
  30032. const almostOne = almostATexel.oneMinus();
  30033. If( absV.z.greaterThanEqual( almostOne ), () => {
  30034. If( v.z.greaterThan( 0.0 ), () => {
  30035. planar.x.assign( sub( 4.0, v.x ) );
  30036. } );
  30037. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  30038. const signX = sign( v.x );
  30039. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  30040. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  30041. const signY = sign( v.y );
  30042. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  30043. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  30044. } );
  30045. // Transform to UV space
  30046. // scale := 0.5 / dim
  30047. // translate := ( center + 0.5 ) / dim
  30048. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  30049. } ).setLayout( {
  30050. name: 'cubeToUV',
  30051. type: 'vec2',
  30052. inputs: [
  30053. { name: 'pos', type: 'vec3' },
  30054. { name: 'texelSizeY', type: 'float' }
  30055. ]
  30056. } );
  30057. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  30058. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  30059. } );
  30060. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  30061. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  30062. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  30063. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  30064. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  30065. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  30066. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  30067. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  30068. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  30069. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  30070. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  30071. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  30072. .mul( 1.0 / 9.0 );
  30073. } );
  30074. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  30075. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  30076. // the vector from the light to the world-space position of the fragment.
  30077. const lightToPosition = shadowCoord.xyz.toVar();
  30078. const lightToPositionLength = lightToPosition.length();
  30079. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  30080. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  30081. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  30082. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  30083. const result = float( 1.0 ).toVar();
  30084. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  30085. // dp = normalized distance from light to fragment position
  30086. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  30087. dp.addAssign( bias );
  30088. // bd3D = base direction 3D
  30089. const bd3D = lightToPosition.normalize();
  30090. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  30091. // percentage-closer filtering
  30092. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  30093. } );
  30094. return result;
  30095. } );
  30096. const _viewport = /*@__PURE__*/ new Vector4();
  30097. const _viewportSize = /*@__PURE__*/ new Vector2();
  30098. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  30099. /**
  30100. * Represents the shadow implementation for point light nodes.
  30101. *
  30102. * @augments ShadowNode
  30103. */
  30104. class PointShadowNode extends ShadowNode {
  30105. static get type() {
  30106. return 'PointShadowNode';
  30107. }
  30108. /**
  30109. * Constructs a new point shadow node.
  30110. *
  30111. * @param {PointLight} light - The shadow casting point light.
  30112. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30113. */
  30114. constructor( light, shadow = null ) {
  30115. super( light, shadow );
  30116. }
  30117. /**
  30118. * Overwrites the default implementation to return point light shadow specific
  30119. * filtering functions.
  30120. *
  30121. * @param {number} type - The shadow type.
  30122. * @return {Function} The filtering function.
  30123. */
  30124. getShadowFilterFn( type ) {
  30125. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  30126. }
  30127. /**
  30128. * Overwrites the default implementation so the unaltered shadow position is used.
  30129. *
  30130. * @param {NodeBuilder} builder - A reference to the current node builder.
  30131. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  30132. * @return {Node<vec3>} The shadow coordinates.
  30133. */
  30134. setupShadowCoord( builder, shadowPosition ) {
  30135. return shadowPosition;
  30136. }
  30137. /**
  30138. * Overwrites the default implementation to only use point light specific
  30139. * shadow filter functions.
  30140. *
  30141. * @param {NodeBuilder} builder - A reference to the current node builder.
  30142. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  30143. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  30144. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  30145. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  30146. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  30147. * @param {LightShadow} inputs.shadow - The light shadow.
  30148. * @return {Node<float>} The result node of the shadow filtering.
  30149. */
  30150. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  30151. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  30152. }
  30153. /**
  30154. * Overwrites the default implementation with point light specific
  30155. * rendering code.
  30156. *
  30157. * @param {NodeFrame} frame - A reference to the current node frame.
  30158. */
  30159. renderShadow( frame ) {
  30160. const { shadow, shadowMap, light } = this;
  30161. const { renderer, scene } = frame;
  30162. const shadowFrameExtents = shadow.getFrameExtents();
  30163. _shadowMapSize.copy( shadow.mapSize );
  30164. _shadowMapSize.multiply( shadowFrameExtents );
  30165. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  30166. _viewportSize.copy( shadow.mapSize );
  30167. //
  30168. const previousAutoClear = renderer.autoClear;
  30169. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  30170. const previousClearAlpha = renderer.getClearAlpha();
  30171. renderer.autoClear = false;
  30172. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  30173. renderer.clear();
  30174. const viewportCount = shadow.getViewportCount();
  30175. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  30176. const viewport = shadow.getViewport( vp );
  30177. const x = _viewportSize.x * viewport.x;
  30178. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  30179. _viewport.set(
  30180. x,
  30181. y,
  30182. _viewportSize.x * viewport.z,
  30183. _viewportSize.y * viewport.w
  30184. );
  30185. shadowMap.viewport.copy( _viewport );
  30186. shadow.updateMatrices( light, vp );
  30187. const currentSceneName = scene.name;
  30188. scene.name = `Point Light Shadow [ ${ light.name || 'ID: ' + light.id } ] - Face ${ vp + 1 }`;
  30189. renderer.render( scene, shadow.camera );
  30190. scene.name = currentSceneName;
  30191. }
  30192. //
  30193. renderer.autoClear = previousAutoClear;
  30194. renderer.setClearColor( previousClearColor, previousClearAlpha );
  30195. }
  30196. }
  30197. /**
  30198. * TSL function for creating an instance of `PointShadowNode`.
  30199. *
  30200. * @tsl
  30201. * @function
  30202. * @param {PointLight} light - The shadow casting point light.
  30203. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  30204. * @return {PointShadowNode} The created point shadow node.
  30205. */
  30206. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  30207. /**
  30208. * Base class for analytic light nodes.
  30209. *
  30210. * @augments LightingNode
  30211. */
  30212. class AnalyticLightNode extends LightingNode {
  30213. static get type() {
  30214. return 'AnalyticLightNode';
  30215. }
  30216. /**
  30217. * Constructs a new analytic light node.
  30218. *
  30219. * @param {?Light} [light=null] - The light source.
  30220. */
  30221. constructor( light = null ) {
  30222. super();
  30223. /**
  30224. * The light source.
  30225. *
  30226. * @type {?Light}
  30227. * @default null
  30228. */
  30229. this.light = light;
  30230. /**
  30231. * The light's color value.
  30232. *
  30233. * @type {Color}
  30234. */
  30235. this.color = new Color();
  30236. /**
  30237. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  30238. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  30239. *
  30240. * @type {Node}
  30241. */
  30242. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  30243. /**
  30244. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  30245. * The final color node is represented by a different node when using shadows.
  30246. *
  30247. * @type {?Node}
  30248. * @default null
  30249. */
  30250. this.baseColorNode = null;
  30251. /**
  30252. * Represents the light's shadow.
  30253. *
  30254. * @type {?ShadowNode}
  30255. * @default null
  30256. */
  30257. this.shadowNode = null;
  30258. /**
  30259. * Represents the light's shadow color.
  30260. *
  30261. * @type {?Node}
  30262. * @default null
  30263. */
  30264. this.shadowColorNode = null;
  30265. /**
  30266. * This flag can be used for type testing.
  30267. *
  30268. * @type {boolean}
  30269. * @readonly
  30270. * @default true
  30271. */
  30272. this.isAnalyticLightNode = true;
  30273. /**
  30274. * Overwritten since analytic light nodes are updated
  30275. * once per frame.
  30276. *
  30277. * @type {string}
  30278. * @default 'frame'
  30279. */
  30280. this.updateType = NodeUpdateType.FRAME;
  30281. }
  30282. getHash() {
  30283. return this.light.uuid;
  30284. }
  30285. /**
  30286. * Returns a node representing a direction vector which points from the current
  30287. * position in view space to the light's position in view space.
  30288. *
  30289. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30290. * @return {Node<vec3>} The light vector node.
  30291. */
  30292. getLightVector( builder ) {
  30293. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  30294. }
  30295. /**
  30296. * Sets up the direct lighting for the analytic light node.
  30297. *
  30298. * @abstract
  30299. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30300. * @return {Object|undefined} The direct light data (color and direction).
  30301. */
  30302. setupDirect( /*builder*/ ) { }
  30303. /**
  30304. * Sets up the direct rect area lighting for the analytic light node.
  30305. *
  30306. * @abstract
  30307. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30308. * @return {Object|undefined} The direct rect area light data.
  30309. */
  30310. setupDirectRectArea( /*builder*/ ) { }
  30311. /**
  30312. * Setups the shadow node for this light. The method exists so concrete light classes
  30313. * can setup different types of shadow nodes.
  30314. *
  30315. * @return {ShadowNode} The created shadow node.
  30316. */
  30317. setupShadowNode() {
  30318. return shadow( this.light );
  30319. }
  30320. /**
  30321. * Setups the shadow for this light. This method is only executed if the light
  30322. * cast shadows and the current build object receives shadows. It incorporates
  30323. * shadows into the lighting computation.
  30324. *
  30325. * @param {NodeBuilder} builder - The current node builder.
  30326. */
  30327. setupShadow( builder ) {
  30328. const { renderer } = builder;
  30329. if ( renderer.shadowMap.enabled === false ) return;
  30330. let shadowColorNode = this.shadowColorNode;
  30331. if ( shadowColorNode === null ) {
  30332. const customShadowNode = this.light.shadow.shadowNode;
  30333. let shadowNode;
  30334. if ( customShadowNode !== undefined ) {
  30335. shadowNode = nodeObject( customShadowNode );
  30336. } else {
  30337. shadowNode = this.setupShadowNode();
  30338. }
  30339. this.shadowNode = shadowNode;
  30340. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  30341. this.baseColorNode = this.colorNode;
  30342. }
  30343. //
  30344. this.colorNode = shadowColorNode;
  30345. }
  30346. /**
  30347. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  30348. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  30349. * invocate the respective interface methods.
  30350. *
  30351. * @param {NodeBuilder} builder - The current node builder.
  30352. */
  30353. setup( builder ) {
  30354. this.colorNode = this.baseColorNode || this.colorNode;
  30355. if ( this.light.castShadow ) {
  30356. if ( builder.object.receiveShadow ) {
  30357. this.setupShadow( builder );
  30358. }
  30359. } else if ( this.shadowNode !== null ) {
  30360. this.shadowNode.dispose();
  30361. this.shadowNode = null;
  30362. this.shadowColorNode = null;
  30363. }
  30364. const directLightData = this.setupDirect( builder );
  30365. const directRectAreaLightData = this.setupDirectRectArea( builder );
  30366. if ( directLightData ) {
  30367. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  30368. }
  30369. if ( directRectAreaLightData ) {
  30370. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  30371. }
  30372. }
  30373. /**
  30374. * The update method is used to update light uniforms per frame.
  30375. * Potentially overwritten in concrete light nodes to update light
  30376. * specific uniforms.
  30377. *
  30378. * @param {NodeFrame} frame - A reference to the current node frame.
  30379. */
  30380. update( /*frame*/ ) {
  30381. const { light } = this;
  30382. this.color.copy( light.color ).multiplyScalar( light.intensity );
  30383. }
  30384. }
  30385. /**
  30386. * Represents a `discard` shader operation in TSL.
  30387. *
  30388. * @method
  30389. * @param {Object} inputs - The input parameter object.
  30390. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  30391. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  30392. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  30393. * @return {Node<float>} The distance falloff.
  30394. */
  30395. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  30396. // based upon Frostbite 3 Moving to Physically-based Rendering
  30397. // page 32, equation 26: E[window1]
  30398. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  30399. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  30400. return cutoffDistance.greaterThan( 0 ).select(
  30401. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  30402. distanceFalloff
  30403. );
  30404. } ); // validated
  30405. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  30406. const lightDirection = lightVector.normalize();
  30407. const lightDistance = lightVector.length();
  30408. const attenuation = getDistanceAttenuation( {
  30409. lightDistance,
  30410. cutoffDistance,
  30411. decayExponent
  30412. } );
  30413. const lightColor = color.mul( attenuation );
  30414. return { lightDirection, lightColor };
  30415. };
  30416. /**
  30417. * Module for representing point lights as nodes.
  30418. *
  30419. * @augments AnalyticLightNode
  30420. */
  30421. class PointLightNode extends AnalyticLightNode {
  30422. static get type() {
  30423. return 'PointLightNode';
  30424. }
  30425. /**
  30426. * Constructs a new point light node.
  30427. *
  30428. * @param {?PointLight} [light=null] - The point light source.
  30429. */
  30430. constructor( light = null ) {
  30431. super( light );
  30432. /**
  30433. * Uniform node representing the cutoff distance.
  30434. *
  30435. * @type {UniformNode<float>}
  30436. */
  30437. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  30438. /**
  30439. * Uniform node representing the decay exponent.
  30440. *
  30441. * @type {UniformNode<float>}
  30442. */
  30443. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  30444. }
  30445. /**
  30446. * Overwritten to updated point light specific uniforms.
  30447. *
  30448. * @param {NodeFrame} frame - A reference to the current node frame.
  30449. */
  30450. update( frame ) {
  30451. const { light } = this;
  30452. super.update( frame );
  30453. this.cutoffDistanceNode.value = light.distance;
  30454. this.decayExponentNode.value = light.decay;
  30455. }
  30456. /**
  30457. * Overwritten to setup point light specific shadow.
  30458. *
  30459. * @return {PointShadowNode}
  30460. */
  30461. setupShadowNode() {
  30462. return pointShadow( this.light );
  30463. }
  30464. setupDirect( builder ) {
  30465. return directPointLight( {
  30466. color: this.colorNode,
  30467. lightVector: this.getLightVector( builder ),
  30468. cutoffDistance: this.cutoffDistanceNode,
  30469. decayExponent: this.decayExponentNode
  30470. } );
  30471. }
  30472. }
  30473. /**
  30474. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  30475. *
  30476. * @tsl
  30477. * @function
  30478. * @param {Node<vec2>} coord - The uv coordinates.
  30479. * @return {Node<float>} The result data.
  30480. */
  30481. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  30482. const uv = coord.mul( 2.0 );
  30483. const cx = uv.x.floor();
  30484. const cy = uv.y.floor();
  30485. const result = cx.add( cy ).mod( 2.0 );
  30486. return result.sign();
  30487. } );
  30488. /**
  30489. * Generates a circle based on the uv coordinates.
  30490. *
  30491. * @tsl
  30492. * @function
  30493. * @param {Node<vec2>} coord - The uv to generate the circle.
  30494. * @return {Node<float>} The circle shape.
  30495. */
  30496. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  30497. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  30498. let alpha;
  30499. if ( material.alphaToCoverage && renderer.currentSamples > 0 ) {
  30500. const dlen = float( len2.fwidth() ).toVar();
  30501. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  30502. } else {
  30503. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  30504. }
  30505. return alpha;
  30506. } );
  30507. // Three.js Transpiler
  30508. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  30509. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  30510. const f = float( f_immutable ).toVar();
  30511. const t = float( t_immutable ).toVar();
  30512. const b = bool( b_immutable ).toVar();
  30513. return select( b, t, f );
  30514. } ).setLayout( {
  30515. name: 'mx_select',
  30516. type: 'float',
  30517. inputs: [
  30518. { name: 'b', type: 'bool' },
  30519. { name: 't', type: 'float' },
  30520. { name: 'f', type: 'float' }
  30521. ]
  30522. } );
  30523. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  30524. const b = bool( b_immutable ).toVar();
  30525. const val = float( val_immutable ).toVar();
  30526. return select( b, val.negate(), val );
  30527. } ).setLayout( {
  30528. name: 'mx_negate_if',
  30529. type: 'float',
  30530. inputs: [
  30531. { name: 'val', type: 'float' },
  30532. { name: 'b', type: 'bool' }
  30533. ]
  30534. } );
  30535. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30536. const x = float( x_immutable ).toVar();
  30537. return int( floor( x ) );
  30538. } ).setLayout( {
  30539. name: 'mx_floor',
  30540. type: 'int',
  30541. inputs: [
  30542. { name: 'x', type: 'float' }
  30543. ]
  30544. } );
  30545. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  30546. const x = float( x_immutable ).toVar();
  30547. i.assign( mx_floor( x ) );
  30548. return x.sub( float( i ) );
  30549. } );
  30550. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30551. const t = float( t_immutable ).toVar();
  30552. const s = float( s_immutable ).toVar();
  30553. const v3 = float( v3_immutable ).toVar();
  30554. const v2 = float( v2_immutable ).toVar();
  30555. const v1 = float( v1_immutable ).toVar();
  30556. const v0 = float( v0_immutable ).toVar();
  30557. const s1 = float( sub( 1.0, s ) ).toVar();
  30558. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30559. } ).setLayout( {
  30560. name: 'mx_bilerp_0',
  30561. type: 'float',
  30562. inputs: [
  30563. { name: 'v0', type: 'float' },
  30564. { name: 'v1', type: 'float' },
  30565. { name: 'v2', type: 'float' },
  30566. { name: 'v3', type: 'float' },
  30567. { name: 's', type: 'float' },
  30568. { name: 't', type: 'float' }
  30569. ]
  30570. } );
  30571. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30572. const t = float( t_immutable ).toVar();
  30573. const s = float( s_immutable ).toVar();
  30574. const v3 = vec3( v3_immutable ).toVar();
  30575. const v2 = vec3( v2_immutable ).toVar();
  30576. const v1 = vec3( v1_immutable ).toVar();
  30577. const v0 = vec3( v0_immutable ).toVar();
  30578. const s1 = float( sub( 1.0, s ) ).toVar();
  30579. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30580. } ).setLayout( {
  30581. name: 'mx_bilerp_1',
  30582. type: 'vec3',
  30583. inputs: [
  30584. { name: 'v0', type: 'vec3' },
  30585. { name: 'v1', type: 'vec3' },
  30586. { name: 'v2', type: 'vec3' },
  30587. { name: 'v3', type: 'vec3' },
  30588. { name: 's', type: 'float' },
  30589. { name: 't', type: 'float' }
  30590. ]
  30591. } );
  30592. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  30593. 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 ] ) => {
  30594. const r = float( r_immutable ).toVar();
  30595. const t = float( t_immutable ).toVar();
  30596. const s = float( s_immutable ).toVar();
  30597. const v7 = float( v7_immutable ).toVar();
  30598. const v6 = float( v6_immutable ).toVar();
  30599. const v5 = float( v5_immutable ).toVar();
  30600. const v4 = float( v4_immutable ).toVar();
  30601. const v3 = float( v3_immutable ).toVar();
  30602. const v2 = float( v2_immutable ).toVar();
  30603. const v1 = float( v1_immutable ).toVar();
  30604. const v0 = float( v0_immutable ).toVar();
  30605. const s1 = float( sub( 1.0, s ) ).toVar();
  30606. const t1 = float( sub( 1.0, t ) ).toVar();
  30607. const r1 = float( sub( 1.0, r ) ).toVar();
  30608. 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 ) ) ) ) ) );
  30609. } ).setLayout( {
  30610. name: 'mx_trilerp_0',
  30611. type: 'float',
  30612. inputs: [
  30613. { name: 'v0', type: 'float' },
  30614. { name: 'v1', type: 'float' },
  30615. { name: 'v2', type: 'float' },
  30616. { name: 'v3', type: 'float' },
  30617. { name: 'v4', type: 'float' },
  30618. { name: 'v5', type: 'float' },
  30619. { name: 'v6', type: 'float' },
  30620. { name: 'v7', type: 'float' },
  30621. { name: 's', type: 'float' },
  30622. { name: 't', type: 'float' },
  30623. { name: 'r', type: 'float' }
  30624. ]
  30625. } );
  30626. 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 ] ) => {
  30627. const r = float( r_immutable ).toVar();
  30628. const t = float( t_immutable ).toVar();
  30629. const s = float( s_immutable ).toVar();
  30630. const v7 = vec3( v7_immutable ).toVar();
  30631. const v6 = vec3( v6_immutable ).toVar();
  30632. const v5 = vec3( v5_immutable ).toVar();
  30633. const v4 = vec3( v4_immutable ).toVar();
  30634. const v3 = vec3( v3_immutable ).toVar();
  30635. const v2 = vec3( v2_immutable ).toVar();
  30636. const v1 = vec3( v1_immutable ).toVar();
  30637. const v0 = vec3( v0_immutable ).toVar();
  30638. const s1 = float( sub( 1.0, s ) ).toVar();
  30639. const t1 = float( sub( 1.0, t ) ).toVar();
  30640. const r1 = float( sub( 1.0, r ) ).toVar();
  30641. 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 ) ) ) ) ) );
  30642. } ).setLayout( {
  30643. name: 'mx_trilerp_1',
  30644. type: 'vec3',
  30645. inputs: [
  30646. { name: 'v0', type: 'vec3' },
  30647. { name: 'v1', type: 'vec3' },
  30648. { name: 'v2', type: 'vec3' },
  30649. { name: 'v3', type: 'vec3' },
  30650. { name: 'v4', type: 'vec3' },
  30651. { name: 'v5', type: 'vec3' },
  30652. { name: 'v6', type: 'vec3' },
  30653. { name: 'v7', type: 'vec3' },
  30654. { name: 's', type: 'float' },
  30655. { name: 't', type: 'float' },
  30656. { name: 'r', type: 'float' }
  30657. ]
  30658. } );
  30659. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  30660. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30661. const y = float( y_immutable ).toVar();
  30662. const x = float( x_immutable ).toVar();
  30663. const hash = uint( hash_immutable ).toVar();
  30664. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  30665. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  30666. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  30667. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30668. } ).setLayout( {
  30669. name: 'mx_gradient_float_0',
  30670. type: 'float',
  30671. inputs: [
  30672. { name: 'hash', type: 'uint' },
  30673. { name: 'x', type: 'float' },
  30674. { name: 'y', type: 'float' }
  30675. ]
  30676. } );
  30677. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30678. const z = float( z_immutable ).toVar();
  30679. const y = float( y_immutable ).toVar();
  30680. const x = float( x_immutable ).toVar();
  30681. const hash = uint( hash_immutable ).toVar();
  30682. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  30683. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  30684. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  30685. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30686. } ).setLayout( {
  30687. name: 'mx_gradient_float_1',
  30688. type: 'float',
  30689. inputs: [
  30690. { name: 'hash', type: 'uint' },
  30691. { name: 'x', type: 'float' },
  30692. { name: 'y', type: 'float' },
  30693. { name: 'z', type: 'float' }
  30694. ]
  30695. } );
  30696. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  30697. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30698. const y = float( y_immutable ).toVar();
  30699. const x = float( x_immutable ).toVar();
  30700. const hash = uvec3( hash_immutable ).toVar();
  30701. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  30702. } ).setLayout( {
  30703. name: 'mx_gradient_vec3_0',
  30704. type: 'vec3',
  30705. inputs: [
  30706. { name: 'hash', type: 'uvec3' },
  30707. { name: 'x', type: 'float' },
  30708. { name: 'y', type: 'float' }
  30709. ]
  30710. } );
  30711. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30712. const z = float( z_immutable ).toVar();
  30713. const y = float( y_immutable ).toVar();
  30714. const x = float( x_immutable ).toVar();
  30715. const hash = uvec3( hash_immutable ).toVar();
  30716. 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 ) );
  30717. } ).setLayout( {
  30718. name: 'mx_gradient_vec3_1',
  30719. type: 'vec3',
  30720. inputs: [
  30721. { name: 'hash', type: 'uvec3' },
  30722. { name: 'x', type: 'float' },
  30723. { name: 'y', type: 'float' },
  30724. { name: 'z', type: 'float' }
  30725. ]
  30726. } );
  30727. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  30728. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30729. const v = float( v_immutable ).toVar();
  30730. return mul( 0.6616, v );
  30731. } ).setLayout( {
  30732. name: 'mx_gradient_scale2d_0',
  30733. type: 'float',
  30734. inputs: [
  30735. { name: 'v', type: 'float' }
  30736. ]
  30737. } );
  30738. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30739. const v = float( v_immutable ).toVar();
  30740. return mul( 0.9820, v );
  30741. } ).setLayout( {
  30742. name: 'mx_gradient_scale3d_0',
  30743. type: 'float',
  30744. inputs: [
  30745. { name: 'v', type: 'float' }
  30746. ]
  30747. } );
  30748. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30749. const v = vec3( v_immutable ).toVar();
  30750. return mul( 0.6616, v );
  30751. } ).setLayout( {
  30752. name: 'mx_gradient_scale2d_1',
  30753. type: 'vec3',
  30754. inputs: [
  30755. { name: 'v', type: 'vec3' }
  30756. ]
  30757. } );
  30758. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  30759. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30760. const v = vec3( v_immutable ).toVar();
  30761. return mul( 0.9820, v );
  30762. } ).setLayout( {
  30763. name: 'mx_gradient_scale3d_1',
  30764. type: 'vec3',
  30765. inputs: [
  30766. { name: 'v', type: 'vec3' }
  30767. ]
  30768. } );
  30769. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  30770. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  30771. const k = int( k_immutable ).toVar();
  30772. const x = uint( x_immutable ).toVar();
  30773. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  30774. } ).setLayout( {
  30775. name: 'mx_rotl32',
  30776. type: 'uint',
  30777. inputs: [
  30778. { name: 'x', type: 'uint' },
  30779. { name: 'k', type: 'int' }
  30780. ]
  30781. } );
  30782. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  30783. a.subAssign( c );
  30784. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  30785. c.addAssign( b );
  30786. b.subAssign( a );
  30787. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  30788. a.addAssign( c );
  30789. c.subAssign( b );
  30790. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  30791. b.addAssign( a );
  30792. a.subAssign( c );
  30793. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  30794. c.addAssign( b );
  30795. b.subAssign( a );
  30796. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  30797. a.addAssign( c );
  30798. c.subAssign( b );
  30799. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  30800. b.addAssign( a );
  30801. } );
  30802. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  30803. const c = uint( c_immutable ).toVar();
  30804. const b = uint( b_immutable ).toVar();
  30805. const a = uint( a_immutable ).toVar();
  30806. c.bitXorAssign( b );
  30807. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  30808. a.bitXorAssign( c );
  30809. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  30810. b.bitXorAssign( a );
  30811. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  30812. c.bitXorAssign( b );
  30813. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  30814. a.bitXorAssign( c );
  30815. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  30816. b.bitXorAssign( a );
  30817. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  30818. c.bitXorAssign( b );
  30819. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  30820. return c;
  30821. } ).setLayout( {
  30822. name: 'mx_bjfinal',
  30823. type: 'uint',
  30824. inputs: [
  30825. { name: 'a', type: 'uint' },
  30826. { name: 'b', type: 'uint' },
  30827. { name: 'c', type: 'uint' }
  30828. ]
  30829. } );
  30830. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  30831. const bits = uint( bits_immutable ).toVar();
  30832. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  30833. } ).setLayout( {
  30834. name: 'mx_bits_to_01',
  30835. type: 'float',
  30836. inputs: [
  30837. { name: 'bits', type: 'uint' }
  30838. ]
  30839. } );
  30840. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  30841. const t = float( t_immutable ).toVar();
  30842. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  30843. } ).setLayout( {
  30844. name: 'mx_fade',
  30845. type: 'float',
  30846. inputs: [
  30847. { name: 't', type: 'float' }
  30848. ]
  30849. } );
  30850. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30851. const x = int( x_immutable ).toVar();
  30852. const len = uint( uint( 1 ) ).toVar();
  30853. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  30854. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  30855. } ).setLayout( {
  30856. name: 'mx_hash_int_0',
  30857. type: 'uint',
  30858. inputs: [
  30859. { name: 'x', type: 'int' }
  30860. ]
  30861. } );
  30862. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30863. const y = int( y_immutable ).toVar();
  30864. const x = int( x_immutable ).toVar();
  30865. const len = uint( uint( 2 ) ).toVar();
  30866. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30867. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30868. a.addAssign( uint( x ) );
  30869. b.addAssign( uint( y ) );
  30870. return mx_bjfinal( a, b, c );
  30871. } ).setLayout( {
  30872. name: 'mx_hash_int_1',
  30873. type: 'uint',
  30874. inputs: [
  30875. { name: 'x', type: 'int' },
  30876. { name: 'y', type: 'int' }
  30877. ]
  30878. } );
  30879. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30880. const z = int( z_immutable ).toVar();
  30881. const y = int( y_immutable ).toVar();
  30882. const x = int( x_immutable ).toVar();
  30883. const len = uint( uint( 3 ) ).toVar();
  30884. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30885. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30886. a.addAssign( uint( x ) );
  30887. b.addAssign( uint( y ) );
  30888. c.addAssign( uint( z ) );
  30889. return mx_bjfinal( a, b, c );
  30890. } ).setLayout( {
  30891. name: 'mx_hash_int_2',
  30892. type: 'uint',
  30893. inputs: [
  30894. { name: 'x', type: 'int' },
  30895. { name: 'y', type: 'int' },
  30896. { name: 'z', type: 'int' }
  30897. ]
  30898. } );
  30899. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  30900. const xx = int( xx_immutable ).toVar();
  30901. const z = int( z_immutable ).toVar();
  30902. const y = int( y_immutable ).toVar();
  30903. const x = int( x_immutable ).toVar();
  30904. const len = uint( uint( 4 ) ).toVar();
  30905. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30906. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30907. a.addAssign( uint( x ) );
  30908. b.addAssign( uint( y ) );
  30909. c.addAssign( uint( z ) );
  30910. mx_bjmix( a, b, c );
  30911. a.addAssign( uint( xx ) );
  30912. return mx_bjfinal( a, b, c );
  30913. } ).setLayout( {
  30914. name: 'mx_hash_int_3',
  30915. type: 'uint',
  30916. inputs: [
  30917. { name: 'x', type: 'int' },
  30918. { name: 'y', type: 'int' },
  30919. { name: 'z', type: 'int' },
  30920. { name: 'xx', type: 'int' }
  30921. ]
  30922. } );
  30923. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  30924. const yy = int( yy_immutable ).toVar();
  30925. const xx = int( xx_immutable ).toVar();
  30926. const z = int( z_immutable ).toVar();
  30927. const y = int( y_immutable ).toVar();
  30928. const x = int( x_immutable ).toVar();
  30929. const len = uint( uint( 5 ) ).toVar();
  30930. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30931. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30932. a.addAssign( uint( x ) );
  30933. b.addAssign( uint( y ) );
  30934. c.addAssign( uint( z ) );
  30935. mx_bjmix( a, b, c );
  30936. a.addAssign( uint( xx ) );
  30937. b.addAssign( uint( yy ) );
  30938. return mx_bjfinal( a, b, c );
  30939. } ).setLayout( {
  30940. name: 'mx_hash_int_4',
  30941. type: 'uint',
  30942. inputs: [
  30943. { name: 'x', type: 'int' },
  30944. { name: 'y', type: 'int' },
  30945. { name: 'z', type: 'int' },
  30946. { name: 'xx', type: 'int' },
  30947. { name: 'yy', type: 'int' }
  30948. ]
  30949. } );
  30950. 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 ] );
  30951. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30952. const y = int( y_immutable ).toVar();
  30953. const x = int( x_immutable ).toVar();
  30954. const h = uint( mx_hash_int( x, y ) ).toVar();
  30955. const result = uvec3().toVar();
  30956. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30957. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30958. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30959. return result;
  30960. } ).setLayout( {
  30961. name: 'mx_hash_vec3_0',
  30962. type: 'uvec3',
  30963. inputs: [
  30964. { name: 'x', type: 'int' },
  30965. { name: 'y', type: 'int' }
  30966. ]
  30967. } );
  30968. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30969. const z = int( z_immutable ).toVar();
  30970. const y = int( y_immutable ).toVar();
  30971. const x = int( x_immutable ).toVar();
  30972. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  30973. const result = uvec3().toVar();
  30974. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30975. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30976. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30977. return result;
  30978. } ).setLayout( {
  30979. name: 'mx_hash_vec3_1',
  30980. type: 'uvec3',
  30981. inputs: [
  30982. { name: 'x', type: 'int' },
  30983. { name: 'y', type: 'int' },
  30984. { name: 'z', type: 'int' }
  30985. ]
  30986. } );
  30987. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  30988. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30989. const p = vec2( p_immutable ).toVar();
  30990. const X = int().toVar(), Y = int().toVar();
  30991. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30992. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30993. const u = float( mx_fade( fx ) ).toVar();
  30994. const v = float( mx_fade( fy ) ).toVar();
  30995. 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();
  30996. return mx_gradient_scale2d( result );
  30997. } ).setLayout( {
  30998. name: 'mx_perlin_noise_float_0',
  30999. type: 'float',
  31000. inputs: [
  31001. { name: 'p', type: 'vec2' }
  31002. ]
  31003. } );
  31004. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31005. const p = vec3( p_immutable ).toVar();
  31006. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31007. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31008. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31009. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31010. const u = float( mx_fade( fx ) ).toVar();
  31011. const v = float( mx_fade( fy ) ).toVar();
  31012. const w = float( mx_fade( fz ) ).toVar();
  31013. 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();
  31014. return mx_gradient_scale3d( result );
  31015. } ).setLayout( {
  31016. name: 'mx_perlin_noise_float_1',
  31017. type: 'float',
  31018. inputs: [
  31019. { name: 'p', type: 'vec3' }
  31020. ]
  31021. } );
  31022. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  31023. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31024. const p = vec2( p_immutable ).toVar();
  31025. const X = int().toVar(), Y = int().toVar();
  31026. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31027. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31028. const u = float( mx_fade( fx ) ).toVar();
  31029. const v = float( mx_fade( fy ) ).toVar();
  31030. 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();
  31031. return mx_gradient_scale2d( result );
  31032. } ).setLayout( {
  31033. name: 'mx_perlin_noise_vec3_0',
  31034. type: 'vec3',
  31035. inputs: [
  31036. { name: 'p', type: 'vec2' }
  31037. ]
  31038. } );
  31039. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31040. const p = vec3( p_immutable ).toVar();
  31041. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31042. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  31043. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  31044. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  31045. const u = float( mx_fade( fx ) ).toVar();
  31046. const v = float( mx_fade( fy ) ).toVar();
  31047. const w = float( mx_fade( fz ) ).toVar();
  31048. 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();
  31049. return mx_gradient_scale3d( result );
  31050. } ).setLayout( {
  31051. name: 'mx_perlin_noise_vec3_1',
  31052. type: 'vec3',
  31053. inputs: [
  31054. { name: 'p', type: 'vec3' }
  31055. ]
  31056. } );
  31057. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  31058. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31059. const p = float( p_immutable ).toVar();
  31060. const ix = int( mx_floor( p ) ).toVar();
  31061. return mx_bits_to_01( mx_hash_int( ix ) );
  31062. } ).setLayout( {
  31063. name: 'mx_cell_noise_float_0',
  31064. type: 'float',
  31065. inputs: [
  31066. { name: 'p', type: 'float' }
  31067. ]
  31068. } );
  31069. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31070. const p = vec2( p_immutable ).toVar();
  31071. const ix = int( mx_floor( p.x ) ).toVar();
  31072. const iy = int( mx_floor( p.y ) ).toVar();
  31073. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  31074. } ).setLayout( {
  31075. name: 'mx_cell_noise_float_1',
  31076. type: 'float',
  31077. inputs: [
  31078. { name: 'p', type: 'vec2' }
  31079. ]
  31080. } );
  31081. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31082. const p = vec3( p_immutable ).toVar();
  31083. const ix = int( mx_floor( p.x ) ).toVar();
  31084. const iy = int( mx_floor( p.y ) ).toVar();
  31085. const iz = int( mx_floor( p.z ) ).toVar();
  31086. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  31087. } ).setLayout( {
  31088. name: 'mx_cell_noise_float_2',
  31089. type: 'float',
  31090. inputs: [
  31091. { name: 'p', type: 'vec3' }
  31092. ]
  31093. } );
  31094. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31095. const p = vec4( p_immutable ).toVar();
  31096. const ix = int( mx_floor( p.x ) ).toVar();
  31097. const iy = int( mx_floor( p.y ) ).toVar();
  31098. const iz = int( mx_floor( p.z ) ).toVar();
  31099. const iw = int( mx_floor( p.w ) ).toVar();
  31100. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  31101. } ).setLayout( {
  31102. name: 'mx_cell_noise_float_3',
  31103. type: 'float',
  31104. inputs: [
  31105. { name: 'p', type: 'vec4' }
  31106. ]
  31107. } );
  31108. 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 ] );
  31109. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31110. const p = float( p_immutable ).toVar();
  31111. const ix = int( mx_floor( p ) ).toVar();
  31112. 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 ) ) ) );
  31113. } ).setLayout( {
  31114. name: 'mx_cell_noise_vec3_0',
  31115. type: 'vec3',
  31116. inputs: [
  31117. { name: 'p', type: 'float' }
  31118. ]
  31119. } );
  31120. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31121. const p = vec2( p_immutable ).toVar();
  31122. const ix = int( mx_floor( p.x ) ).toVar();
  31123. const iy = int( mx_floor( p.y ) ).toVar();
  31124. 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 ) ) ) );
  31125. } ).setLayout( {
  31126. name: 'mx_cell_noise_vec3_1',
  31127. type: 'vec3',
  31128. inputs: [
  31129. { name: 'p', type: 'vec2' }
  31130. ]
  31131. } );
  31132. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31133. const p = vec3( p_immutable ).toVar();
  31134. const ix = int( mx_floor( p.x ) ).toVar();
  31135. const iy = int( mx_floor( p.y ) ).toVar();
  31136. const iz = int( mx_floor( p.z ) ).toVar();
  31137. 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 ) ) ) );
  31138. } ).setLayout( {
  31139. name: 'mx_cell_noise_vec3_2',
  31140. type: 'vec3',
  31141. inputs: [
  31142. { name: 'p', type: 'vec3' }
  31143. ]
  31144. } );
  31145. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  31146. const p = vec4( p_immutable ).toVar();
  31147. const ix = int( mx_floor( p.x ) ).toVar();
  31148. const iy = int( mx_floor( p.y ) ).toVar();
  31149. const iz = int( mx_floor( p.z ) ).toVar();
  31150. const iw = int( mx_floor( p.w ) ).toVar();
  31151. 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 ) ) ) );
  31152. } ).setLayout( {
  31153. name: 'mx_cell_noise_vec3_3',
  31154. type: 'vec3',
  31155. inputs: [
  31156. { name: 'p', type: 'vec4' }
  31157. ]
  31158. } );
  31159. 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 ] );
  31160. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31161. const diminish = float( diminish_immutable ).toVar();
  31162. const lacunarity = float( lacunarity_immutable ).toVar();
  31163. const octaves = int( octaves_immutable ).toVar();
  31164. const p = vec3( p_immutable ).toVar();
  31165. const result = float( 0.0 ).toVar();
  31166. const amplitude = float( 1.0 ).toVar();
  31167. Loop( octaves, () => {
  31168. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  31169. amplitude.mulAssign( diminish );
  31170. p.mulAssign( lacunarity );
  31171. } );
  31172. return result;
  31173. } ).setLayout( {
  31174. name: 'mx_fractal_noise_float',
  31175. type: 'float',
  31176. inputs: [
  31177. { name: 'p', type: 'vec3' },
  31178. { name: 'octaves', type: 'int' },
  31179. { name: 'lacunarity', type: 'float' },
  31180. { name: 'diminish', type: 'float' }
  31181. ]
  31182. } );
  31183. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31184. const diminish = float( diminish_immutable ).toVar();
  31185. const lacunarity = float( lacunarity_immutable ).toVar();
  31186. const octaves = int( octaves_immutable ).toVar();
  31187. const p = vec3( p_immutable ).toVar();
  31188. const result = vec3( 0.0 ).toVar();
  31189. const amplitude = float( 1.0 ).toVar();
  31190. Loop( octaves, () => {
  31191. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  31192. amplitude.mulAssign( diminish );
  31193. p.mulAssign( lacunarity );
  31194. } );
  31195. return result;
  31196. } ).setLayout( {
  31197. name: 'mx_fractal_noise_vec3',
  31198. type: 'vec3',
  31199. inputs: [
  31200. { name: 'p', type: 'vec3' },
  31201. { name: 'octaves', type: 'int' },
  31202. { name: 'lacunarity', type: 'float' },
  31203. { name: 'diminish', type: 'float' }
  31204. ]
  31205. } );
  31206. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31207. const diminish = float( diminish_immutable ).toVar();
  31208. const lacunarity = float( lacunarity_immutable ).toVar();
  31209. const octaves = int( octaves_immutable ).toVar();
  31210. const p = vec3( p_immutable ).toVar();
  31211. 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 ) );
  31212. } ).setLayout( {
  31213. name: 'mx_fractal_noise_vec2',
  31214. type: 'vec2',
  31215. inputs: [
  31216. { name: 'p', type: 'vec3' },
  31217. { name: 'octaves', type: 'int' },
  31218. { name: 'lacunarity', type: 'float' },
  31219. { name: 'diminish', type: 'float' }
  31220. ]
  31221. } );
  31222. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  31223. const diminish = float( diminish_immutable ).toVar();
  31224. const lacunarity = float( lacunarity_immutable ).toVar();
  31225. const octaves = int( octaves_immutable ).toVar();
  31226. const p = vec3( p_immutable ).toVar();
  31227. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  31228. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  31229. return vec4( c, f );
  31230. } ).setLayout( {
  31231. name: 'mx_fractal_noise_vec4',
  31232. type: 'vec4',
  31233. inputs: [
  31234. { name: 'p', type: 'vec3' },
  31235. { name: 'octaves', type: 'int' },
  31236. { name: 'lacunarity', type: 'float' },
  31237. { name: 'diminish', type: 'float' }
  31238. ]
  31239. } );
  31240. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  31241. const metric = int( metric_immutable ).toVar();
  31242. const jitter = float( jitter_immutable ).toVar();
  31243. const yoff = int( yoff_immutable ).toVar();
  31244. const xoff = int( xoff_immutable ).toVar();
  31245. const y = int( y_immutable ).toVar();
  31246. const x = int( x_immutable ).toVar();
  31247. const p = vec2( p_immutable ).toVar();
  31248. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  31249. const off = vec2( tmp.x, tmp.y ).toVar();
  31250. off.subAssign( 0.5 );
  31251. off.mulAssign( jitter );
  31252. off.addAssign( 0.5 );
  31253. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  31254. const diff = vec2( cellpos.sub( p ) ).toVar();
  31255. If( metric.equal( int( 2 ) ), () => {
  31256. return abs( diff.x ).add( abs( diff.y ) );
  31257. } );
  31258. If( metric.equal( int( 3 ) ), () => {
  31259. return max$1( abs( diff.x ), abs( diff.y ) );
  31260. } );
  31261. return dot( diff, diff );
  31262. } ).setLayout( {
  31263. name: 'mx_worley_distance_0',
  31264. type: 'float',
  31265. inputs: [
  31266. { name: 'p', type: 'vec2' },
  31267. { name: 'x', type: 'int' },
  31268. { name: 'y', type: 'int' },
  31269. { name: 'xoff', type: 'int' },
  31270. { name: 'yoff', type: 'int' },
  31271. { name: 'jitter', type: 'float' },
  31272. { name: 'metric', type: 'int' }
  31273. ]
  31274. } );
  31275. 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 ] ) => {
  31276. const metric = int( metric_immutable ).toVar();
  31277. const jitter = float( jitter_immutable ).toVar();
  31278. const zoff = int( zoff_immutable ).toVar();
  31279. const yoff = int( yoff_immutable ).toVar();
  31280. const xoff = int( xoff_immutable ).toVar();
  31281. const z = int( z_immutable ).toVar();
  31282. const y = int( y_immutable ).toVar();
  31283. const x = int( x_immutable ).toVar();
  31284. const p = vec3( p_immutable ).toVar();
  31285. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  31286. off.subAssign( 0.5 );
  31287. off.mulAssign( jitter );
  31288. off.addAssign( 0.5 );
  31289. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  31290. const diff = vec3( cellpos.sub( p ) ).toVar();
  31291. If( metric.equal( int( 2 ) ), () => {
  31292. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  31293. } );
  31294. If( metric.equal( int( 3 ) ), () => {
  31295. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  31296. } );
  31297. return dot( diff, diff );
  31298. } ).setLayout( {
  31299. name: 'mx_worley_distance_1',
  31300. type: 'float',
  31301. inputs: [
  31302. { name: 'p', type: 'vec3' },
  31303. { name: 'x', type: 'int' },
  31304. { name: 'y', type: 'int' },
  31305. { name: 'z', type: 'int' },
  31306. { name: 'xoff', type: 'int' },
  31307. { name: 'yoff', type: 'int' },
  31308. { name: 'zoff', type: 'int' },
  31309. { name: 'jitter', type: 'float' },
  31310. { name: 'metric', type: 'int' }
  31311. ]
  31312. } );
  31313. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  31314. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31315. const metric = int( metric_immutable ).toVar();
  31316. const jitter = float( jitter_immutable ).toVar();
  31317. const p = vec2( p_immutable ).toVar();
  31318. const X = int().toVar(), Y = int().toVar();
  31319. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31320. const sqdist = float( 1e6 ).toVar();
  31321. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31322. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31323. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31324. sqdist.assign( min$1( sqdist, dist ) );
  31325. } );
  31326. } );
  31327. If( metric.equal( int( 0 ) ), () => {
  31328. sqdist.assign( sqrt( sqdist ) );
  31329. } );
  31330. return sqdist;
  31331. } ).setLayout( {
  31332. name: 'mx_worley_noise_float_0',
  31333. type: 'float',
  31334. inputs: [
  31335. { name: 'p', type: 'vec2' },
  31336. { name: 'jitter', type: 'float' },
  31337. { name: 'metric', type: 'int' }
  31338. ]
  31339. } );
  31340. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31341. const metric = int( metric_immutable ).toVar();
  31342. const jitter = float( jitter_immutable ).toVar();
  31343. const p = vec2( p_immutable ).toVar();
  31344. const X = int().toVar(), Y = int().toVar();
  31345. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31346. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31347. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31348. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31349. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31350. If( dist.lessThan( sqdist.x ), () => {
  31351. sqdist.y.assign( sqdist.x );
  31352. sqdist.x.assign( dist );
  31353. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31354. sqdist.y.assign( dist );
  31355. } );
  31356. } );
  31357. } );
  31358. If( metric.equal( int( 0 ) ), () => {
  31359. sqdist.assign( sqrt( sqdist ) );
  31360. } );
  31361. return sqdist;
  31362. } ).setLayout( {
  31363. name: 'mx_worley_noise_vec2_0',
  31364. type: 'vec2',
  31365. inputs: [
  31366. { name: 'p', type: 'vec2' },
  31367. { name: 'jitter', type: 'float' },
  31368. { name: 'metric', type: 'int' }
  31369. ]
  31370. } );
  31371. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31372. const metric = int( metric_immutable ).toVar();
  31373. const jitter = float( jitter_immutable ).toVar();
  31374. const p = vec2( p_immutable ).toVar();
  31375. const X = int().toVar(), Y = int().toVar();
  31376. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31377. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31378. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31379. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31380. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31381. If( dist.lessThan( sqdist.x ), () => {
  31382. sqdist.z.assign( sqdist.y );
  31383. sqdist.y.assign( sqdist.x );
  31384. sqdist.x.assign( dist );
  31385. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31386. sqdist.z.assign( sqdist.y );
  31387. sqdist.y.assign( dist );
  31388. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31389. sqdist.z.assign( dist );
  31390. } );
  31391. } );
  31392. } );
  31393. If( metric.equal( int( 0 ) ), () => {
  31394. sqdist.assign( sqrt( sqdist ) );
  31395. } );
  31396. return sqdist;
  31397. } ).setLayout( {
  31398. name: 'mx_worley_noise_vec3_0',
  31399. type: 'vec3',
  31400. inputs: [
  31401. { name: 'p', type: 'vec2' },
  31402. { name: 'jitter', type: 'float' },
  31403. { name: 'metric', type: 'int' }
  31404. ]
  31405. } );
  31406. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31407. const metric = int( metric_immutable ).toVar();
  31408. const jitter = float( jitter_immutable ).toVar();
  31409. const p = vec3( p_immutable ).toVar();
  31410. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31411. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31412. const sqdist = float( 1e6 ).toVar();
  31413. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31414. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31415. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31416. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31417. sqdist.assign( min$1( sqdist, dist ) );
  31418. } );
  31419. } );
  31420. } );
  31421. If( metric.equal( int( 0 ) ), () => {
  31422. sqdist.assign( sqrt( sqdist ) );
  31423. } );
  31424. return sqdist;
  31425. } ).setLayout( {
  31426. name: 'mx_worley_noise_float_1',
  31427. type: 'float',
  31428. inputs: [
  31429. { name: 'p', type: 'vec3' },
  31430. { name: 'jitter', type: 'float' },
  31431. { name: 'metric', type: 'int' }
  31432. ]
  31433. } );
  31434. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  31435. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31436. const metric = int( metric_immutable ).toVar();
  31437. const jitter = float( jitter_immutable ).toVar();
  31438. const p = vec3( p_immutable ).toVar();
  31439. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31440. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31441. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31442. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31443. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31444. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31445. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31446. If( dist.lessThan( sqdist.x ), () => {
  31447. sqdist.y.assign( sqdist.x );
  31448. sqdist.x.assign( dist );
  31449. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31450. sqdist.y.assign( dist );
  31451. } );
  31452. } );
  31453. } );
  31454. } );
  31455. If( metric.equal( int( 0 ) ), () => {
  31456. sqdist.assign( sqrt( sqdist ) );
  31457. } );
  31458. return sqdist;
  31459. } ).setLayout( {
  31460. name: 'mx_worley_noise_vec2_1',
  31461. type: 'vec2',
  31462. inputs: [
  31463. { name: 'p', type: 'vec3' },
  31464. { name: 'jitter', type: 'float' },
  31465. { name: 'metric', type: 'int' }
  31466. ]
  31467. } );
  31468. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  31469. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31470. const metric = int( metric_immutable ).toVar();
  31471. const jitter = float( jitter_immutable ).toVar();
  31472. const p = vec3( p_immutable ).toVar();
  31473. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31474. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31475. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31476. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31477. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31478. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31479. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31480. If( dist.lessThan( sqdist.x ), () => {
  31481. sqdist.z.assign( sqdist.y );
  31482. sqdist.y.assign( sqdist.x );
  31483. sqdist.x.assign( dist );
  31484. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31485. sqdist.z.assign( sqdist.y );
  31486. sqdist.y.assign( dist );
  31487. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31488. sqdist.z.assign( dist );
  31489. } );
  31490. } );
  31491. } );
  31492. } );
  31493. If( metric.equal( int( 0 ) ), () => {
  31494. sqdist.assign( sqrt( sqdist ) );
  31495. } );
  31496. return sqdist;
  31497. } ).setLayout( {
  31498. name: 'mx_worley_noise_vec3_1',
  31499. type: 'vec3',
  31500. inputs: [
  31501. { name: 'p', type: 'vec3' },
  31502. { name: 'jitter', type: 'float' },
  31503. { name: 'metric', type: 'int' }
  31504. ]
  31505. } );
  31506. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  31507. // Unified Noise 2D
  31508. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  31509. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  31510. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31511. octaves_immutable, lacunarity_immutable, diminish_immutable
  31512. ] ) => {
  31513. const noiseType = int( noiseType_immutable ).toVar();
  31514. const texcoord = vec2( texcoord_immutable ).toVar();
  31515. const freq = vec2( freq_immutable ).toVar();
  31516. const offset = vec2( offset_immutable ).toVar();
  31517. const jitter = float( jitter_immutable ).toVar();
  31518. const outmin = float( outmin_immutable ).toVar();
  31519. const outmax = float( outmax_immutable ).toVar();
  31520. const clampoutput = bool( clampoutput_immutable ).toVar();
  31521. const octaves = int( octaves_immutable ).toVar();
  31522. const lacunarity = float( lacunarity_immutable ).toVar();
  31523. const diminish = float( diminish_immutable ).toVar();
  31524. // Compute input position
  31525. const p = texcoord.mul( freq ).add( offset );
  31526. const result = float( 0.0 ).toVar();
  31527. // Perlin
  31528. If( noiseType.equal( int( 0 ) ), () => {
  31529. result.assign( mx_perlin_noise_vec3( p ) );
  31530. } );
  31531. // Cell
  31532. If( noiseType.equal( int( 1 ) ), () => {
  31533. result.assign( mx_cell_noise_vec3( p ) );
  31534. } );
  31535. // Worley (metric=0 = euclidean)
  31536. If( noiseType.equal( int( 2 ) ), () => {
  31537. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31538. } );
  31539. // Fractal (use vec3(p, 0.0) for 2D input)
  31540. If( noiseType.equal( int( 3 ) ), () => {
  31541. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  31542. } );
  31543. // Remap output to [outmin, outmax]
  31544. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31545. // Clamp if requested
  31546. If( clampoutput, () => {
  31547. result.assign( clamp( result, outmin, outmax ) );
  31548. } );
  31549. return result;
  31550. } ).setLayout( {
  31551. name: 'mx_unifiednoise2d',
  31552. type: 'float',
  31553. inputs: [
  31554. { name: 'noiseType', type: 'int' },
  31555. { name: 'texcoord', type: 'vec2' },
  31556. { name: 'freq', type: 'vec2' },
  31557. { name: 'offset', type: 'vec2' },
  31558. { name: 'jitter', type: 'float' },
  31559. { name: 'outmin', type: 'float' },
  31560. { name: 'outmax', type: 'float' },
  31561. { name: 'clampoutput', type: 'bool' },
  31562. { name: 'octaves', type: 'int' },
  31563. { name: 'lacunarity', type: 'float' },
  31564. { name: 'diminish', type: 'float' }
  31565. ]
  31566. } );
  31567. // Unified Noise 3D
  31568. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  31569. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  31570. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31571. octaves_immutable, lacunarity_immutable, diminish_immutable
  31572. ] ) => {
  31573. const noiseType = int( noiseType_immutable ).toVar();
  31574. const position = vec3( position_immutable ).toVar();
  31575. const freq = vec3( freq_immutable ).toVar();
  31576. const offset = vec3( offset_immutable ).toVar();
  31577. const jitter = float( jitter_immutable ).toVar();
  31578. const outmin = float( outmin_immutable ).toVar();
  31579. const outmax = float( outmax_immutable ).toVar();
  31580. const clampoutput = bool( clampoutput_immutable ).toVar();
  31581. const octaves = int( octaves_immutable ).toVar();
  31582. const lacunarity = float( lacunarity_immutable ).toVar();
  31583. const diminish = float( diminish_immutable ).toVar();
  31584. // Compute input position
  31585. const p = position.mul( freq ).add( offset );
  31586. const result = float( 0.0 ).toVar();
  31587. // Perlin
  31588. If( noiseType.equal( int( 0 ) ), () => {
  31589. result.assign( mx_perlin_noise_vec3( p ) );
  31590. } );
  31591. // Cell
  31592. If( noiseType.equal( int( 1 ) ), () => {
  31593. result.assign( mx_cell_noise_vec3( p ) );
  31594. } );
  31595. // Worley (metric=0 = euclidean)
  31596. If( noiseType.equal( int( 2 ) ), () => {
  31597. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31598. } );
  31599. // Fractal
  31600. If( noiseType.equal( int( 3 ) ), () => {
  31601. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  31602. } );
  31603. // Remap output to [outmin, outmax]
  31604. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31605. // Clamp if requested
  31606. If( clampoutput, () => {
  31607. result.assign( clamp( result, outmin, outmax ) );
  31608. } );
  31609. return result;
  31610. } ).setLayout( {
  31611. name: 'mx_unifiednoise3d',
  31612. type: 'float',
  31613. inputs: [
  31614. { name: 'noiseType', type: 'int' },
  31615. { name: 'position', type: 'vec3' },
  31616. { name: 'freq', type: 'vec3' },
  31617. { name: 'offset', type: 'vec3' },
  31618. { name: 'jitter', type: 'float' },
  31619. { name: 'outmin', type: 'float' },
  31620. { name: 'outmax', type: 'float' },
  31621. { name: 'clampoutput', type: 'bool' },
  31622. { name: 'octaves', type: 'int' },
  31623. { name: 'lacunarity', type: 'float' },
  31624. { name: 'diminish', type: 'float' }
  31625. ]
  31626. } );
  31627. // Three.js Transpiler
  31628. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  31629. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  31630. const s = hsv.y;
  31631. const v = hsv.z;
  31632. const result = vec3().toVar();
  31633. If( s.lessThan( 0.0001 ), () => {
  31634. result.assign( vec3( v, v, v ) );
  31635. } ).Else( () => {
  31636. let h = hsv.x;
  31637. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  31638. const hi = int( trunc( h ) );
  31639. const f = h.sub( float( hi ) );
  31640. const p = v.mul( s.oneMinus() );
  31641. const q = v.mul( s.mul( f ).oneMinus() );
  31642. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  31643. If( hi.equal( int( 0 ) ), () => {
  31644. result.assign( vec3( v, t, p ) );
  31645. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  31646. result.assign( vec3( q, v, p ) );
  31647. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  31648. result.assign( vec3( p, v, t ) );
  31649. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  31650. result.assign( vec3( p, q, v ) );
  31651. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  31652. result.assign( vec3( t, p, v ) );
  31653. } ).Else( () => {
  31654. result.assign( vec3( v, p, q ) );
  31655. } );
  31656. } );
  31657. return result;
  31658. } ).setLayout( {
  31659. name: 'mx_hsvtorgb',
  31660. type: 'vec3',
  31661. inputs: [
  31662. { name: 'hsv', type: 'vec3' }
  31663. ]
  31664. } );
  31665. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  31666. const c = vec3( c_immutable ).toVar();
  31667. const r = float( c.x ).toVar();
  31668. const g = float( c.y ).toVar();
  31669. const b = float( c.z ).toVar();
  31670. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  31671. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  31672. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  31673. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  31674. v.assign( maxcomp );
  31675. If( maxcomp.greaterThan( 0.0 ), () => {
  31676. s.assign( delta.div( maxcomp ) );
  31677. } ).Else( () => {
  31678. s.assign( 0.0 );
  31679. } );
  31680. If( s.lessThanEqual( 0.0 ), () => {
  31681. h.assign( 0.0 );
  31682. } ).Else( () => {
  31683. If( r.greaterThanEqual( maxcomp ), () => {
  31684. h.assign( g.sub( b ).div( delta ) );
  31685. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  31686. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  31687. } ).Else( () => {
  31688. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  31689. } );
  31690. h.mulAssign( 1.0 / 6.0 );
  31691. If( h.lessThan( 0.0 ), () => {
  31692. h.addAssign( 1.0 );
  31693. } );
  31694. } );
  31695. return vec3( h, s, v );
  31696. } ).setLayout( {
  31697. name: 'mx_rgbtohsv',
  31698. type: 'vec3',
  31699. inputs: [
  31700. { name: 'c', type: 'vec3' }
  31701. ]
  31702. } );
  31703. // Three.js Transpiler
  31704. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  31705. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  31706. const color = vec3( color_immutable ).toVar();
  31707. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  31708. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  31709. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  31710. return mix( linSeg, powSeg, isAbove );
  31711. } ).setLayout( {
  31712. name: 'mx_srgb_texture_to_lin_rec709',
  31713. type: 'vec3',
  31714. inputs: [
  31715. { name: 'color', type: 'vec3' }
  31716. ]
  31717. } );
  31718. const mx_aastep = ( threshold, value ) => {
  31719. threshold = float( threshold );
  31720. value = float( value );
  31721. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  31722. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  31723. };
  31724. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  31725. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  31726. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  31727. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  31728. const mx_ramp4 = (
  31729. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  31730. ) => {
  31731. const u = texcoord.x.clamp();
  31732. const v = texcoord.y.clamp();
  31733. const top = mix( valuetl, valuetr, u );
  31734. const bottom = mix( valuebl, valuebr, u );
  31735. return mix( top, bottom, v );
  31736. };
  31737. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  31738. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  31739. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  31740. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  31741. const mx_safepower = ( in1, in2 = 1 ) => {
  31742. in1 = float( in1 );
  31743. return in1.abs().pow( in2 ).mul( in1.sign() );
  31744. };
  31745. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  31746. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31747. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31748. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31749. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  31750. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  31751. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  31752. return noise_vec4.mul( amplitude ).add( pivot );
  31753. };
  31754. 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 );
  31755. 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 );
  31756. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31757. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31758. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31759. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  31760. 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 );
  31761. 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 );
  31762. 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 );
  31763. 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 );
  31764. // === Moved from MaterialXLoader.js ===
  31765. // Math ops
  31766. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  31767. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  31768. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  31769. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  31770. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  31771. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  31772. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  31773. const mx_timer = () => time;
  31774. const mx_frame = () => frameId;
  31775. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  31776. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  31777. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  31778. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  31779. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  31780. const mx_separate = ( in1, channelOrOut = null ) => {
  31781. if ( typeof channelOrOut === 'string' ) {
  31782. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31783. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  31784. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  31785. }
  31786. if ( typeof channelOrOut === 'number' ) {
  31787. return in1.element( channelOrOut );
  31788. }
  31789. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  31790. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31791. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  31792. }
  31793. return in1;
  31794. };
  31795. const mx_place2d = (
  31796. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  31797. ) => {
  31798. let uv = texcoord;
  31799. if ( pivot ) uv = uv.sub( pivot );
  31800. if ( scale ) uv = uv.mul( scale );
  31801. if ( rotate ) {
  31802. const rad = rotate.mul( Math.PI / 180.0 );
  31803. const cosR = rad.cos();
  31804. const sinR = rad.sin();
  31805. uv = vec2(
  31806. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  31807. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  31808. );
  31809. }
  31810. if ( pivot ) uv = uv.add( pivot );
  31811. if ( offset ) uv = uv.add( offset );
  31812. return uv;
  31813. };
  31814. const mx_rotate2d = ( input, amount ) => {
  31815. input = vec2( input );
  31816. amount = float( amount );
  31817. const radians = amount.mul( Math.PI / 180.0 );
  31818. return rotate( input, radians );
  31819. };
  31820. const mx_rotate3d = ( input, amount, axis ) => {
  31821. input = vec3( input );
  31822. amount = float( amount );
  31823. axis = vec3( axis );
  31824. const radians = amount.mul( Math.PI / 180.0 );
  31825. const nAxis = axis.normalize();
  31826. const cosA = radians.cos();
  31827. const sinA = radians.sin();
  31828. const oneMinusCosA = float( 1 ).sub( cosA );
  31829. const rot =
  31830. input.mul( cosA )
  31831. .add( nAxis.cross( input ).mul( sinA ) )
  31832. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  31833. return rot;
  31834. };
  31835. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  31836. input = vec3( input );
  31837. scale = float( scale );
  31838. return bumpMap( input, scale );
  31839. };
  31840. /**
  31841. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  31842. *
  31843. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  31844. *
  31845. * ```js
  31846. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  31847. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  31848. * ```
  31849. *
  31850. * @tsl
  31851. * @function
  31852. * @param {Node<vec3>} normal - The normal to correct.
  31853. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  31854. * @param {Node<vec3>} cubePos - The cube position.
  31855. * @return {Node<vec3>} The parallax corrected normal.
  31856. */
  31857. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  31858. const nDir = normalize( normal ).toVar();
  31859. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31860. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31861. const rbminmax = vec3().toVar();
  31862. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  31863. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  31864. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  31865. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  31866. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  31867. return boxIntersection.sub( cubePos );
  31868. } );
  31869. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  31870. // normal is assumed to have unit length
  31871. const x = normal.x, y = normal.y, z = normal.z;
  31872. // band 0
  31873. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  31874. // band 1
  31875. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  31876. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  31877. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  31878. // band 2
  31879. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  31880. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  31881. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  31882. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  31883. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  31884. return result;
  31885. } );
  31886. // constants
  31887. var TSL = /*#__PURE__*/Object.freeze({
  31888. __proto__: null,
  31889. BRDF_GGX: BRDF_GGX,
  31890. BRDF_Lambert: BRDF_Lambert,
  31891. BasicPointShadowFilter: BasicPointShadowFilter,
  31892. BasicShadowFilter: BasicShadowFilter,
  31893. Break: Break,
  31894. Const: Const,
  31895. Continue: Continue,
  31896. DFGApprox: DFGApprox,
  31897. D_GGX: D_GGX,
  31898. Discard: Discard,
  31899. EPSILON: EPSILON,
  31900. F_Schlick: F_Schlick,
  31901. Fn: Fn,
  31902. HALF_PI: HALF_PI,
  31903. INFINITY: INFINITY,
  31904. If: If,
  31905. Loop: Loop,
  31906. NodeAccess: NodeAccess,
  31907. NodeShaderStage: NodeShaderStage,
  31908. NodeType: NodeType,
  31909. NodeUpdateType: NodeUpdateType,
  31910. OnMaterialUpdate: OnMaterialUpdate,
  31911. OnObjectUpdate: OnObjectUpdate,
  31912. PCFShadowFilter: PCFShadowFilter,
  31913. PCFSoftShadowFilter: PCFSoftShadowFilter,
  31914. PI: PI,
  31915. PI2: PI2,
  31916. PointShadowFilter: PointShadowFilter,
  31917. Return: Return,
  31918. Schlick_to_F0: Schlick_to_F0,
  31919. ScriptableNodeResources: ScriptableNodeResources,
  31920. ShaderNode: ShaderNode,
  31921. Stack: Stack,
  31922. Switch: Switch,
  31923. TBNViewMatrix: TBNViewMatrix,
  31924. TWO_PI: TWO_PI,
  31925. VSMShadowFilter: VSMShadowFilter,
  31926. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  31927. Var: Var,
  31928. VarIntent: VarIntent,
  31929. abs: abs,
  31930. acesFilmicToneMapping: acesFilmicToneMapping,
  31931. acos: acos,
  31932. add: add,
  31933. addMethodChaining: addMethodChaining,
  31934. addNodeElement: addNodeElement,
  31935. agxToneMapping: agxToneMapping,
  31936. all: all,
  31937. alphaT: alphaT,
  31938. and: and,
  31939. anisotropy: anisotropy,
  31940. anisotropyB: anisotropyB,
  31941. anisotropyT: anisotropyT,
  31942. any: any,
  31943. append: append,
  31944. array: array,
  31945. arrayBuffer: arrayBuffer,
  31946. asin: asin,
  31947. assign: assign,
  31948. atan: atan,
  31949. atan2: atan2,
  31950. atomicAdd: atomicAdd,
  31951. atomicAnd: atomicAnd,
  31952. atomicFunc: atomicFunc,
  31953. atomicLoad: atomicLoad,
  31954. atomicMax: atomicMax,
  31955. atomicMin: atomicMin,
  31956. atomicOr: atomicOr,
  31957. atomicStore: atomicStore,
  31958. atomicSub: atomicSub,
  31959. atomicXor: atomicXor,
  31960. attenuationColor: attenuationColor,
  31961. attenuationDistance: attenuationDistance,
  31962. attribute: attribute,
  31963. attributeArray: attributeArray,
  31964. backgroundBlurriness: backgroundBlurriness,
  31965. backgroundIntensity: backgroundIntensity,
  31966. backgroundRotation: backgroundRotation,
  31967. batch: batch,
  31968. bentNormalView: bentNormalView,
  31969. billboarding: billboarding,
  31970. bitAnd: bitAnd,
  31971. bitNot: bitNot,
  31972. bitOr: bitOr,
  31973. bitXor: bitXor,
  31974. bitangentGeometry: bitangentGeometry,
  31975. bitangentLocal: bitangentLocal,
  31976. bitangentView: bitangentView,
  31977. bitangentWorld: bitangentWorld,
  31978. bitcast: bitcast,
  31979. blendBurn: blendBurn,
  31980. blendColor: blendColor,
  31981. blendDodge: blendDodge,
  31982. blendOverlay: blendOverlay,
  31983. blendScreen: blendScreen,
  31984. blur: blur,
  31985. bool: bool,
  31986. buffer: buffer,
  31987. bufferAttribute: bufferAttribute,
  31988. builtin: builtin,
  31989. bumpMap: bumpMap,
  31990. burn: burn,
  31991. bvec2: bvec2,
  31992. bvec3: bvec3,
  31993. bvec4: bvec4,
  31994. bypass: bypass,
  31995. cache: cache,
  31996. call: call,
  31997. cameraFar: cameraFar,
  31998. cameraIndex: cameraIndex,
  31999. cameraNear: cameraNear,
  32000. cameraNormalMatrix: cameraNormalMatrix,
  32001. cameraPosition: cameraPosition,
  32002. cameraProjectionMatrix: cameraProjectionMatrix,
  32003. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  32004. cameraViewMatrix: cameraViewMatrix,
  32005. cameraViewport: cameraViewport,
  32006. cameraWorldMatrix: cameraWorldMatrix,
  32007. cbrt: cbrt,
  32008. cdl: cdl,
  32009. ceil: ceil,
  32010. checker: checker,
  32011. cineonToneMapping: cineonToneMapping,
  32012. clamp: clamp,
  32013. clearcoat: clearcoat,
  32014. clearcoatNormalView: clearcoatNormalView,
  32015. clearcoatRoughness: clearcoatRoughness,
  32016. code: code,
  32017. color: color,
  32018. colorSpaceToWorking: colorSpaceToWorking,
  32019. colorToDirection: colorToDirection,
  32020. compute: compute,
  32021. computeKernel: computeKernel,
  32022. computeSkinning: computeSkinning,
  32023. context: context,
  32024. convert: convert,
  32025. convertColorSpace: convertColorSpace,
  32026. convertToTexture: convertToTexture,
  32027. cos: cos,
  32028. cross: cross,
  32029. cubeTexture: cubeTexture,
  32030. cubeTextureBase: cubeTextureBase,
  32031. cubeToUV: cubeToUV,
  32032. dFdx: dFdx,
  32033. dFdy: dFdy,
  32034. dashSize: dashSize,
  32035. debug: debug,
  32036. decrement: decrement,
  32037. decrementBefore: decrementBefore,
  32038. defaultBuildStages: defaultBuildStages,
  32039. defaultShaderStages: defaultShaderStages,
  32040. defined: defined,
  32041. degrees: degrees,
  32042. deltaTime: deltaTime,
  32043. densityFog: densityFog,
  32044. densityFogFactor: densityFogFactor,
  32045. depth: depth,
  32046. depthPass: depthPass,
  32047. determinant: determinant,
  32048. difference: difference,
  32049. diffuseColor: diffuseColor,
  32050. directPointLight: directPointLight,
  32051. directionToColor: directionToColor,
  32052. directionToFaceDirection: directionToFaceDirection,
  32053. dispersion: dispersion,
  32054. distance: distance,
  32055. div: div,
  32056. dodge: dodge,
  32057. dot: dot,
  32058. drawIndex: drawIndex,
  32059. dynamicBufferAttribute: dynamicBufferAttribute,
  32060. element: element,
  32061. emissive: emissive,
  32062. equal: equal,
  32063. equals: equals,
  32064. equirectUV: equirectUV,
  32065. exp: exp,
  32066. exp2: exp2,
  32067. expression: expression,
  32068. faceDirection: faceDirection,
  32069. faceForward: faceForward,
  32070. faceforward: faceforward,
  32071. float: float,
  32072. floatBitsToInt: floatBitsToInt,
  32073. floatBitsToUint: floatBitsToUint,
  32074. floor: floor,
  32075. fog: fog,
  32076. fract: fract,
  32077. frameGroup: frameGroup,
  32078. frameId: frameId,
  32079. frontFacing: frontFacing,
  32080. fwidth: fwidth,
  32081. gain: gain,
  32082. gapSize: gapSize,
  32083. getConstNodeType: getConstNodeType,
  32084. getCurrentStack: getCurrentStack,
  32085. getDirection: getDirection,
  32086. getDistanceAttenuation: getDistanceAttenuation,
  32087. getGeometryRoughness: getGeometryRoughness,
  32088. getNormalFromDepth: getNormalFromDepth,
  32089. getParallaxCorrectNormal: getParallaxCorrectNormal,
  32090. getRoughness: getRoughness,
  32091. getScreenPosition: getScreenPosition,
  32092. getShIrradianceAt: getShIrradianceAt,
  32093. getShadowMaterial: getShadowMaterial,
  32094. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  32095. getTextureIndex: getTextureIndex,
  32096. getViewPosition: getViewPosition,
  32097. globalId: globalId,
  32098. glsl: glsl,
  32099. glslFn: glslFn,
  32100. grayscale: grayscale,
  32101. greaterThan: greaterThan,
  32102. greaterThanEqual: greaterThanEqual,
  32103. hash: hash,
  32104. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  32105. highpModelViewMatrix: highpModelViewMatrix,
  32106. hue: hue,
  32107. increment: increment,
  32108. incrementBefore: incrementBefore,
  32109. inspector: inspector,
  32110. instance: instance,
  32111. instanceIndex: instanceIndex,
  32112. instancedArray: instancedArray,
  32113. instancedBufferAttribute: instancedBufferAttribute,
  32114. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  32115. instancedMesh: instancedMesh,
  32116. int: int,
  32117. intBitsToFloat: intBitsToFloat,
  32118. inverse: inverse,
  32119. inverseSqrt: inverseSqrt,
  32120. inversesqrt: inversesqrt,
  32121. invocationLocalIndex: invocationLocalIndex,
  32122. invocationSubgroupIndex: invocationSubgroupIndex,
  32123. ior: ior,
  32124. iridescence: iridescence,
  32125. iridescenceIOR: iridescenceIOR,
  32126. iridescenceThickness: iridescenceThickness,
  32127. isolate: isolate,
  32128. ivec2: ivec2,
  32129. ivec3: ivec3,
  32130. ivec4: ivec4,
  32131. js: js,
  32132. label: label,
  32133. length: length,
  32134. lengthSq: lengthSq,
  32135. lessThan: lessThan,
  32136. lessThanEqual: lessThanEqual,
  32137. lightPosition: lightPosition,
  32138. lightProjectionUV: lightProjectionUV,
  32139. lightShadowMatrix: lightShadowMatrix,
  32140. lightTargetDirection: lightTargetDirection,
  32141. lightTargetPosition: lightTargetPosition,
  32142. lightViewPosition: lightViewPosition,
  32143. lightingContext: lightingContext,
  32144. lights: lights,
  32145. linearDepth: linearDepth,
  32146. linearToneMapping: linearToneMapping,
  32147. localId: localId,
  32148. log: log,
  32149. log2: log2,
  32150. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  32151. luminance: luminance,
  32152. mat2: mat2,
  32153. mat3: mat3,
  32154. mat4: mat4,
  32155. matcapUV: matcapUV,
  32156. materialAO: materialAO,
  32157. materialAlphaTest: materialAlphaTest,
  32158. materialAnisotropy: materialAnisotropy,
  32159. materialAnisotropyVector: materialAnisotropyVector,
  32160. materialAttenuationColor: materialAttenuationColor,
  32161. materialAttenuationDistance: materialAttenuationDistance,
  32162. materialClearcoat: materialClearcoat,
  32163. materialClearcoatNormal: materialClearcoatNormal,
  32164. materialClearcoatRoughness: materialClearcoatRoughness,
  32165. materialColor: materialColor,
  32166. materialDispersion: materialDispersion,
  32167. materialEmissive: materialEmissive,
  32168. materialEnvIntensity: materialEnvIntensity,
  32169. materialEnvRotation: materialEnvRotation,
  32170. materialIOR: materialIOR,
  32171. materialIridescence: materialIridescence,
  32172. materialIridescenceIOR: materialIridescenceIOR,
  32173. materialIridescenceThickness: materialIridescenceThickness,
  32174. materialLightMap: materialLightMap,
  32175. materialLineDashOffset: materialLineDashOffset,
  32176. materialLineDashSize: materialLineDashSize,
  32177. materialLineGapSize: materialLineGapSize,
  32178. materialLineScale: materialLineScale,
  32179. materialLineWidth: materialLineWidth,
  32180. materialMetalness: materialMetalness,
  32181. materialNormal: materialNormal,
  32182. materialOpacity: materialOpacity,
  32183. materialPointSize: materialPointSize,
  32184. materialReference: materialReference,
  32185. materialReflectivity: materialReflectivity,
  32186. materialRefractionRatio: materialRefractionRatio,
  32187. materialRotation: materialRotation,
  32188. materialRoughness: materialRoughness,
  32189. materialSheen: materialSheen,
  32190. materialSheenRoughness: materialSheenRoughness,
  32191. materialShininess: materialShininess,
  32192. materialSpecular: materialSpecular,
  32193. materialSpecularColor: materialSpecularColor,
  32194. materialSpecularIntensity: materialSpecularIntensity,
  32195. materialSpecularStrength: materialSpecularStrength,
  32196. materialThickness: materialThickness,
  32197. materialTransmission: materialTransmission,
  32198. max: max$1,
  32199. maxMipLevel: maxMipLevel,
  32200. mediumpModelViewMatrix: mediumpModelViewMatrix,
  32201. metalness: metalness,
  32202. min: min$1,
  32203. mix: mix,
  32204. mixElement: mixElement,
  32205. mod: mod,
  32206. modInt: modInt,
  32207. modelDirection: modelDirection,
  32208. modelNormalMatrix: modelNormalMatrix,
  32209. modelPosition: modelPosition,
  32210. modelRadius: modelRadius,
  32211. modelScale: modelScale,
  32212. modelViewMatrix: modelViewMatrix,
  32213. modelViewPosition: modelViewPosition,
  32214. modelViewProjection: modelViewProjection,
  32215. modelWorldMatrix: modelWorldMatrix,
  32216. modelWorldMatrixInverse: modelWorldMatrixInverse,
  32217. morphReference: morphReference,
  32218. mrt: mrt,
  32219. mul: mul,
  32220. mx_aastep: mx_aastep,
  32221. mx_add: mx_add,
  32222. mx_atan2: mx_atan2,
  32223. mx_cell_noise_float: mx_cell_noise_float,
  32224. mx_contrast: mx_contrast,
  32225. mx_divide: mx_divide,
  32226. mx_fractal_noise_float: mx_fractal_noise_float,
  32227. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  32228. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  32229. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  32230. mx_frame: mx_frame,
  32231. mx_heighttonormal: mx_heighttonormal,
  32232. mx_hsvtorgb: mx_hsvtorgb,
  32233. mx_ifequal: mx_ifequal,
  32234. mx_ifgreater: mx_ifgreater,
  32235. mx_ifgreatereq: mx_ifgreatereq,
  32236. mx_invert: mx_invert,
  32237. mx_modulo: mx_modulo,
  32238. mx_multiply: mx_multiply,
  32239. mx_noise_float: mx_noise_float,
  32240. mx_noise_vec3: mx_noise_vec3,
  32241. mx_noise_vec4: mx_noise_vec4,
  32242. mx_place2d: mx_place2d,
  32243. mx_power: mx_power,
  32244. mx_ramp4: mx_ramp4,
  32245. mx_ramplr: mx_ramplr,
  32246. mx_ramptb: mx_ramptb,
  32247. mx_rgbtohsv: mx_rgbtohsv,
  32248. mx_rotate2d: mx_rotate2d,
  32249. mx_rotate3d: mx_rotate3d,
  32250. mx_safepower: mx_safepower,
  32251. mx_separate: mx_separate,
  32252. mx_splitlr: mx_splitlr,
  32253. mx_splittb: mx_splittb,
  32254. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  32255. mx_subtract: mx_subtract,
  32256. mx_timer: mx_timer,
  32257. mx_transform_uv: mx_transform_uv,
  32258. mx_unifiednoise2d: mx_unifiednoise2d,
  32259. mx_unifiednoise3d: mx_unifiednoise3d,
  32260. mx_worley_noise_float: mx_worley_noise_float,
  32261. mx_worley_noise_vec2: mx_worley_noise_vec2,
  32262. mx_worley_noise_vec3: mx_worley_noise_vec3,
  32263. negate: negate,
  32264. neutralToneMapping: neutralToneMapping,
  32265. nodeArray: nodeArray,
  32266. nodeImmutable: nodeImmutable,
  32267. nodeObject: nodeObject,
  32268. nodeObjectIntent: nodeObjectIntent,
  32269. nodeObjects: nodeObjects,
  32270. nodeProxy: nodeProxy,
  32271. nodeProxyIntent: nodeProxyIntent,
  32272. normalFlat: normalFlat,
  32273. normalGeometry: normalGeometry,
  32274. normalLocal: normalLocal,
  32275. normalMap: normalMap,
  32276. normalView: normalView,
  32277. normalViewGeometry: normalViewGeometry,
  32278. normalWorld: normalWorld,
  32279. normalWorldGeometry: normalWorldGeometry,
  32280. normalize: normalize,
  32281. not: not,
  32282. notEqual: notEqual,
  32283. numWorkgroups: numWorkgroups,
  32284. objectDirection: objectDirection,
  32285. objectGroup: objectGroup,
  32286. objectPosition: objectPosition,
  32287. objectRadius: objectRadius,
  32288. objectScale: objectScale,
  32289. objectViewPosition: objectViewPosition,
  32290. objectWorldMatrix: objectWorldMatrix,
  32291. oneMinus: oneMinus,
  32292. or: or,
  32293. orthographicDepthToViewZ: orthographicDepthToViewZ,
  32294. oscSawtooth: oscSawtooth,
  32295. oscSine: oscSine,
  32296. oscSquare: oscSquare,
  32297. oscTriangle: oscTriangle,
  32298. output: output,
  32299. outputStruct: outputStruct,
  32300. overlay: overlay,
  32301. overloadingFn: overloadingFn,
  32302. parabola: parabola,
  32303. parallaxDirection: parallaxDirection,
  32304. parallaxUV: parallaxUV,
  32305. parameter: parameter,
  32306. pass: pass,
  32307. passTexture: passTexture,
  32308. pcurve: pcurve,
  32309. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  32310. pmremTexture: pmremTexture,
  32311. pointShadow: pointShadow,
  32312. pointUV: pointUV,
  32313. pointWidth: pointWidth,
  32314. positionGeometry: positionGeometry,
  32315. positionLocal: positionLocal,
  32316. positionPrevious: positionPrevious,
  32317. positionView: positionView,
  32318. positionViewDirection: positionViewDirection,
  32319. positionWorld: positionWorld,
  32320. positionWorldDirection: positionWorldDirection,
  32321. posterize: posterize,
  32322. pow: pow,
  32323. pow2: pow2,
  32324. pow3: pow3,
  32325. pow4: pow4,
  32326. premultiplyAlpha: premultiplyAlpha,
  32327. property: property,
  32328. quadBroadcast: quadBroadcast,
  32329. quadSwapDiagonal: quadSwapDiagonal,
  32330. quadSwapX: quadSwapX,
  32331. quadSwapY: quadSwapY,
  32332. radians: radians,
  32333. rand: rand,
  32334. range: range,
  32335. rangeFog: rangeFog,
  32336. rangeFogFactor: rangeFogFactor,
  32337. reciprocal: reciprocal,
  32338. reference: reference,
  32339. referenceBuffer: referenceBuffer,
  32340. reflect: reflect,
  32341. reflectVector: reflectVector,
  32342. reflectView: reflectView,
  32343. reflector: reflector,
  32344. refract: refract,
  32345. refractVector: refractVector,
  32346. refractView: refractView,
  32347. reinhardToneMapping: reinhardToneMapping,
  32348. remap: remap,
  32349. remapClamp: remapClamp,
  32350. renderGroup: renderGroup,
  32351. renderOutput: renderOutput,
  32352. rendererReference: rendererReference,
  32353. rotate: rotate,
  32354. rotateUV: rotateUV,
  32355. roughness: roughness,
  32356. round: round,
  32357. rtt: rtt,
  32358. sRGBTransferEOTF: sRGBTransferEOTF,
  32359. sRGBTransferOETF: sRGBTransferOETF,
  32360. sample: sample,
  32361. sampler: sampler,
  32362. samplerComparison: samplerComparison,
  32363. saturate: saturate,
  32364. saturation: saturation,
  32365. screen: screen,
  32366. screenCoordinate: screenCoordinate,
  32367. screenDPR: screenDPR,
  32368. screenSize: screenSize,
  32369. screenUV: screenUV,
  32370. scriptable: scriptable,
  32371. scriptableValue: scriptableValue,
  32372. select: select,
  32373. setCurrentStack: setCurrentStack,
  32374. setName: setName,
  32375. shaderStages: shaderStages,
  32376. shadow: shadow,
  32377. shadowPositionWorld: shadowPositionWorld,
  32378. shapeCircle: shapeCircle,
  32379. sharedUniformGroup: sharedUniformGroup,
  32380. sheen: sheen,
  32381. sheenRoughness: sheenRoughness,
  32382. shiftLeft: shiftLeft,
  32383. shiftRight: shiftRight,
  32384. shininess: shininess,
  32385. sign: sign,
  32386. sin: sin,
  32387. sinc: sinc,
  32388. skinning: skinning,
  32389. smoothstep: smoothstep,
  32390. smoothstepElement: smoothstepElement,
  32391. specularColor: specularColor,
  32392. specularF90: specularF90,
  32393. spherizeUV: spherizeUV,
  32394. split: split,
  32395. spritesheetUV: spritesheetUV,
  32396. sqrt: sqrt,
  32397. stack: stack,
  32398. step: step,
  32399. stepElement: stepElement,
  32400. storage: storage,
  32401. storageBarrier: storageBarrier,
  32402. storageObject: storageObject,
  32403. storageTexture: storageTexture,
  32404. string: string,
  32405. struct: struct,
  32406. sub: sub,
  32407. subBuild: subBuild,
  32408. subgroupAdd: subgroupAdd,
  32409. subgroupAll: subgroupAll,
  32410. subgroupAnd: subgroupAnd,
  32411. subgroupAny: subgroupAny,
  32412. subgroupBallot: subgroupBallot,
  32413. subgroupBroadcast: subgroupBroadcast,
  32414. subgroupBroadcastFirst: subgroupBroadcastFirst,
  32415. subgroupElect: subgroupElect,
  32416. subgroupExclusiveAdd: subgroupExclusiveAdd,
  32417. subgroupExclusiveMul: subgroupExclusiveMul,
  32418. subgroupInclusiveAdd: subgroupInclusiveAdd,
  32419. subgroupInclusiveMul: subgroupInclusiveMul,
  32420. subgroupIndex: subgroupIndex,
  32421. subgroupMax: subgroupMax,
  32422. subgroupMin: subgroupMin,
  32423. subgroupMul: subgroupMul,
  32424. subgroupOr: subgroupOr,
  32425. subgroupShuffle: subgroupShuffle,
  32426. subgroupShuffleDown: subgroupShuffleDown,
  32427. subgroupShuffleUp: subgroupShuffleUp,
  32428. subgroupShuffleXor: subgroupShuffleXor,
  32429. subgroupSize: subgroupSize,
  32430. subgroupXor: subgroupXor,
  32431. tan: tan,
  32432. tangentGeometry: tangentGeometry,
  32433. tangentLocal: tangentLocal,
  32434. tangentView: tangentView,
  32435. tangentWorld: tangentWorld,
  32436. texture: texture,
  32437. texture3D: texture3D,
  32438. textureBarrier: textureBarrier,
  32439. textureBicubic: textureBicubic,
  32440. textureBicubicLevel: textureBicubicLevel,
  32441. textureCubeUV: textureCubeUV,
  32442. textureLoad: textureLoad,
  32443. textureSize: textureSize,
  32444. textureStore: textureStore,
  32445. thickness: thickness,
  32446. time: time,
  32447. toneMapping: toneMapping,
  32448. toneMappingExposure: toneMappingExposure,
  32449. toonOutlinePass: toonOutlinePass,
  32450. transformDirection: transformDirection,
  32451. transformNormal: transformNormal,
  32452. transformNormalToView: transformNormalToView,
  32453. transformedClearcoatNormalView: transformedClearcoatNormalView,
  32454. transformedNormalView: transformedNormalView,
  32455. transformedNormalWorld: transformedNormalWorld,
  32456. transmission: transmission,
  32457. transpose: transpose,
  32458. triNoise3D: triNoise3D,
  32459. triplanarTexture: triplanarTexture,
  32460. triplanarTextures: triplanarTextures,
  32461. trunc: trunc,
  32462. uint: uint,
  32463. uintBitsToFloat: uintBitsToFloat,
  32464. uniform: uniform,
  32465. uniformArray: uniformArray,
  32466. uniformCubeTexture: uniformCubeTexture,
  32467. uniformFlow: uniformFlow,
  32468. uniformGroup: uniformGroup,
  32469. uniformTexture: uniformTexture,
  32470. unpremultiplyAlpha: unpremultiplyAlpha,
  32471. userData: userData,
  32472. uv: uv$1,
  32473. uvec2: uvec2,
  32474. uvec3: uvec3,
  32475. uvec4: uvec4,
  32476. varying: varying,
  32477. varyingProperty: varyingProperty,
  32478. vec2: vec2,
  32479. vec3: vec3,
  32480. vec4: vec4,
  32481. vectorComponents: vectorComponents,
  32482. velocity: velocity,
  32483. vertexColor: vertexColor,
  32484. vertexIndex: vertexIndex,
  32485. vertexStage: vertexStage,
  32486. vibrance: vibrance,
  32487. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  32488. viewZToOrthographicDepth: viewZToOrthographicDepth,
  32489. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  32490. viewport: viewport,
  32491. viewportCoordinate: viewportCoordinate,
  32492. viewportDepthTexture: viewportDepthTexture,
  32493. viewportLinearDepth: viewportLinearDepth,
  32494. viewportMipTexture: viewportMipTexture,
  32495. viewportResolution: viewportResolution,
  32496. viewportSafeUV: viewportSafeUV,
  32497. viewportSharedTexture: viewportSharedTexture,
  32498. viewportSize: viewportSize,
  32499. viewportTexture: viewportTexture,
  32500. viewportUV: viewportUV,
  32501. wgsl: wgsl,
  32502. wgslFn: wgslFn,
  32503. workgroupArray: workgroupArray,
  32504. workgroupBarrier: workgroupBarrier,
  32505. workgroupId: workgroupId,
  32506. workingToColorSpace: workingToColorSpace,
  32507. xor: xor
  32508. });
  32509. const _clearColor = /*@__PURE__*/ new Color4();
  32510. /**
  32511. * This renderer module manages the background.
  32512. *
  32513. * @private
  32514. * @augments DataMap
  32515. */
  32516. class Background extends DataMap {
  32517. /**
  32518. * Constructs a new background management component.
  32519. *
  32520. * @param {Renderer} renderer - The renderer.
  32521. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  32522. */
  32523. constructor( renderer, nodes ) {
  32524. super();
  32525. /**
  32526. * The renderer.
  32527. *
  32528. * @type {Renderer}
  32529. */
  32530. this.renderer = renderer;
  32531. /**
  32532. * Renderer component for managing nodes related logic.
  32533. *
  32534. * @type {Nodes}
  32535. */
  32536. this.nodes = nodes;
  32537. }
  32538. /**
  32539. * Updates the background for the given scene. Depending on how `Scene.background`
  32540. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  32541. * or add a mesh to the render list for rendering the background as a textured plane
  32542. * or skybox.
  32543. *
  32544. * @param {Scene} scene - The scene.
  32545. * @param {RenderList} renderList - The current render list.
  32546. * @param {RenderContext} renderContext - The current render context.
  32547. */
  32548. update( scene, renderList, renderContext ) {
  32549. const renderer = this.renderer;
  32550. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  32551. let forceClear = false;
  32552. if ( background === null ) {
  32553. // no background settings, use clear color configuration from the renderer
  32554. renderer._clearColor.getRGB( _clearColor );
  32555. _clearColor.a = renderer._clearColor.a;
  32556. } else if ( background.isColor === true ) {
  32557. // background is an opaque color
  32558. background.getRGB( _clearColor );
  32559. _clearColor.a = 1;
  32560. forceClear = true;
  32561. } else if ( background.isNode === true ) {
  32562. const sceneData = this.get( scene );
  32563. const backgroundNode = background;
  32564. _clearColor.copy( renderer._clearColor );
  32565. let backgroundMesh = sceneData.backgroundMesh;
  32566. if ( backgroundMesh === undefined ) {
  32567. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  32568. // @TODO: Add Texture2D support using node context
  32569. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  32570. getTextureLevel: () => backgroundBlurriness
  32571. } );
  32572. let viewProj = modelViewProjection;
  32573. viewProj = viewProj.setZ( viewProj.w );
  32574. const nodeMaterial = new NodeMaterial();
  32575. nodeMaterial.name = 'Background.material';
  32576. nodeMaterial.side = BackSide;
  32577. nodeMaterial.depthTest = false;
  32578. nodeMaterial.depthWrite = false;
  32579. nodeMaterial.allowOverride = false;
  32580. nodeMaterial.fog = false;
  32581. nodeMaterial.lights = false;
  32582. nodeMaterial.vertexNode = viewProj;
  32583. nodeMaterial.colorNode = backgroundMeshNode;
  32584. sceneData.backgroundMeshNode = backgroundMeshNode;
  32585. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  32586. backgroundMesh.frustumCulled = false;
  32587. backgroundMesh.name = 'Background.mesh';
  32588. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  32589. this.matrixWorld.copyPosition( camera.matrixWorld );
  32590. };
  32591. function onBackgroundDispose() {
  32592. background.removeEventListener( 'dispose', onBackgroundDispose );
  32593. backgroundMesh.material.dispose();
  32594. backgroundMesh.geometry.dispose();
  32595. }
  32596. background.addEventListener( 'dispose', onBackgroundDispose );
  32597. }
  32598. const backgroundCacheKey = backgroundNode.getCacheKey();
  32599. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  32600. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  32601. sceneData.backgroundMeshNode.needsUpdate = true;
  32602. backgroundMesh.material.needsUpdate = true;
  32603. sceneData.backgroundCacheKey = backgroundCacheKey;
  32604. }
  32605. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  32606. } else {
  32607. error( 'Renderer: Unsupported background configuration.', background );
  32608. }
  32609. //
  32610. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  32611. if ( environmentBlendMode === 'additive' ) {
  32612. _clearColor.set( 0, 0, 0, 1 );
  32613. } else if ( environmentBlendMode === 'alpha-blend' ) {
  32614. _clearColor.set( 0, 0, 0, 0 );
  32615. }
  32616. //
  32617. if ( renderer.autoClear === true || forceClear === true ) {
  32618. const clearColorValue = renderContext.clearColorValue;
  32619. clearColorValue.r = _clearColor.r;
  32620. clearColorValue.g = _clearColor.g;
  32621. clearColorValue.b = _clearColor.b;
  32622. clearColorValue.a = _clearColor.a;
  32623. // premultiply alpha
  32624. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  32625. clearColorValue.r *= clearColorValue.a;
  32626. clearColorValue.g *= clearColorValue.a;
  32627. clearColorValue.b *= clearColorValue.a;
  32628. }
  32629. //
  32630. renderContext.depthClearValue = renderer._clearDepth;
  32631. renderContext.stencilClearValue = renderer._clearStencil;
  32632. renderContext.clearColor = renderer.autoClearColor === true;
  32633. renderContext.clearDepth = renderer.autoClearDepth === true;
  32634. renderContext.clearStencil = renderer.autoClearStencil === true;
  32635. } else {
  32636. renderContext.clearColor = false;
  32637. renderContext.clearDepth = false;
  32638. renderContext.clearStencil = false;
  32639. }
  32640. }
  32641. }
  32642. let _id$6 = 0;
  32643. /**
  32644. * A bind group represents a collection of bindings and thus a collection
  32645. * or resources. Bind groups are assigned to pipelines to provide them
  32646. * with the required resources (like uniform buffers or textures).
  32647. *
  32648. * @private
  32649. */
  32650. class BindGroup {
  32651. /**
  32652. * Constructs a new bind group.
  32653. *
  32654. * @param {string} name - The bind group's name.
  32655. * @param {Array<Binding>} bindings - An array of bindings.
  32656. * @param {number} index - The group index.
  32657. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  32658. */
  32659. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  32660. /**
  32661. * The bind group's name.
  32662. *
  32663. * @type {string}
  32664. */
  32665. this.name = name;
  32666. /**
  32667. * An array of bindings.
  32668. *
  32669. * @type {Array<Binding>}
  32670. */
  32671. this.bindings = bindings;
  32672. /**
  32673. * The group index.
  32674. *
  32675. * @type {number}
  32676. */
  32677. this.index = index;
  32678. /**
  32679. * An array of reference bindings.
  32680. *
  32681. * @type {Array<Binding>}
  32682. */
  32683. this.bindingsReference = bindingsReference;
  32684. /**
  32685. * The group's ID.
  32686. *
  32687. * @type {number}
  32688. */
  32689. this.id = _id$6 ++;
  32690. }
  32691. }
  32692. /**
  32693. * This module represents the state of a node builder after it was
  32694. * used to build the nodes for a render object. The state holds the
  32695. * results of the build for further processing in the renderer.
  32696. *
  32697. * Render objects with identical cache keys share the same node builder state.
  32698. *
  32699. * @private
  32700. */
  32701. class NodeBuilderState {
  32702. /**
  32703. * Constructs a new node builder state.
  32704. *
  32705. * @param {string} vertexShader - The native vertex shader code.
  32706. * @param {string} fragmentShader - The native fragment shader code.
  32707. * @param {string} computeShader - The native compute shader code.
  32708. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  32709. * @param {Array<BindGroup>} bindings - An array of bind groups.
  32710. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  32711. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  32712. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  32713. * @param {NodeMaterialObserver} observer - A node material observer.
  32714. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  32715. */
  32716. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  32717. /**
  32718. * The native vertex shader code.
  32719. *
  32720. * @type {string}
  32721. */
  32722. this.vertexShader = vertexShader;
  32723. /**
  32724. * The native fragment shader code.
  32725. *
  32726. * @type {string}
  32727. */
  32728. this.fragmentShader = fragmentShader;
  32729. /**
  32730. * The native compute shader code.
  32731. *
  32732. * @type {string}
  32733. */
  32734. this.computeShader = computeShader;
  32735. /**
  32736. * An array with transform attribute objects.
  32737. * Only relevant when using compute shaders with WebGL 2.
  32738. *
  32739. * @type {Array<Object>}
  32740. */
  32741. this.transforms = transforms;
  32742. /**
  32743. * An array of node attributes representing
  32744. * the attributes of the shaders.
  32745. *
  32746. * @type {Array<NodeAttribute>}
  32747. */
  32748. this.nodeAttributes = nodeAttributes;
  32749. /**
  32750. * An array of bind groups representing the uniform or storage
  32751. * buffers, texture or samplers of the shader.
  32752. *
  32753. * @type {Array<BindGroup>}
  32754. */
  32755. this.bindings = bindings;
  32756. /**
  32757. * An array of nodes that implement their `update()` method.
  32758. *
  32759. * @type {Array<Node>}
  32760. */
  32761. this.updateNodes = updateNodes;
  32762. /**
  32763. * An array of nodes that implement their `updateBefore()` method.
  32764. *
  32765. * @type {Array<Node>}
  32766. */
  32767. this.updateBeforeNodes = updateBeforeNodes;
  32768. /**
  32769. * An array of nodes that implement their `updateAfter()` method.
  32770. *
  32771. * @type {Array<Node>}
  32772. */
  32773. this.updateAfterNodes = updateAfterNodes;
  32774. /**
  32775. * A node material observer.
  32776. *
  32777. * @type {NodeMaterialObserver}
  32778. */
  32779. this.observer = observer;
  32780. /**
  32781. * How often this state is used by render objects.
  32782. *
  32783. * @type {number}
  32784. */
  32785. this.usedTimes = 0;
  32786. }
  32787. /**
  32788. * This method is used to create a array of bind groups based
  32789. * on the existing bind groups of this state. Shared groups are
  32790. * not cloned.
  32791. *
  32792. * @return {Array<BindGroup>} A array of bind groups.
  32793. */
  32794. createBindings() {
  32795. const bindings = [];
  32796. for ( const instanceGroup of this.bindings ) {
  32797. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  32798. if ( shared !== true ) {
  32799. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  32800. bindings.push( bindingsGroup );
  32801. for ( const instanceBinding of instanceGroup.bindings ) {
  32802. bindingsGroup.bindings.push( instanceBinding.clone() );
  32803. }
  32804. } else {
  32805. bindings.push( instanceGroup );
  32806. }
  32807. }
  32808. return bindings;
  32809. }
  32810. }
  32811. /**
  32812. * {@link NodeBuilder} is going to create instances of this class during the build process
  32813. * of nodes. They represent the final shader attributes that are going to be generated
  32814. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  32815. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  32816. */
  32817. class NodeAttribute {
  32818. /**
  32819. * Constructs a new node attribute.
  32820. *
  32821. * @param {string} name - The name of the attribute.
  32822. * @param {string} type - The type of the attribute.
  32823. * @param {?Node} node - An optional reference to the node.
  32824. */
  32825. constructor( name, type, node = null ) {
  32826. /**
  32827. * This flag can be used for type testing.
  32828. *
  32829. * @type {boolean}
  32830. * @readonly
  32831. * @default true
  32832. */
  32833. this.isNodeAttribute = true;
  32834. /**
  32835. * The name of the attribute.
  32836. *
  32837. * @type {string}
  32838. */
  32839. this.name = name;
  32840. /**
  32841. * The type of the attribute.
  32842. *
  32843. * @type {string}
  32844. */
  32845. this.type = type;
  32846. /**
  32847. * An optional reference to the node.
  32848. *
  32849. * @type {?Node}
  32850. * @default null
  32851. */
  32852. this.node = node;
  32853. }
  32854. }
  32855. /**
  32856. * {@link NodeBuilder} is going to create instances of this class during the build process
  32857. * of nodes. They represent the final shader uniforms that are going to be generated
  32858. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  32859. * for this purpose.
  32860. */
  32861. class NodeUniform {
  32862. /**
  32863. * Constructs a new node uniform.
  32864. *
  32865. * @param {string} name - The name of the uniform.
  32866. * @param {string} type - The type of the uniform.
  32867. * @param {UniformNode} node - An reference to the node.
  32868. */
  32869. constructor( name, type, node ) {
  32870. /**
  32871. * This flag can be used for type testing.
  32872. *
  32873. * @type {boolean}
  32874. * @readonly
  32875. * @default true
  32876. */
  32877. this.isNodeUniform = true;
  32878. /**
  32879. * The name of the uniform.
  32880. *
  32881. * @type {string}
  32882. */
  32883. this.name = name;
  32884. /**
  32885. * The type of the uniform.
  32886. *
  32887. * @type {string}
  32888. */
  32889. this.type = type;
  32890. /**
  32891. * An reference to the node.
  32892. *
  32893. * @type {UniformNode}
  32894. */
  32895. this.node = node;
  32896. }
  32897. /**
  32898. * The value of the uniform node.
  32899. *
  32900. * @type {any}
  32901. */
  32902. get value() {
  32903. return this.node.value;
  32904. }
  32905. set value( val ) {
  32906. this.node.value = val;
  32907. }
  32908. /**
  32909. * The id of the uniform node.
  32910. *
  32911. * @type {number}
  32912. */
  32913. get id() {
  32914. return this.node.id;
  32915. }
  32916. /**
  32917. * The uniform node's group.
  32918. *
  32919. * @type {UniformGroupNode}
  32920. */
  32921. get groupNode() {
  32922. return this.node.groupNode;
  32923. }
  32924. }
  32925. /**
  32926. * {@link NodeBuilder} is going to create instances of this class during the build process
  32927. * of nodes. They represent the final shader variables that are going to be generated
  32928. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  32929. * this purpose.
  32930. */
  32931. class NodeVar {
  32932. /**
  32933. * Constructs a new node variable.
  32934. *
  32935. * @param {string} name - The name of the variable.
  32936. * @param {string} type - The type of the variable.
  32937. * @param {boolean} [readOnly=false] - The read-only flag.
  32938. * @param {?number} [count=null] - The size.
  32939. */
  32940. constructor( name, type, readOnly = false, count = null ) {
  32941. /**
  32942. * This flag can be used for type testing.
  32943. *
  32944. * @type {boolean}
  32945. * @readonly
  32946. * @default true
  32947. */
  32948. this.isNodeVar = true;
  32949. /**
  32950. * The name of the variable.
  32951. *
  32952. * @type {string}
  32953. */
  32954. this.name = name;
  32955. /**
  32956. * The type of the variable.
  32957. *
  32958. * @type {string}
  32959. */
  32960. this.type = type;
  32961. /**
  32962. * The read-only flag.
  32963. *
  32964. * @type {boolean}
  32965. */
  32966. this.readOnly = readOnly;
  32967. /**
  32968. * The size.
  32969. *
  32970. * @type {?number}
  32971. */
  32972. this.count = count;
  32973. }
  32974. }
  32975. /**
  32976. * {@link NodeBuilder} is going to create instances of this class during the build process
  32977. * of nodes. They represent the final shader varyings that are going to be generated
  32978. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  32979. * this purpose.
  32980. *
  32981. * @augments NodeVar
  32982. */
  32983. class NodeVarying extends NodeVar {
  32984. /**
  32985. * Constructs a new node varying.
  32986. *
  32987. * @param {string} name - The name of the varying.
  32988. * @param {string} type - The type of the varying.
  32989. * @param {?string} interpolationType - The interpolation type of the varying.
  32990. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32991. */
  32992. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  32993. super( name, type );
  32994. /**
  32995. * Whether this varying requires interpolation or not. This property can be used
  32996. * to check if the varying can be optimized for a variable.
  32997. *
  32998. * @type {boolean}
  32999. * @default false
  33000. */
  33001. this.needsInterpolation = false;
  33002. /**
  33003. * This flag can be used for type testing.
  33004. *
  33005. * @type {boolean}
  33006. * @readonly
  33007. * @default true
  33008. */
  33009. this.isNodeVarying = true;
  33010. /**
  33011. * The interpolation type of the varying data.
  33012. *
  33013. * @type {?string}
  33014. * @default null
  33015. */
  33016. this.interpolationType = interpolationType;
  33017. /**
  33018. * The interpolation sampling type of varying data.
  33019. *
  33020. * @type {?string}
  33021. * @default null
  33022. */
  33023. this.interpolationSampling = interpolationSampling;
  33024. }
  33025. }
  33026. /**
  33027. * {@link NodeBuilder} is going to create instances of this class during the build process
  33028. * of nodes. They represent user-defined, native shader code portions that are going to be
  33029. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  33030. * for this purpose.
  33031. */
  33032. class NodeCode {
  33033. /**
  33034. * Constructs a new code node.
  33035. *
  33036. * @param {string} name - The name of the code.
  33037. * @param {string} type - The node type.
  33038. * @param {string} [code=''] - The native shader code.
  33039. */
  33040. constructor( name, type, code = '' ) {
  33041. /**
  33042. * The name of the code.
  33043. *
  33044. * @type {string}
  33045. */
  33046. this.name = name;
  33047. /**
  33048. * The node type.
  33049. *
  33050. * @type {string}
  33051. */
  33052. this.type = type;
  33053. /**
  33054. * The native shader code.
  33055. *
  33056. * @type {string}
  33057. * @default ''
  33058. */
  33059. this.code = code;
  33060. Object.defineProperty( this, 'isNodeCode', { value: true } );
  33061. }
  33062. }
  33063. let _id$5 = 0;
  33064. /**
  33065. * This utility class is used in {@link NodeBuilder} as an internal
  33066. * cache data structure for node data.
  33067. */
  33068. class NodeCache {
  33069. /**
  33070. * Constructs a new node cache.
  33071. *
  33072. * @param {?NodeCache} parent - A reference to a parent cache.
  33073. */
  33074. constructor( parent = null ) {
  33075. /**
  33076. * The id of the cache.
  33077. *
  33078. * @type {number}
  33079. * @readonly
  33080. */
  33081. this.id = _id$5 ++;
  33082. /**
  33083. * A weak map for managing node data.
  33084. *
  33085. * @type {WeakMap<Node, Object>}
  33086. */
  33087. this.nodesData = new WeakMap();
  33088. /**
  33089. * Reference to a parent node cache.
  33090. *
  33091. * @type {?NodeCache}
  33092. * @default null
  33093. */
  33094. this.parent = parent;
  33095. }
  33096. /**
  33097. * Returns the data for the given node.
  33098. *
  33099. * @param {Node} node - The node.
  33100. * @return {?Object} The data for the node.
  33101. */
  33102. getData( node ) {
  33103. let data = this.nodesData.get( node );
  33104. if ( data === undefined && this.parent !== null ) {
  33105. data = this.parent.getData( node );
  33106. }
  33107. return data;
  33108. }
  33109. /**
  33110. * Sets the data for a given node.
  33111. *
  33112. * @param {Node} node - The node.
  33113. * @param {Object} data - The data that should be cached.
  33114. */
  33115. setData( node, data ) {
  33116. this.nodesData.set( node, data );
  33117. }
  33118. }
  33119. class StructType {
  33120. constructor( name, members ) {
  33121. this.name = name;
  33122. this.members = members;
  33123. this.output = false;
  33124. }
  33125. }
  33126. /**
  33127. * Abstract base class for uniforms.
  33128. *
  33129. * @abstract
  33130. * @private
  33131. */
  33132. class Uniform {
  33133. /**
  33134. * Constructs a new uniform.
  33135. *
  33136. * @param {string} name - The uniform's name.
  33137. * @param {any} value - The uniform's value.
  33138. */
  33139. constructor( name, value ) {
  33140. /**
  33141. * The uniform's name.
  33142. *
  33143. * @type {string}
  33144. */
  33145. this.name = name;
  33146. /**
  33147. * The uniform's value.
  33148. *
  33149. * @type {any}
  33150. */
  33151. this.value = value;
  33152. /**
  33153. * Used to build the uniform buffer according to the STD140 layout.
  33154. * Derived uniforms will set this property to a data type specific
  33155. * value.
  33156. *
  33157. * @type {number}
  33158. */
  33159. this.boundary = 0;
  33160. /**
  33161. * The item size. Derived uniforms will set this property to a data
  33162. * type specific value.
  33163. *
  33164. * @type {number}
  33165. */
  33166. this.itemSize = 0;
  33167. /**
  33168. * This property is set by {@link UniformsGroup} and marks
  33169. * the start position in the uniform buffer.
  33170. *
  33171. * @type {number}
  33172. */
  33173. this.offset = 0;
  33174. }
  33175. /**
  33176. * Sets the uniform's value.
  33177. *
  33178. * @param {any} value - The value to set.
  33179. */
  33180. setValue( value ) {
  33181. this.value = value;
  33182. }
  33183. /**
  33184. * Returns the uniform's value.
  33185. *
  33186. * @return {any} The value.
  33187. */
  33188. getValue() {
  33189. return this.value;
  33190. }
  33191. }
  33192. /**
  33193. * Represents a Number uniform.
  33194. *
  33195. * @private
  33196. * @augments Uniform
  33197. */
  33198. class NumberUniform extends Uniform {
  33199. /**
  33200. * Constructs a new Number uniform.
  33201. *
  33202. * @param {string} name - The uniform's name.
  33203. * @param {number} value - The uniform's value.
  33204. */
  33205. constructor( name, value = 0 ) {
  33206. super( name, value );
  33207. /**
  33208. * This flag can be used for type testing.
  33209. *
  33210. * @type {boolean}
  33211. * @readonly
  33212. * @default true
  33213. */
  33214. this.isNumberUniform = true;
  33215. this.boundary = 4;
  33216. this.itemSize = 1;
  33217. }
  33218. }
  33219. /**
  33220. * Represents a Vector2 uniform.
  33221. *
  33222. * @private
  33223. * @augments Uniform
  33224. */
  33225. class Vector2Uniform extends Uniform {
  33226. /**
  33227. * Constructs a new Number uniform.
  33228. *
  33229. * @param {string} name - The uniform's name.
  33230. * @param {Vector2} value - The uniform's value.
  33231. */
  33232. constructor( name, value = new Vector2() ) {
  33233. super( name, value );
  33234. /**
  33235. * This flag can be used for type testing.
  33236. *
  33237. * @type {boolean}
  33238. * @readonly
  33239. * @default true
  33240. */
  33241. this.isVector2Uniform = true;
  33242. this.boundary = 8;
  33243. this.itemSize = 2;
  33244. }
  33245. }
  33246. /**
  33247. * Represents a Vector3 uniform.
  33248. *
  33249. * @private
  33250. * @augments Uniform
  33251. */
  33252. class Vector3Uniform extends Uniform {
  33253. /**
  33254. * Constructs a new Number uniform.
  33255. *
  33256. * @param {string} name - The uniform's name.
  33257. * @param {Vector3} value - The uniform's value.
  33258. */
  33259. constructor( name, value = new Vector3() ) {
  33260. super( name, value );
  33261. /**
  33262. * This flag can be used for type testing.
  33263. *
  33264. * @type {boolean}
  33265. * @readonly
  33266. * @default true
  33267. */
  33268. this.isVector3Uniform = true;
  33269. this.boundary = 16;
  33270. this.itemSize = 3;
  33271. }
  33272. }
  33273. /**
  33274. * Represents a Vector4 uniform.
  33275. *
  33276. * @private
  33277. * @augments Uniform
  33278. */
  33279. class Vector4Uniform extends Uniform {
  33280. /**
  33281. * Constructs a new Number uniform.
  33282. *
  33283. * @param {string} name - The uniform's name.
  33284. * @param {Vector4} value - The uniform's value.
  33285. */
  33286. constructor( name, value = new Vector4() ) {
  33287. super( name, value );
  33288. /**
  33289. * This flag can be used for type testing.
  33290. *
  33291. * @type {boolean}
  33292. * @readonly
  33293. * @default true
  33294. */
  33295. this.isVector4Uniform = true;
  33296. this.boundary = 16;
  33297. this.itemSize = 4;
  33298. }
  33299. }
  33300. /**
  33301. * Represents a Color uniform.
  33302. *
  33303. * @private
  33304. * @augments Uniform
  33305. */
  33306. class ColorUniform extends Uniform {
  33307. /**
  33308. * Constructs a new Number uniform.
  33309. *
  33310. * @param {string} name - The uniform's name.
  33311. * @param {Color} value - The uniform's value.
  33312. */
  33313. constructor( name, value = new Color() ) {
  33314. super( name, value );
  33315. /**
  33316. * This flag can be used for type testing.
  33317. *
  33318. * @type {boolean}
  33319. * @readonly
  33320. * @default true
  33321. */
  33322. this.isColorUniform = true;
  33323. this.boundary = 16;
  33324. this.itemSize = 3;
  33325. }
  33326. }
  33327. /**
  33328. * Represents a Matrix2 uniform.
  33329. *
  33330. * @private
  33331. * @augments Uniform
  33332. */
  33333. class Matrix2Uniform extends Uniform {
  33334. /**
  33335. * Constructs a new Number uniform.
  33336. *
  33337. * @param {string} name - The uniform's name.
  33338. * @param {Matrix2} value - The uniform's value.
  33339. */
  33340. constructor( name, value = new Matrix2() ) {
  33341. super( name, value );
  33342. /**
  33343. * This flag can be used for type testing.
  33344. *
  33345. * @type {boolean}
  33346. * @readonly
  33347. * @default true
  33348. */
  33349. this.isMatrix2Uniform = true;
  33350. this.boundary = 8;
  33351. this.itemSize = 4;
  33352. }
  33353. }
  33354. /**
  33355. * Represents a Matrix3 uniform.
  33356. *
  33357. * @private
  33358. * @augments Uniform
  33359. */
  33360. class Matrix3Uniform extends Uniform {
  33361. /**
  33362. * Constructs a new Number uniform.
  33363. *
  33364. * @param {string} name - The uniform's name.
  33365. * @param {Matrix3} value - The uniform's value.
  33366. */
  33367. constructor( name, value = new Matrix3() ) {
  33368. super( name, value );
  33369. /**
  33370. * This flag can be used for type testing.
  33371. *
  33372. * @type {boolean}
  33373. * @readonly
  33374. * @default true
  33375. */
  33376. this.isMatrix3Uniform = true;
  33377. this.boundary = 48;
  33378. this.itemSize = 12;
  33379. }
  33380. }
  33381. /**
  33382. * Represents a Matrix4 uniform.
  33383. *
  33384. * @private
  33385. * @augments Uniform
  33386. */
  33387. class Matrix4Uniform extends Uniform {
  33388. /**
  33389. * Constructs a new Number uniform.
  33390. *
  33391. * @param {string} name - The uniform's name.
  33392. * @param {Matrix4} value - The uniform's value.
  33393. */
  33394. constructor( name, value = new Matrix4() ) {
  33395. super( name, value );
  33396. /**
  33397. * This flag can be used for type testing.
  33398. *
  33399. * @type {boolean}
  33400. * @readonly
  33401. * @default true
  33402. */
  33403. this.isMatrix4Uniform = true;
  33404. this.boundary = 64;
  33405. this.itemSize = 16;
  33406. }
  33407. }
  33408. /**
  33409. * A special form of Number uniform binding type.
  33410. * It's value is managed by a node object.
  33411. *
  33412. * @private
  33413. * @augments NumberUniform
  33414. */
  33415. class NumberNodeUniform extends NumberUniform {
  33416. /**
  33417. * Constructs a new node-based Number uniform.
  33418. *
  33419. * @param {NodeUniform} nodeUniform - The node uniform.
  33420. */
  33421. constructor( nodeUniform ) {
  33422. super( nodeUniform.name, nodeUniform.value );
  33423. /**
  33424. * The node uniform.
  33425. *
  33426. * @type {NodeUniform}
  33427. */
  33428. this.nodeUniform = nodeUniform;
  33429. }
  33430. /**
  33431. * Overwritten to return the value of the node uniform.
  33432. *
  33433. * @return {number} The value.
  33434. */
  33435. getValue() {
  33436. return this.nodeUniform.value;
  33437. }
  33438. /**
  33439. * Returns the node uniform data type.
  33440. *
  33441. * @return {string} The data type.
  33442. */
  33443. getType() {
  33444. return this.nodeUniform.type;
  33445. }
  33446. }
  33447. /**
  33448. * A special form of Vector2 uniform binding type.
  33449. * It's value is managed by a node object.
  33450. *
  33451. * @private
  33452. * @augments Vector2Uniform
  33453. */
  33454. class Vector2NodeUniform extends Vector2Uniform {
  33455. /**
  33456. * Constructs a new node-based Vector2 uniform.
  33457. *
  33458. * @param {NodeUniform} nodeUniform - The node uniform.
  33459. */
  33460. constructor( nodeUniform ) {
  33461. super( nodeUniform.name, nodeUniform.value );
  33462. /**
  33463. * The node uniform.
  33464. *
  33465. * @type {NodeUniform}
  33466. */
  33467. this.nodeUniform = nodeUniform;
  33468. }
  33469. /**
  33470. * Overwritten to return the value of the node uniform.
  33471. *
  33472. * @return {Vector2} The value.
  33473. */
  33474. getValue() {
  33475. return this.nodeUniform.value;
  33476. }
  33477. /**
  33478. * Returns the node uniform data type.
  33479. *
  33480. * @return {string} The data type.
  33481. */
  33482. getType() {
  33483. return this.nodeUniform.type;
  33484. }
  33485. }
  33486. /**
  33487. * A special form of Vector3 uniform binding type.
  33488. * It's value is managed by a node object.
  33489. *
  33490. * @private
  33491. * @augments Vector3Uniform
  33492. */
  33493. class Vector3NodeUniform extends Vector3Uniform {
  33494. /**
  33495. * Constructs a new node-based Vector3 uniform.
  33496. *
  33497. * @param {NodeUniform} nodeUniform - The node uniform.
  33498. */
  33499. constructor( nodeUniform ) {
  33500. super( nodeUniform.name, nodeUniform.value );
  33501. /**
  33502. * The node uniform.
  33503. *
  33504. * @type {NodeUniform}
  33505. */
  33506. this.nodeUniform = nodeUniform;
  33507. }
  33508. /**
  33509. * Overwritten to return the value of the node uniform.
  33510. *
  33511. * @return {Vector3} The value.
  33512. */
  33513. getValue() {
  33514. return this.nodeUniform.value;
  33515. }
  33516. /**
  33517. * Returns the node uniform data type.
  33518. *
  33519. * @return {string} The data type.
  33520. */
  33521. getType() {
  33522. return this.nodeUniform.type;
  33523. }
  33524. }
  33525. /**
  33526. * A special form of Vector4 uniform binding type.
  33527. * It's value is managed by a node object.
  33528. *
  33529. * @private
  33530. * @augments Vector4Uniform
  33531. */
  33532. class Vector4NodeUniform extends Vector4Uniform {
  33533. /**
  33534. * Constructs a new node-based Vector4 uniform.
  33535. *
  33536. * @param {NodeUniform} nodeUniform - The node uniform.
  33537. */
  33538. constructor( nodeUniform ) {
  33539. super( nodeUniform.name, nodeUniform.value );
  33540. /**
  33541. * The node uniform.
  33542. *
  33543. * @type {NodeUniform}
  33544. */
  33545. this.nodeUniform = nodeUniform;
  33546. }
  33547. /**
  33548. * Overwritten to return the value of the node uniform.
  33549. *
  33550. * @return {Vector4} The value.
  33551. */
  33552. getValue() {
  33553. return this.nodeUniform.value;
  33554. }
  33555. /**
  33556. * Returns the node uniform data type.
  33557. *
  33558. * @return {string} The data type.
  33559. */
  33560. getType() {
  33561. return this.nodeUniform.type;
  33562. }
  33563. }
  33564. /**
  33565. * A special form of Color uniform binding type.
  33566. * It's value is managed by a node object.
  33567. *
  33568. * @private
  33569. * @augments ColorUniform
  33570. */
  33571. class ColorNodeUniform extends ColorUniform {
  33572. /**
  33573. * Constructs a new node-based Color uniform.
  33574. *
  33575. * @param {NodeUniform} nodeUniform - The node uniform.
  33576. */
  33577. constructor( nodeUniform ) {
  33578. super( nodeUniform.name, nodeUniform.value );
  33579. /**
  33580. * The node uniform.
  33581. *
  33582. * @type {NodeUniform}
  33583. */
  33584. this.nodeUniform = nodeUniform;
  33585. }
  33586. /**
  33587. * Overwritten to return the value of the node uniform.
  33588. *
  33589. * @return {Color} The value.
  33590. */
  33591. getValue() {
  33592. return this.nodeUniform.value;
  33593. }
  33594. /**
  33595. * Returns the node uniform data type.
  33596. *
  33597. * @return {string} The data type.
  33598. */
  33599. getType() {
  33600. return this.nodeUniform.type;
  33601. }
  33602. }
  33603. /**
  33604. * A special form of Matrix2 uniform binding type.
  33605. * It's value is managed by a node object.
  33606. *
  33607. * @private
  33608. * @augments Matrix2Uniform
  33609. */
  33610. class Matrix2NodeUniform extends Matrix2Uniform {
  33611. /**
  33612. * Constructs a new node-based Matrix2 uniform.
  33613. *
  33614. * @param {NodeUniform} nodeUniform - The node uniform.
  33615. */
  33616. constructor( nodeUniform ) {
  33617. super( nodeUniform.name, nodeUniform.value );
  33618. /**
  33619. * The node uniform.
  33620. *
  33621. * @type {NodeUniform}
  33622. */
  33623. this.nodeUniform = nodeUniform;
  33624. }
  33625. /**
  33626. * Overwritten to return the value of the node uniform.
  33627. *
  33628. * @return {Matrix2} The value.
  33629. */
  33630. getValue() {
  33631. return this.nodeUniform.value;
  33632. }
  33633. /**
  33634. * Returns the node uniform data type.
  33635. *
  33636. * @return {string} The data type.
  33637. */
  33638. getType() {
  33639. return this.nodeUniform.type;
  33640. }
  33641. }
  33642. /**
  33643. * A special form of Matrix3 uniform binding type.
  33644. * It's value is managed by a node object.
  33645. *
  33646. * @private
  33647. * @augments Matrix3Uniform
  33648. */
  33649. class Matrix3NodeUniform extends Matrix3Uniform {
  33650. /**
  33651. * Constructs a new node-based Matrix3 uniform.
  33652. *
  33653. * @param {NodeUniform} nodeUniform - The node uniform.
  33654. */
  33655. constructor( nodeUniform ) {
  33656. super( nodeUniform.name, nodeUniform.value );
  33657. /**
  33658. * The node uniform.
  33659. *
  33660. * @type {NodeUniform}
  33661. */
  33662. this.nodeUniform = nodeUniform;
  33663. }
  33664. /**
  33665. * Overwritten to return the value of the node uniform.
  33666. *
  33667. * @return {Matrix3} The value.
  33668. */
  33669. getValue() {
  33670. return this.nodeUniform.value;
  33671. }
  33672. /**
  33673. * Returns the node uniform data type.
  33674. *
  33675. * @return {string} The data type.
  33676. */
  33677. getType() {
  33678. return this.nodeUniform.type;
  33679. }
  33680. }
  33681. /**
  33682. * A special form of Matrix4 uniform binding type.
  33683. * It's value is managed by a node object.
  33684. *
  33685. * @private
  33686. * @augments Matrix4Uniform
  33687. */
  33688. class Matrix4NodeUniform extends Matrix4Uniform {
  33689. /**
  33690. * Constructs a new node-based Matrix4 uniform.
  33691. *
  33692. * @param {NodeUniform} nodeUniform - The node uniform.
  33693. */
  33694. constructor( nodeUniform ) {
  33695. super( nodeUniform.name, nodeUniform.value );
  33696. /**
  33697. * The node uniform.
  33698. *
  33699. * @type {NodeUniform}
  33700. */
  33701. this.nodeUniform = nodeUniform;
  33702. }
  33703. /**
  33704. * Overwritten to return the value of the node uniform.
  33705. *
  33706. * @return {Matrix4} The value.
  33707. */
  33708. getValue() {
  33709. return this.nodeUniform.value;
  33710. }
  33711. /**
  33712. * Returns the node uniform data type.
  33713. *
  33714. * @return {string} The data type.
  33715. */
  33716. getType() {
  33717. return this.nodeUniform.type;
  33718. }
  33719. }
  33720. const rendererCache = new WeakMap();
  33721. const typeFromArray = new Map( [
  33722. [ Int8Array, 'int' ],
  33723. [ Int16Array, 'int' ],
  33724. [ Int32Array, 'int' ],
  33725. [ Uint8Array, 'uint' ],
  33726. [ Uint16Array, 'uint' ],
  33727. [ Uint32Array, 'uint' ],
  33728. [ Float32Array, 'float' ]
  33729. ] );
  33730. const toFloat = ( value ) => {
  33731. if ( /e/g.test( value ) ) {
  33732. return String( value ).replace( /\+/g, '' );
  33733. } else {
  33734. value = Number( value );
  33735. return value + ( value % 1 ? '' : '.0' );
  33736. }
  33737. };
  33738. /**
  33739. * Base class for builders which generate a shader program based
  33740. * on a 3D object and its node material definition.
  33741. */
  33742. class NodeBuilder {
  33743. /**
  33744. * Constructs a new node builder.
  33745. *
  33746. * @param {Object3D} object - The 3D object.
  33747. * @param {Renderer} renderer - The current renderer.
  33748. * @param {NodeParser} parser - A reference to a node parser.
  33749. */
  33750. constructor( object, renderer, parser ) {
  33751. /**
  33752. * The 3D object.
  33753. *
  33754. * @type {Object3D}
  33755. */
  33756. this.object = object;
  33757. /**
  33758. * The material of the 3D object.
  33759. *
  33760. * @type {?Material}
  33761. */
  33762. this.material = ( object && object.material ) || null;
  33763. /**
  33764. * The geometry of the 3D object.
  33765. *
  33766. * @type {?BufferGeometry}
  33767. */
  33768. this.geometry = ( object && object.geometry ) || null;
  33769. /**
  33770. * The current renderer.
  33771. *
  33772. * @type {Renderer}
  33773. */
  33774. this.renderer = renderer;
  33775. /**
  33776. * A reference to a node parser.
  33777. *
  33778. * @type {NodeParser}
  33779. */
  33780. this.parser = parser;
  33781. /**
  33782. * The scene the 3D object belongs to.
  33783. *
  33784. * @type {?Scene}
  33785. * @default null
  33786. */
  33787. this.scene = null;
  33788. /**
  33789. * The camera the 3D object is rendered with.
  33790. *
  33791. * @type {?Camera}
  33792. * @default null
  33793. */
  33794. this.camera = null;
  33795. /**
  33796. * A list of all nodes the builder is processing
  33797. * for this 3D object.
  33798. *
  33799. * @type {Array<Node>}
  33800. */
  33801. this.nodes = [];
  33802. /**
  33803. * A list of all sequential nodes.
  33804. *
  33805. * @type {Array<Node>}
  33806. */
  33807. this.sequentialNodes = [];
  33808. /**
  33809. * A list of all nodes which {@link Node#update} method should be executed.
  33810. *
  33811. * @type {Array<Node>}
  33812. */
  33813. this.updateNodes = [];
  33814. /**
  33815. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  33816. *
  33817. * @type {Array<Node>}
  33818. */
  33819. this.updateBeforeNodes = [];
  33820. /**
  33821. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  33822. *
  33823. * @type {Array<Node>}
  33824. */
  33825. this.updateAfterNodes = [];
  33826. /**
  33827. * A dictionary that assigns each node to a unique hash.
  33828. *
  33829. * @type {Object<number,Node>}
  33830. */
  33831. this.hashNodes = {};
  33832. /**
  33833. * A reference to a node material observer.
  33834. *
  33835. * @type {?NodeMaterialObserver}
  33836. * @default null
  33837. */
  33838. this.observer = null;
  33839. /**
  33840. * A reference to the current lights node.
  33841. *
  33842. * @type {?LightsNode}
  33843. * @default null
  33844. */
  33845. this.lightsNode = null;
  33846. /**
  33847. * A reference to the current environment node.
  33848. *
  33849. * @type {?Node}
  33850. * @default null
  33851. */
  33852. this.environmentNode = null;
  33853. /**
  33854. * A reference to the current fog node.
  33855. *
  33856. * @type {?Node}
  33857. * @default null
  33858. */
  33859. this.fogNode = null;
  33860. /**
  33861. * The current clipping context.
  33862. *
  33863. * @type {?ClippingContext}
  33864. */
  33865. this.clippingContext = null;
  33866. /**
  33867. * The generated vertex shader.
  33868. *
  33869. * @type {?string}
  33870. */
  33871. this.vertexShader = null;
  33872. /**
  33873. * The generated fragment shader.
  33874. *
  33875. * @type {?string}
  33876. */
  33877. this.fragmentShader = null;
  33878. /**
  33879. * The generated compute shader.
  33880. *
  33881. * @type {?string}
  33882. */
  33883. this.computeShader = null;
  33884. /**
  33885. * Nodes used in the primary flow of code generation.
  33886. *
  33887. * @type {Object<string,Array<Node>>}
  33888. */
  33889. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  33890. /**
  33891. * Nodes code from `.flowNodes`.
  33892. *
  33893. * @type {Object<string,string>}
  33894. */
  33895. this.flowCode = { vertex: '', fragment: '', compute: '' };
  33896. /**
  33897. * This dictionary holds the node uniforms of the builder.
  33898. * The uniforms are maintained in an array for each shader stage.
  33899. *
  33900. * @type {Object}
  33901. */
  33902. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  33903. /**
  33904. * This dictionary holds the output structs of the builder.
  33905. * The structs are maintained in an array for each shader stage.
  33906. *
  33907. * @type {Object}
  33908. */
  33909. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  33910. /**
  33911. * This dictionary holds the types of the builder.
  33912. *
  33913. * @type {Object}
  33914. */
  33915. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  33916. /**
  33917. * This dictionary holds the bindings for each shader stage.
  33918. *
  33919. * @type {Object}
  33920. */
  33921. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  33922. /**
  33923. * This dictionary maintains the binding indices per bind group.
  33924. *
  33925. * @type {Object}
  33926. */
  33927. this.bindingsIndexes = {};
  33928. /**
  33929. * Reference to the array of bind groups.
  33930. *
  33931. * @type {?Array<BindGroup>}
  33932. */
  33933. this.bindGroups = null;
  33934. /**
  33935. * This array holds the node attributes of this builder
  33936. * created via {@link AttributeNode}.
  33937. *
  33938. * @type {Array<NodeAttribute>}
  33939. */
  33940. this.attributes = [];
  33941. /**
  33942. * This array holds the node attributes of this builder
  33943. * created via {@link BufferAttributeNode}.
  33944. *
  33945. * @type {Array<NodeAttribute>}
  33946. */
  33947. this.bufferAttributes = [];
  33948. /**
  33949. * This array holds the node varyings of this builder.
  33950. *
  33951. * @type {Array<NodeVarying>}
  33952. */
  33953. this.varyings = [];
  33954. /**
  33955. * This dictionary holds the (native) node codes of this builder.
  33956. * The codes are maintained in an array for each shader stage.
  33957. *
  33958. * @type {Object<string,Array<NodeCode>>}
  33959. */
  33960. this.codes = {};
  33961. /**
  33962. * This dictionary holds the node variables of this builder.
  33963. * The variables are maintained in an array for each shader stage.
  33964. * This dictionary is also used to count the number of variables
  33965. * according to their type (const, vars).
  33966. *
  33967. * @type {Object<string,Array<NodeVar>|number>}
  33968. */
  33969. this.vars = {};
  33970. /**
  33971. * This dictionary holds the declarations for each shader stage.
  33972. *
  33973. * @type {Object}
  33974. */
  33975. this.declarations = {};
  33976. /**
  33977. * Current code flow.
  33978. * All code generated in this stack will be stored in `.flow`.
  33979. *
  33980. * @type {{code: string}}
  33981. */
  33982. this.flow = { code: '' };
  33983. /**
  33984. * A chain of nodes.
  33985. * Used to check recursive calls in node-graph.
  33986. *
  33987. * @type {Array<Node>}
  33988. */
  33989. this.chaining = [];
  33990. /**
  33991. * The current stack.
  33992. * This reflects the current process in the code block hierarchy,
  33993. * it is useful to know if the current process is inside a conditional for example.
  33994. *
  33995. * @type {StackNode}
  33996. */
  33997. this.stack = stack();
  33998. /**
  33999. * List of stack nodes.
  34000. * The current stack hierarchy is stored in an array.
  34001. *
  34002. * @type {Array<StackNode>}
  34003. */
  34004. this.stacks = [];
  34005. /**
  34006. * A tab value. Used for shader string generation.
  34007. *
  34008. * @type {string}
  34009. * @default '\t'
  34010. */
  34011. this.tab = '\t';
  34012. /**
  34013. * Reference to the current function node.
  34014. *
  34015. * @type {?FunctionNode}
  34016. * @default null
  34017. */
  34018. this.currentFunctionNode = null;
  34019. /**
  34020. * The builder's context.
  34021. *
  34022. * @type {Object}
  34023. */
  34024. this.context = {
  34025. material: this.material
  34026. };
  34027. /**
  34028. * The builder's cache.
  34029. *
  34030. * @type {NodeCache}
  34031. */
  34032. this.cache = new NodeCache();
  34033. /**
  34034. * Since the {@link NodeBuilder#cache} might be temporarily
  34035. * overwritten by other caches, this member retains the reference
  34036. * to the builder's own cache.
  34037. *
  34038. * @type {NodeCache}
  34039. * @default this.cache
  34040. */
  34041. this.globalCache = this.cache;
  34042. this.flowsData = new WeakMap();
  34043. /**
  34044. * The current shader stage.
  34045. *
  34046. * @type {?('vertex'|'fragment'|'compute'|'any')}
  34047. */
  34048. this.shaderStage = null;
  34049. /**
  34050. * The current build stage.
  34051. *
  34052. * @type {?('setup'|'analyze'|'generate')}
  34053. */
  34054. this.buildStage = null;
  34055. /**
  34056. * The sub-build layers.
  34057. *
  34058. * @type {Array<SubBuildNode>}
  34059. * @default []
  34060. */
  34061. this.subBuildLayers = [];
  34062. /**
  34063. * The current stack of nodes.
  34064. *
  34065. * @type {?StackNode}
  34066. * @default null
  34067. */
  34068. this.currentStack = null;
  34069. /**
  34070. * The current sub-build TSL function(Fn).
  34071. *
  34072. * @type {?string}
  34073. * @default null
  34074. */
  34075. this.subBuildFn = null;
  34076. }
  34077. /**
  34078. * Returns the bind groups of the current renderer.
  34079. *
  34080. * @return {ChainMap} The cache.
  34081. */
  34082. getBindGroupsCache() {
  34083. let bindGroupsCache = rendererCache.get( this.renderer );
  34084. if ( bindGroupsCache === undefined ) {
  34085. bindGroupsCache = new ChainMap();
  34086. rendererCache.set( this.renderer, bindGroupsCache );
  34087. }
  34088. return bindGroupsCache;
  34089. }
  34090. /**
  34091. * Factory method for creating an instance of {@link RenderTarget} with the given
  34092. * dimensions and options.
  34093. *
  34094. * @param {number} width - The width of the render target.
  34095. * @param {number} height - The height of the render target.
  34096. * @param {Object} options - The options of the render target.
  34097. * @return {RenderTarget} The render target.
  34098. */
  34099. createRenderTarget( width, height, options ) {
  34100. return new RenderTarget( width, height, options );
  34101. }
  34102. /**
  34103. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  34104. * dimensions and options.
  34105. *
  34106. * @param {number} size - The size of the cube render target.
  34107. * @param {Object} options - The options of the cube render target.
  34108. * @return {CubeRenderTarget} The cube render target.
  34109. */
  34110. createCubeRenderTarget( size, options ) {
  34111. return new CubeRenderTarget( size, options );
  34112. }
  34113. /**
  34114. * Whether the given node is included in the internal array of nodes or not.
  34115. *
  34116. * @param {Node} node - The node to test.
  34117. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  34118. */
  34119. includes( node ) {
  34120. return this.nodes.includes( node );
  34121. }
  34122. /**
  34123. * Returns the output struct name which is required by
  34124. * {@link OutputStructNode}.
  34125. *
  34126. * @abstract
  34127. * @return {string} The name of the output struct.
  34128. */
  34129. getOutputStructName() {}
  34130. /**
  34131. * Returns a bind group for the given group name and binding.
  34132. *
  34133. * @private
  34134. * @param {string} groupName - The group name.
  34135. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  34136. * @return {BindGroup} The bind group
  34137. */
  34138. _getBindGroup( groupName, bindings ) {
  34139. const bindGroupsCache = this.getBindGroupsCache();
  34140. //
  34141. const bindingsArray = [];
  34142. let sharedGroup = true;
  34143. for ( const binding of bindings ) {
  34144. bindingsArray.push( binding );
  34145. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  34146. }
  34147. //
  34148. let bindGroup;
  34149. if ( sharedGroup ) {
  34150. bindGroup = bindGroupsCache.get( bindingsArray );
  34151. if ( bindGroup === undefined ) {
  34152. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34153. bindGroupsCache.set( bindingsArray, bindGroup );
  34154. }
  34155. } else {
  34156. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  34157. }
  34158. return bindGroup;
  34159. }
  34160. /**
  34161. * Returns an array of node uniform groups for the given group name and shader stage.
  34162. *
  34163. * @param {string} groupName - The group name.
  34164. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34165. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  34166. */
  34167. getBindGroupArray( groupName, shaderStage ) {
  34168. const bindings = this.bindings[ shaderStage ];
  34169. let bindGroup = bindings[ groupName ];
  34170. if ( bindGroup === undefined ) {
  34171. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  34172. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  34173. }
  34174. bindings[ groupName ] = bindGroup = [];
  34175. }
  34176. return bindGroup;
  34177. }
  34178. /**
  34179. * Returns a list bindings of all shader stages separated by groups.
  34180. *
  34181. * @return {Array<BindGroup>} The list of bindings.
  34182. */
  34183. getBindings() {
  34184. let bindingsGroups = this.bindGroups;
  34185. if ( bindingsGroups === null ) {
  34186. const groups = {};
  34187. const bindings = this.bindings;
  34188. for ( const shaderStage of shaderStages ) {
  34189. for ( const groupName in bindings[ shaderStage ] ) {
  34190. const uniforms = bindings[ shaderStage ][ groupName ];
  34191. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  34192. groupUniforms.push( ...uniforms );
  34193. }
  34194. }
  34195. bindingsGroups = [];
  34196. for ( const groupName in groups ) {
  34197. const group = groups[ groupName ];
  34198. const bindingsGroup = this._getBindGroup( groupName, group );
  34199. bindingsGroups.push( bindingsGroup );
  34200. }
  34201. this.bindGroups = bindingsGroups;
  34202. }
  34203. return bindingsGroups;
  34204. }
  34205. /**
  34206. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  34207. */
  34208. sortBindingGroups() {
  34209. const bindingsGroups = this.getBindings();
  34210. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  34211. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  34212. const bindingGroup = bindingsGroups[ i ];
  34213. this.bindingsIndexes[ bindingGroup.name ].group = i;
  34214. bindingGroup.index = i;
  34215. }
  34216. }
  34217. /**
  34218. * The builder maintains each node in a hash-based dictionary.
  34219. * This method sets the given node (value) with the given hash (key) into this dictionary.
  34220. *
  34221. * @param {Node} node - The node to add.
  34222. * @param {number} hash - The hash of the node.
  34223. */
  34224. setHashNode( node, hash ) {
  34225. this.hashNodes[ hash ] = node;
  34226. }
  34227. /**
  34228. * Adds a node to this builder.
  34229. *
  34230. * @param {Node} node - The node to add.
  34231. */
  34232. addNode( node ) {
  34233. if ( this.nodes.includes( node ) === false ) {
  34234. this.nodes.push( node );
  34235. this.setHashNode( node, node.getHash( this ) );
  34236. }
  34237. }
  34238. /**
  34239. * It is used to add Nodes that will be used as FRAME and RENDER events,
  34240. * and need to follow a certain sequence in the calls to work correctly.
  34241. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  34242. *
  34243. * @param {Node} node - The node to add.
  34244. */
  34245. addSequentialNode( node ) {
  34246. if ( this.sequentialNodes.includes( node ) === false ) {
  34247. this.sequentialNodes.push( node );
  34248. }
  34249. }
  34250. /**
  34251. * Checks the update types of nodes
  34252. */
  34253. buildUpdateNodes() {
  34254. for ( const node of this.nodes ) {
  34255. const updateType = node.getUpdateType();
  34256. if ( updateType !== NodeUpdateType.NONE ) {
  34257. this.updateNodes.push( node );
  34258. }
  34259. }
  34260. for ( const node of this.sequentialNodes ) {
  34261. const updateBeforeType = node.getUpdateBeforeType();
  34262. const updateAfterType = node.getUpdateAfterType();
  34263. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  34264. this.updateBeforeNodes.push( node );
  34265. }
  34266. if ( updateAfterType !== NodeUpdateType.NONE ) {
  34267. this.updateAfterNodes.push( node );
  34268. }
  34269. }
  34270. }
  34271. /**
  34272. * A reference the current node which is the
  34273. * last node in the chain of nodes.
  34274. *
  34275. * @type {Node}
  34276. */
  34277. get currentNode() {
  34278. return this.chaining[ this.chaining.length - 1 ];
  34279. }
  34280. /**
  34281. * Whether the given texture is filtered or not.
  34282. *
  34283. * @param {Texture} texture - The texture to check.
  34284. * @return {boolean} Whether the given texture is filtered or not.
  34285. */
  34286. isFilteredTexture( texture ) {
  34287. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  34288. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  34289. }
  34290. /**
  34291. * Adds the given node to the internal node chain.
  34292. * This is used to check recursive calls in node-graph.
  34293. *
  34294. * @param {Node} node - The node to add.
  34295. */
  34296. addChain( node ) {
  34297. /*
  34298. if ( this.chaining.indexOf( node ) !== - 1 ) {
  34299. warn( 'Recursive node: ', node );
  34300. }
  34301. */
  34302. this.chaining.push( node );
  34303. }
  34304. /**
  34305. * Removes the given node from the internal node chain.
  34306. *
  34307. * @param {Node} node - The node to remove.
  34308. */
  34309. removeChain( node ) {
  34310. const lastChain = this.chaining.pop();
  34311. if ( lastChain !== node ) {
  34312. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  34313. }
  34314. }
  34315. /**
  34316. * Returns the native shader method name for a given generic name. E.g.
  34317. * the method name `textureDimensions` matches the WGSL name but must be
  34318. * resolved to `textureSize` in GLSL.
  34319. *
  34320. * @abstract
  34321. * @param {string} method - The method name to resolve.
  34322. * @return {string} The resolved method name.
  34323. */
  34324. getMethod( method ) {
  34325. return method;
  34326. }
  34327. /**
  34328. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  34329. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  34330. *
  34331. * @abstract
  34332. * @param {string} condSnippet - The condition determining which expression gets resolved.
  34333. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  34334. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  34335. * @return {string} The resolved method name.
  34336. */
  34337. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  34338. return null;
  34339. }
  34340. /**
  34341. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  34342. *
  34343. * @param {number} hash - The hash of the node.
  34344. * @return {Node} The found node.
  34345. */
  34346. getNodeFromHash( hash ) {
  34347. return this.hashNodes[ hash ];
  34348. }
  34349. /**
  34350. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  34351. *
  34352. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  34353. * @param {Node} node - The node to add.
  34354. * @return {Node} The node.
  34355. */
  34356. addFlow( shaderStage, node ) {
  34357. this.flowNodes[ shaderStage ].push( node );
  34358. return node;
  34359. }
  34360. /**
  34361. * Sets builder's context.
  34362. *
  34363. * @param {Object} context - The context to set.
  34364. */
  34365. setContext( context ) {
  34366. this.context = context;
  34367. }
  34368. /**
  34369. * Returns the builder's current context.
  34370. *
  34371. * @return {Object} The builder's current context.
  34372. */
  34373. getContext() {
  34374. return this.context;
  34375. }
  34376. /**
  34377. * Gets a context used in shader construction that can be shared across different materials.
  34378. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  34379. *
  34380. * @return {Object} The builder's current context without material.
  34381. */
  34382. getSharedContext() {
  34383. ({ ...this.context });
  34384. return this.context;
  34385. }
  34386. /**
  34387. * Sets builder's cache.
  34388. *
  34389. * @param {NodeCache} cache - The cache to set.
  34390. */
  34391. setCache( cache ) {
  34392. this.cache = cache;
  34393. }
  34394. /**
  34395. * Returns the builder's current cache.
  34396. *
  34397. * @return {NodeCache} The builder's current cache.
  34398. */
  34399. getCache() {
  34400. return this.cache;
  34401. }
  34402. /**
  34403. * Returns a cache for the given node.
  34404. *
  34405. * @param {Node} node - The node.
  34406. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  34407. * @return {NodeCache} The cache.
  34408. */
  34409. getCacheFromNode( node, parent = true ) {
  34410. const data = this.getDataFromNode( node );
  34411. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  34412. return data.cache;
  34413. }
  34414. /**
  34415. * Whether the requested feature is available or not.
  34416. *
  34417. * @abstract
  34418. * @param {string} name - The requested feature.
  34419. * @return {boolean} Whether the requested feature is supported or not.
  34420. */
  34421. isAvailable( /*name*/ ) {
  34422. return false;
  34423. }
  34424. /**
  34425. * Returns the vertexIndex input variable as a native shader string.
  34426. *
  34427. * @abstract
  34428. * @return {string} The instanceIndex shader string.
  34429. */
  34430. getVertexIndex() {
  34431. warn( 'Abstract function.' );
  34432. }
  34433. /**
  34434. * Contextually returns either the vertex stage instance index builtin
  34435. * or the linearized index of an compute invocation within a grid of workgroups.
  34436. *
  34437. * @abstract
  34438. * @return {string} The instanceIndex shader string.
  34439. */
  34440. getInstanceIndex() {
  34441. warn( 'Abstract function.' );
  34442. }
  34443. /**
  34444. * Returns the drawIndex input variable as a native shader string.
  34445. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  34446. *
  34447. * @abstract
  34448. * @return {?string} The drawIndex shader string.
  34449. */
  34450. getDrawIndex() {
  34451. warn( 'Abstract function.' );
  34452. }
  34453. /**
  34454. * Returns the frontFacing input variable as a native shader string.
  34455. *
  34456. * @abstract
  34457. * @return {string} The frontFacing shader string.
  34458. */
  34459. getFrontFacing() {
  34460. warn( 'Abstract function.' );
  34461. }
  34462. /**
  34463. * Returns the fragCoord input variable as a native shader string.
  34464. *
  34465. * @abstract
  34466. * @return {string} The fragCoord shader string.
  34467. */
  34468. getFragCoord() {
  34469. warn( 'Abstract function.' );
  34470. }
  34471. /**
  34472. * Whether to flip texture data along its vertical axis or not. WebGL needs
  34473. * this method evaluate to `true`, WebGPU to `false`.
  34474. *
  34475. * @abstract
  34476. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  34477. */
  34478. isFlipY() {
  34479. return false;
  34480. }
  34481. /**
  34482. * Calling this method increases the usage count for the given node by one.
  34483. *
  34484. * @param {Node} node - The node to increase the usage count for.
  34485. * @return {number} The updated usage count.
  34486. */
  34487. increaseUsage( node ) {
  34488. const nodeData = this.getDataFromNode( node );
  34489. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  34490. return nodeData.usageCount;
  34491. }
  34492. /**
  34493. * Generates a texture sample shader string for the given texture data.
  34494. *
  34495. * @abstract
  34496. * @param {Texture} texture - The texture.
  34497. * @param {string} textureProperty - The texture property name.
  34498. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34499. * @return {string} The generated shader string.
  34500. */
  34501. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  34502. warn( 'Abstract function.' );
  34503. }
  34504. /**
  34505. * Generates a texture LOD shader string for the given texture data.
  34506. *
  34507. * @abstract
  34508. * @param {Texture} texture - The texture.
  34509. * @param {string} textureProperty - The texture property name.
  34510. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34511. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  34512. * @param {string} levelSnippet - Snippet defining the mip level.
  34513. * @return {string} The generated shader string.
  34514. */
  34515. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  34516. warn( 'Abstract function.' );
  34517. }
  34518. /**
  34519. * Generates the array declaration string.
  34520. *
  34521. * @param {string} type - The type.
  34522. * @param {?number} [count] - The count.
  34523. * @return {string} The generated value as a shader string.
  34524. */
  34525. generateArrayDeclaration( type, count ) {
  34526. return this.getType( type ) + '[ ' + count + ' ]';
  34527. }
  34528. /**
  34529. * Generates the array shader string for the given type and value.
  34530. *
  34531. * @param {string} type - The type.
  34532. * @param {?number} [count] - The count.
  34533. * @param {?Array<Node>} [values=null] - The default values.
  34534. * @return {string} The generated value as a shader string.
  34535. */
  34536. generateArray( type, count, values = null ) {
  34537. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  34538. for ( let i = 0; i < count; i ++ ) {
  34539. const value = values ? values[ i ] : null;
  34540. if ( value !== null ) {
  34541. snippet += value.build( this, type );
  34542. } else {
  34543. snippet += this.generateConst( type );
  34544. }
  34545. if ( i < count - 1 ) snippet += ', ';
  34546. }
  34547. snippet += ' )';
  34548. return snippet;
  34549. }
  34550. /**
  34551. * Generates the struct shader string.
  34552. *
  34553. * @param {string} type - The type.
  34554. * @param {Array<Object>} [membersLayout] - The count.
  34555. * @param {?Array<Node>} [values=null] - The default values.
  34556. * @return {string} The generated value as a shader string.
  34557. */
  34558. generateStruct( type, membersLayout, values = null ) {
  34559. const snippets = [];
  34560. for ( const member of membersLayout ) {
  34561. const { name, type } = member;
  34562. if ( values && values[ name ] && values[ name ].isNode ) {
  34563. snippets.push( values[ name ].build( this, type ) );
  34564. } else {
  34565. snippets.push( this.generateConst( type ) );
  34566. }
  34567. }
  34568. return type + '( ' + snippets.join( ', ' ) + ' )';
  34569. }
  34570. /**
  34571. * Generates the shader string for the given type and value.
  34572. *
  34573. * @param {string} type - The type.
  34574. * @param {?any} [value=null] - The value.
  34575. * @return {string} The generated value as a shader string.
  34576. */
  34577. generateConst( type, value = null ) {
  34578. if ( value === null ) {
  34579. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  34580. else if ( type === 'bool' ) value = false;
  34581. else if ( type === 'color' ) value = new Color();
  34582. else if ( type === 'vec2' ) value = new Vector2();
  34583. else if ( type === 'vec3' ) value = new Vector3();
  34584. else if ( type === 'vec4' ) value = new Vector4();
  34585. }
  34586. if ( type === 'float' ) return toFloat( value );
  34587. if ( type === 'int' ) return `${ Math.round( value ) }`;
  34588. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  34589. if ( type === 'bool' ) return value ? 'true' : 'false';
  34590. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  34591. const typeLength = this.getTypeLength( type );
  34592. const componentType = this.getComponentType( type );
  34593. const generateConst = value => this.generateConst( componentType, value );
  34594. if ( typeLength === 2 ) {
  34595. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  34596. } else if ( typeLength === 3 ) {
  34597. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  34598. } else if ( typeLength === 4 && type !== 'mat2' ) {
  34599. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  34600. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  34601. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  34602. } else if ( typeLength > 4 ) {
  34603. return `${ this.getType( type ) }()`;
  34604. }
  34605. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  34606. }
  34607. /**
  34608. * It might be necessary to convert certain data types to different ones
  34609. * so this method can be used to hide the conversion.
  34610. *
  34611. * @param {string} type - The type.
  34612. * @return {string} The updated type.
  34613. */
  34614. getType( type ) {
  34615. if ( type === 'color' ) return 'vec3';
  34616. return type;
  34617. }
  34618. /**
  34619. * Whether the given attribute name is defined in the geometry or not.
  34620. *
  34621. * @param {string} name - The attribute name.
  34622. * @return {boolean} Whether the given attribute name is defined in the geometry.
  34623. */
  34624. hasGeometryAttribute( name ) {
  34625. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  34626. }
  34627. /**
  34628. * Returns a node attribute for the given name and type.
  34629. *
  34630. * @param {string} name - The attribute's name.
  34631. * @param {string} type - The attribute's type.
  34632. * @return {NodeAttribute} The node attribute.
  34633. */
  34634. getAttribute( name, type ) {
  34635. const attributes = this.attributes;
  34636. // find attribute
  34637. for ( const attribute of attributes ) {
  34638. if ( attribute.name === name ) {
  34639. return attribute;
  34640. }
  34641. }
  34642. // create a new if no exist
  34643. const attribute = new NodeAttribute( name, type );
  34644. this.registerDeclaration( attribute );
  34645. attributes.push( attribute );
  34646. return attribute;
  34647. }
  34648. /**
  34649. * Returns for the given node and shader stage the property name for the shader.
  34650. *
  34651. * @param {Node} node - The node.
  34652. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34653. * @return {string} The property name.
  34654. */
  34655. getPropertyName( node/*, shaderStage*/ ) {
  34656. return node.name;
  34657. }
  34658. /**
  34659. * Whether the given type is a vector type or not.
  34660. *
  34661. * @param {string} type - The type to check.
  34662. * @return {boolean} Whether the given type is a vector type or not.
  34663. */
  34664. isVector( type ) {
  34665. return /vec\d/.test( type );
  34666. }
  34667. /**
  34668. * Whether the given type is a matrix type or not.
  34669. *
  34670. * @param {string} type - The type to check.
  34671. * @return {boolean} Whether the given type is a matrix type or not.
  34672. */
  34673. isMatrix( type ) {
  34674. return /mat\d/.test( type );
  34675. }
  34676. /**
  34677. * Whether the given type is a reference type or not.
  34678. *
  34679. * @param {string} type - The type to check.
  34680. * @return {boolean} Whether the given type is a reference type or not.
  34681. */
  34682. isReference( type ) {
  34683. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  34684. }
  34685. /**
  34686. * Checks if the given texture requires a manual conversion to the working color space.
  34687. *
  34688. * @abstract
  34689. * @param {Texture} texture - The texture to check.
  34690. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  34691. */
  34692. needsToWorkingColorSpace( /*texture*/ ) {
  34693. return false;
  34694. }
  34695. /**
  34696. * Returns the component type of a given texture.
  34697. *
  34698. * @param {Texture} texture - The texture.
  34699. * @return {string} The component type.
  34700. */
  34701. getComponentTypeFromTexture( texture ) {
  34702. const type = texture.type;
  34703. if ( texture.isDataTexture ) {
  34704. if ( type === IntType ) return 'int';
  34705. if ( type === UnsignedIntType ) return 'uint';
  34706. }
  34707. return 'float';
  34708. }
  34709. /**
  34710. * Returns the element type for a given type.
  34711. *
  34712. * @param {string} type - The type.
  34713. * @return {string} The element type.
  34714. */
  34715. getElementType( type ) {
  34716. if ( type === 'mat2' ) return 'vec2';
  34717. if ( type === 'mat3' ) return 'vec3';
  34718. if ( type === 'mat4' ) return 'vec4';
  34719. return this.getComponentType( type );
  34720. }
  34721. /**
  34722. * Returns the component type for a given type.
  34723. *
  34724. * @param {string} type - The type.
  34725. * @return {string} The component type.
  34726. */
  34727. getComponentType( type ) {
  34728. type = this.getVectorType( type );
  34729. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  34730. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  34731. if ( componentType === null ) return null;
  34732. if ( componentType[ 1 ] === 'b' ) return 'bool';
  34733. if ( componentType[ 1 ] === 'i' ) return 'int';
  34734. if ( componentType[ 1 ] === 'u' ) return 'uint';
  34735. return 'float';
  34736. }
  34737. /**
  34738. * Returns the vector type for a given type.
  34739. *
  34740. * @param {string} type - The type.
  34741. * @return {string} The vector type.
  34742. */
  34743. getVectorType( type ) {
  34744. if ( type === 'color' ) return 'vec3';
  34745. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  34746. return type;
  34747. }
  34748. /**
  34749. * Returns the data type for the given the length and component type.
  34750. *
  34751. * @param {number} length - The length.
  34752. * @param {string} [componentType='float'] - The component type.
  34753. * @return {string} The type.
  34754. */
  34755. getTypeFromLength( length, componentType = 'float' ) {
  34756. if ( length === 1 ) return componentType;
  34757. let baseType = getTypeFromLength( length );
  34758. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  34759. // fix edge case for mat2x2 being same size as vec4
  34760. if ( /mat2/.test( componentType ) === true ) {
  34761. baseType = baseType.replace( 'vec', 'mat' );
  34762. }
  34763. return prefix + baseType;
  34764. }
  34765. /**
  34766. * Returns the type for a given typed array.
  34767. *
  34768. * @param {TypedArray} array - The typed array.
  34769. * @return {string} The type.
  34770. */
  34771. getTypeFromArray( array ) {
  34772. return typeFromArray.get( array.constructor );
  34773. }
  34774. /**
  34775. * Returns the type is an integer type.
  34776. *
  34777. * @param {string} type - The type.
  34778. * @return {boolean} Whether the type is an integer type or not.
  34779. */
  34780. isInteger( type ) {
  34781. return /int|uint|(i|u)vec/.test( type );
  34782. }
  34783. /**
  34784. * Returns the type for a given buffer attribute.
  34785. *
  34786. * @param {BufferAttribute} attribute - The buffer attribute.
  34787. * @return {string} The type.
  34788. */
  34789. getTypeFromAttribute( attribute ) {
  34790. let dataAttribute = attribute;
  34791. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  34792. const array = dataAttribute.array;
  34793. const itemSize = attribute.itemSize;
  34794. const normalized = attribute.normalized;
  34795. let arrayType;
  34796. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  34797. arrayType = this.getTypeFromArray( array );
  34798. }
  34799. return this.getTypeFromLength( itemSize, arrayType );
  34800. }
  34801. /**
  34802. * Returns the length for the given data type.
  34803. *
  34804. * @param {string} type - The data type.
  34805. * @return {number} The length.
  34806. */
  34807. getTypeLength( type ) {
  34808. const vecType = this.getVectorType( type );
  34809. const vecNum = /vec([2-4])/.exec( vecType );
  34810. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  34811. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  34812. if ( /mat2/.test( type ) === true ) return 4;
  34813. if ( /mat3/.test( type ) === true ) return 9;
  34814. if ( /mat4/.test( type ) === true ) return 16;
  34815. return 0;
  34816. }
  34817. /**
  34818. * Returns the vector type for a given matrix type.
  34819. *
  34820. * @param {string} type - The matrix type.
  34821. * @return {string} The vector type.
  34822. */
  34823. getVectorFromMatrix( type ) {
  34824. return type.replace( 'mat', 'vec' );
  34825. }
  34826. /**
  34827. * For a given type this method changes the component type to the
  34828. * given value. E.g. `vec4` should be changed to the new component type
  34829. * `uint` which results in `uvec4`.
  34830. *
  34831. * @param {string} type - The type.
  34832. * @param {string} newComponentType - The new component type.
  34833. * @return {string} The new type.
  34834. */
  34835. changeComponentType( type, newComponentType ) {
  34836. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  34837. }
  34838. /**
  34839. * Returns the integer type pendant for the given type.
  34840. *
  34841. * @param {string} type - The type.
  34842. * @return {string} The integer type.
  34843. */
  34844. getIntegerType( type ) {
  34845. const componentType = this.getComponentType( type );
  34846. if ( componentType === 'int' || componentType === 'uint' ) return type;
  34847. return this.changeComponentType( type, 'int' );
  34848. }
  34849. /**
  34850. * Adds a stack node to the internal stack.
  34851. *
  34852. * @return {StackNode} The added stack node.
  34853. */
  34854. addStack() {
  34855. this.stack = stack( this.stack );
  34856. const previousStack = getCurrentStack();
  34857. this.stacks.push( previousStack );
  34858. setCurrentStack( this.stack );
  34859. return this.stack;
  34860. }
  34861. /**
  34862. * Removes the last stack node from the internal stack.
  34863. *
  34864. * @return {StackNode} The removed stack node.
  34865. */
  34866. removeStack() {
  34867. const lastStack = this.stack;
  34868. this.stack = lastStack.parent;
  34869. setCurrentStack( this.stacks.pop() );
  34870. return lastStack;
  34871. }
  34872. /**
  34873. * The builder maintains (cached) data for each node during the building process. This method
  34874. * can be used to get these data for a specific shader stage and cache.
  34875. *
  34876. * @param {Node} node - The node to get the data for.
  34877. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34878. * @param {?NodeCache} cache - An optional cache.
  34879. * @return {Object} The node data.
  34880. */
  34881. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  34882. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  34883. let nodeData = cache.getData( node );
  34884. if ( nodeData === undefined ) {
  34885. nodeData = {};
  34886. cache.setData( node, nodeData );
  34887. }
  34888. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  34889. //
  34890. let data = nodeData[ shaderStage ];
  34891. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  34892. const subBuild = this.getClosestSubBuild( subBuilds );
  34893. if ( subBuild ) {
  34894. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  34895. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  34896. data.subBuilds = subBuilds;
  34897. }
  34898. return data;
  34899. }
  34900. /**
  34901. * Returns the properties for the given node and shader stage.
  34902. *
  34903. * @param {Node} node - The node to get the properties for.
  34904. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  34905. * @return {Object} The node properties.
  34906. */
  34907. getNodeProperties( node, shaderStage = 'any' ) {
  34908. const nodeData = this.getDataFromNode( node, shaderStage );
  34909. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  34910. }
  34911. /**
  34912. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  34913. *
  34914. * @param {BufferAttributeNode} node - The buffer attribute node.
  34915. * @param {string} type - The node type.
  34916. * @return {NodeAttribute} The node attribute.
  34917. */
  34918. getBufferAttributeFromNode( node, type ) {
  34919. const nodeData = this.getDataFromNode( node );
  34920. let bufferAttribute = nodeData.bufferAttribute;
  34921. if ( bufferAttribute === undefined ) {
  34922. const index = this.uniforms.index ++;
  34923. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  34924. this.bufferAttributes.push( bufferAttribute );
  34925. nodeData.bufferAttribute = bufferAttribute;
  34926. }
  34927. return bufferAttribute;
  34928. }
  34929. /**
  34930. * Returns an instance of {@link StructType} for the given struct name and shader stage
  34931. * or null if not found.
  34932. *
  34933. * @param {string} name - The name of the struct.
  34934. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34935. * @return {?StructType} The struct type or null if not found.
  34936. */
  34937. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  34938. return this.types[ shaderStage ][ name ] || null;
  34939. }
  34940. /**
  34941. * Returns an instance of {@link StructType} for the given output struct node.
  34942. *
  34943. * @param {OutputStructNode} node - The output struct node.
  34944. * @param {Array<Object>} membersLayout - The output struct types.
  34945. * @param {?string} [name=null] - The name of the struct.
  34946. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34947. * @return {StructType} The struct type attribute.
  34948. */
  34949. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  34950. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34951. let structType = nodeData.structType;
  34952. if ( structType === undefined ) {
  34953. const index = this.structs.index ++;
  34954. if ( name === null ) name = 'StructType' + index;
  34955. structType = new StructType( name, membersLayout );
  34956. this.structs[ shaderStage ].push( structType );
  34957. this.types[ shaderStage ][ name ] = node;
  34958. nodeData.structType = structType;
  34959. }
  34960. return structType;
  34961. }
  34962. /**
  34963. * Returns an instance of {@link StructType} for the given output struct node.
  34964. *
  34965. * @param {OutputStructNode} node - The output struct node.
  34966. * @param {Array<Object>} membersLayout - The output struct types.
  34967. * @return {StructType} The struct type attribute.
  34968. */
  34969. getOutputStructTypeFromNode( node, membersLayout ) {
  34970. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  34971. structType.output = true;
  34972. return structType;
  34973. }
  34974. /**
  34975. * Returns an instance of {@link NodeUniform} for the given uniform node.
  34976. *
  34977. * @param {UniformNode} node - The uniform node.
  34978. * @param {string} type - The uniform type.
  34979. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34980. * @param {?string} name - The name of the uniform.
  34981. * @return {NodeUniform} The node uniform.
  34982. */
  34983. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  34984. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34985. let nodeUniform = nodeData.uniform;
  34986. if ( nodeUniform === undefined ) {
  34987. const index = this.uniforms.index ++;
  34988. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  34989. this.uniforms[ shaderStage ].push( nodeUniform );
  34990. this.registerDeclaration( nodeUniform );
  34991. nodeData.uniform = nodeUniform;
  34992. }
  34993. return nodeUniform;
  34994. }
  34995. /**
  34996. * Returns an instance of {@link NodeVar} for the given variable node.
  34997. *
  34998. * @param {VarNode} node - The variable node.
  34999. * @param {?string} name - The variable's name.
  35000. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  35001. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35002. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  35003. *
  35004. * @return {NodeVar} The node variable.
  35005. */
  35006. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  35007. const nodeData = this.getDataFromNode( node, shaderStage );
  35008. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  35009. let nodeVar = nodeData[ subBuildVariable ];
  35010. if ( nodeVar === undefined ) {
  35011. const idNS = readOnly ? '_const' : '_var';
  35012. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  35013. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  35014. if ( name === null ) {
  35015. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  35016. this.vars[ idNS ] ++;
  35017. }
  35018. //
  35019. if ( subBuildVariable !== 'variable' ) {
  35020. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35021. }
  35022. //
  35023. const count = node.getArrayCount( this );
  35024. nodeVar = new NodeVar( name, type, readOnly, count );
  35025. if ( ! readOnly ) {
  35026. vars.push( nodeVar );
  35027. }
  35028. this.registerDeclaration( nodeVar );
  35029. nodeData[ subBuildVariable ] = nodeVar;
  35030. }
  35031. return nodeVar;
  35032. }
  35033. /**
  35034. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  35035. *
  35036. * @param {Node} node - The varying node.
  35037. * @return {boolean} Returns true if deterministic.
  35038. */
  35039. isDeterministic( node ) {
  35040. if ( node.isMathNode ) {
  35041. return this.isDeterministic( node.aNode ) &&
  35042. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  35043. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  35044. } else if ( node.isOperatorNode ) {
  35045. return this.isDeterministic( node.aNode ) &&
  35046. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  35047. } else if ( node.isArrayNode ) {
  35048. if ( node.values !== null ) {
  35049. for ( const n of node.values ) {
  35050. if ( ! this.isDeterministic( n ) ) {
  35051. return false;
  35052. }
  35053. }
  35054. }
  35055. return true;
  35056. } else if ( node.isConstNode ) {
  35057. return true;
  35058. }
  35059. return false;
  35060. }
  35061. /**
  35062. * Returns an instance of {@link NodeVarying} for the given varying node.
  35063. *
  35064. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  35065. * @param {?string} name - The varying's name.
  35066. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  35067. * @param {?string} interpolationType - The interpolation type of the varying.
  35068. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  35069. * @return {NodeVar} The node varying.
  35070. */
  35071. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  35072. const nodeData = this.getDataFromNode( node, 'any' );
  35073. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  35074. let nodeVarying = nodeData[ subBuildVarying ];
  35075. if ( nodeVarying === undefined ) {
  35076. const varyings = this.varyings;
  35077. const index = varyings.length;
  35078. if ( name === null ) name = 'nodeVarying' + index;
  35079. //
  35080. if ( subBuildVarying !== 'varying' ) {
  35081. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  35082. }
  35083. //
  35084. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  35085. varyings.push( nodeVarying );
  35086. this.registerDeclaration( nodeVarying );
  35087. nodeData[ subBuildVarying ] = nodeVarying;
  35088. }
  35089. return nodeVarying;
  35090. }
  35091. /**
  35092. * Registers a node declaration in the current shader stage.
  35093. *
  35094. * @param {Object} node - The node to be registered.
  35095. */
  35096. registerDeclaration( node ) {
  35097. const shaderStage = this.shaderStage;
  35098. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  35099. const property = this.getPropertyName( node );
  35100. let index = 1;
  35101. let name = property;
  35102. // Automatically renames the property if the name is already in use.
  35103. while ( declarations[ name ] !== undefined ) {
  35104. name = property + '_' + index ++;
  35105. }
  35106. if ( index > 1 ) {
  35107. node.name = name;
  35108. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  35109. }
  35110. declarations[ name ] = node;
  35111. }
  35112. /**
  35113. * Returns an instance of {@link NodeCode} for the given code node.
  35114. *
  35115. * @param {CodeNode} node - The code node.
  35116. * @param {string} type - The node type.
  35117. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  35118. * @return {NodeCode} The node code.
  35119. */
  35120. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  35121. const nodeData = this.getDataFromNode( node );
  35122. let nodeCode = nodeData.code;
  35123. if ( nodeCode === undefined ) {
  35124. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  35125. const index = codes.length;
  35126. nodeCode = new NodeCode( 'nodeCode' + index, type );
  35127. codes.push( nodeCode );
  35128. nodeData.code = nodeCode;
  35129. }
  35130. return nodeCode;
  35131. }
  35132. /**
  35133. * Adds a code flow based on the code-block hierarchy.
  35134. * This is used so that code-blocks like If,Else create their variables locally if the Node
  35135. * is only used inside one of these conditionals in the current shader stage.
  35136. *
  35137. * @param {Node} node - The node to add.
  35138. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  35139. */
  35140. addFlowCodeHierarchy( node, nodeBlock ) {
  35141. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  35142. let needsFlowCode = true;
  35143. let nodeBlockHierarchy = nodeBlock;
  35144. while ( nodeBlockHierarchy ) {
  35145. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  35146. needsFlowCode = false;
  35147. break;
  35148. }
  35149. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  35150. }
  35151. if ( needsFlowCode ) {
  35152. for ( const flowCode of flowCodes ) {
  35153. this.addLineFlowCode( flowCode );
  35154. }
  35155. }
  35156. }
  35157. /**
  35158. * Add a inline-code to the current flow code-block.
  35159. *
  35160. * @param {Node} node - The node to add.
  35161. * @param {string} code - The code to add.
  35162. * @param {Node} nodeBlock - Current ConditionalNode
  35163. */
  35164. addLineFlowCodeBlock( node, code, nodeBlock ) {
  35165. const nodeData = this.getDataFromNode( node );
  35166. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  35167. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  35168. flowCodes.push( code );
  35169. codeBlock.set( nodeBlock, true );
  35170. }
  35171. /**
  35172. * Add a inline-code to the current flow.
  35173. *
  35174. * @param {string} code - The code to add.
  35175. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  35176. * @return {NodeBuilder} A reference to this node builder.
  35177. */
  35178. addLineFlowCode( code, node = null ) {
  35179. if ( code === '' ) return this;
  35180. if ( node !== null && this.context.nodeBlock ) {
  35181. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  35182. }
  35183. code = this.tab + code;
  35184. if ( ! /;\s*$/.test( code ) ) {
  35185. code = code + ';\n';
  35186. }
  35187. this.flow.code += code;
  35188. return this;
  35189. }
  35190. /**
  35191. * Adds a code to the current code flow.
  35192. *
  35193. * @param {string} code - Shader code.
  35194. * @return {NodeBuilder} A reference to this node builder.
  35195. */
  35196. addFlowCode( code ) {
  35197. this.flow.code += code;
  35198. return this;
  35199. }
  35200. /**
  35201. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  35202. * Typically used in codes with If,Else.
  35203. *
  35204. * @return {NodeBuilder} A reference to this node builder.
  35205. */
  35206. addFlowTab() {
  35207. this.tab += '\t';
  35208. return this;
  35209. }
  35210. /**
  35211. * Removes a tab.
  35212. *
  35213. * @return {NodeBuilder} A reference to this node builder.
  35214. */
  35215. removeFlowTab() {
  35216. this.tab = this.tab.slice( 0, -1 );
  35217. return this;
  35218. }
  35219. /**
  35220. * Gets the current flow data based on a Node.
  35221. *
  35222. * @param {Node} node - Node that the flow was started.
  35223. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35224. * @return {Object} The flow data.
  35225. */
  35226. getFlowData( node/*, shaderStage*/ ) {
  35227. return this.flowsData.get( node );
  35228. }
  35229. /**
  35230. * Executes the node flow based on a root node to generate the final shader code.
  35231. *
  35232. * @param {Node} node - The node to execute.
  35233. * @return {Object} The code flow.
  35234. */
  35235. flowNode( node ) {
  35236. const output = node.getNodeType( this );
  35237. const flowData = this.flowChildNode( node, output );
  35238. this.flowsData.set( node, flowData );
  35239. return flowData;
  35240. }
  35241. /**
  35242. * Includes a node in the current function node.
  35243. *
  35244. * @param {Node} node - The node to include.
  35245. * @returns {void}
  35246. */
  35247. addInclude( node ) {
  35248. if ( this.currentFunctionNode !== null ) {
  35249. this.currentFunctionNode.includes.push( node );
  35250. }
  35251. }
  35252. /**
  35253. * Returns the native shader operator name for a given generic name.
  35254. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35255. *
  35256. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  35257. * @return {FunctionNode} The build function node.
  35258. */
  35259. buildFunctionNode( shaderNode ) {
  35260. const fn = new FunctionNode();
  35261. const previous = this.currentFunctionNode;
  35262. this.currentFunctionNode = fn;
  35263. fn.code = this.buildFunctionCode( shaderNode );
  35264. this.currentFunctionNode = previous;
  35265. return fn;
  35266. }
  35267. /**
  35268. * Generates a code flow based on a TSL function: Fn().
  35269. *
  35270. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  35271. * @return {Object}
  35272. */
  35273. flowShaderNode( shaderNode ) {
  35274. const layout = shaderNode.layout;
  35275. const inputs = {
  35276. [ Symbol.iterator ]() {
  35277. let index = 0;
  35278. const values = Object.values( this );
  35279. return {
  35280. next: () => ( {
  35281. value: values[ index ],
  35282. done: index ++ >= values.length
  35283. } )
  35284. };
  35285. }
  35286. };
  35287. for ( const input of layout.inputs ) {
  35288. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  35289. }
  35290. //
  35291. shaderNode.layout = null;
  35292. const callNode = shaderNode.call( inputs );
  35293. const flowData = this.flowStagesNode( callNode, layout.type );
  35294. shaderNode.layout = layout;
  35295. return flowData;
  35296. }
  35297. /**
  35298. * Executes the node in a specific build stage.
  35299. *
  35300. * @param {Node} node - The node to execute.
  35301. * @param {string} buildStage - The build stage to execute the node in.
  35302. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  35303. * @return {?(Node|string)} The result of the node build.
  35304. */
  35305. flowBuildStage( node, buildStage, output = null ) {
  35306. const previousBuildStage = this.getBuildStage();
  35307. this.setBuildStage( buildStage );
  35308. const result = node.build( this, output );
  35309. this.setBuildStage( previousBuildStage );
  35310. return result;
  35311. }
  35312. /**
  35313. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  35314. *
  35315. * @param {Node} node - The node to execute.
  35316. * @param {?string} output - Expected output type. For example 'vec3'.
  35317. * @return {Object}
  35318. */
  35319. flowStagesNode( node, output = null ) {
  35320. const previousFlow = this.flow;
  35321. const previousVars = this.vars;
  35322. const previousDeclarations = this.declarations;
  35323. const previousCache = this.cache;
  35324. const previousBuildStage = this.buildStage;
  35325. const previousStack = this.stack;
  35326. const flow = {
  35327. code: ''
  35328. };
  35329. this.flow = flow;
  35330. this.vars = {};
  35331. this.declarations = {};
  35332. this.cache = new NodeCache();
  35333. this.stack = stack();
  35334. for ( const buildStage of defaultBuildStages ) {
  35335. this.setBuildStage( buildStage );
  35336. flow.result = node.build( this, output );
  35337. }
  35338. flow.vars = this.getVars( this.shaderStage );
  35339. this.flow = previousFlow;
  35340. this.vars = previousVars;
  35341. this.declarations = previousDeclarations;
  35342. this.cache = previousCache;
  35343. this.stack = previousStack;
  35344. this.setBuildStage( previousBuildStage );
  35345. return flow;
  35346. }
  35347. /**
  35348. * Returns the native shader operator name for a given generic name.
  35349. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35350. *
  35351. * @abstract
  35352. * @param {string} op - The operator name to resolve.
  35353. * @return {?string} The resolved operator name.
  35354. */
  35355. getFunctionOperator( /* op */ ) {
  35356. return null;
  35357. }
  35358. /**
  35359. * Builds the given shader node.
  35360. *
  35361. * @abstract
  35362. * @param {ShaderNodeInternal} shaderNode - The shader node.
  35363. * @return {string} The function code.
  35364. */
  35365. buildFunctionCode( /* shaderNode */ ) {
  35366. warn( 'Abstract function.' );
  35367. }
  35368. /**
  35369. * Generates a code flow based on a child Node.
  35370. *
  35371. * @param {Node} node - The node to execute.
  35372. * @param {?string} output - Expected output type. For example 'vec3'.
  35373. * @return {Object} The code flow.
  35374. */
  35375. flowChildNode( node, output = null ) {
  35376. const previousFlow = this.flow;
  35377. const flow = {
  35378. code: ''
  35379. };
  35380. this.flow = flow;
  35381. flow.result = node.build( this, output );
  35382. this.flow = previousFlow;
  35383. return flow;
  35384. }
  35385. /**
  35386. * Executes a flow of code in a different stage.
  35387. *
  35388. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  35389. * return the value in fragment-stage even if it is being executed in an input fragment.
  35390. *
  35391. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35392. * @param {Node} node - The node to execute.
  35393. * @param {?string} output - Expected output type. For example 'vec3'.
  35394. * @param {?string} propertyName - The property name to assign the result.
  35395. * @return {?(Object|Node)} The code flow or node.build() result.
  35396. */
  35397. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  35398. const previousTab = this.tab;
  35399. const previousCache = this.cache;
  35400. const previousShaderStage = this.shaderStage;
  35401. const previousContext = this.context;
  35402. this.setShaderStage( shaderStage );
  35403. const context = { ...this.context };
  35404. delete context.nodeBlock;
  35405. this.cache = this.globalCache;
  35406. this.tab = '\t';
  35407. this.context = context;
  35408. let result = null;
  35409. if ( this.buildStage === 'generate' ) {
  35410. const flowData = this.flowChildNode( node, output );
  35411. if ( propertyName !== null ) {
  35412. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  35413. }
  35414. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  35415. result = flowData;
  35416. } else {
  35417. result = node.build( this );
  35418. }
  35419. this.setShaderStage( previousShaderStage );
  35420. this.cache = previousCache;
  35421. this.tab = previousTab;
  35422. this.context = previousContext;
  35423. return result;
  35424. }
  35425. /**
  35426. * Returns an array holding all node attributes of this node builder.
  35427. *
  35428. * @return {Array<NodeAttribute>} The node attributes of this builder.
  35429. */
  35430. getAttributesArray() {
  35431. return this.attributes.concat( this.bufferAttributes );
  35432. }
  35433. /**
  35434. * Returns the attribute definitions as a shader string for the given shader stage.
  35435. *
  35436. * @abstract
  35437. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35438. * @return {string} The attribute code section.
  35439. */
  35440. getAttributes( /*shaderStage*/ ) {
  35441. warn( 'Abstract function.' );
  35442. }
  35443. /**
  35444. * Returns the varying definitions as a shader string for the given shader stage.
  35445. *
  35446. * @abstract
  35447. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35448. * @return {string} The varying code section.
  35449. */
  35450. getVaryings( /*shaderStage*/ ) {
  35451. warn( 'Abstract function.' );
  35452. }
  35453. /**
  35454. * Returns a single variable definition as a shader string for the given variable type and name.
  35455. *
  35456. * @param {string} type - The variable's type.
  35457. * @param {string} name - The variable's name.
  35458. * @param {?number} [count=null] - The array length.
  35459. * @return {string} The shader string.
  35460. */
  35461. getVar( type, name, count = null ) {
  35462. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  35463. }
  35464. /**
  35465. * Returns the variable definitions as a shader string for the given shader stage.
  35466. *
  35467. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35468. * @return {string} The variable code section.
  35469. */
  35470. getVars( shaderStage ) {
  35471. let snippet = '';
  35472. const vars = this.vars[ shaderStage ];
  35473. if ( vars !== undefined ) {
  35474. for ( const variable of vars ) {
  35475. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  35476. }
  35477. }
  35478. return snippet;
  35479. }
  35480. /**
  35481. * Returns the uniform definitions as a shader string for the given shader stage.
  35482. *
  35483. * @abstract
  35484. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35485. * @return {string} The uniform code section.
  35486. */
  35487. getUniforms( /*shaderStage*/ ) {
  35488. warn( 'Abstract function.' );
  35489. }
  35490. /**
  35491. * Returns the native code definitions as a shader string for the given shader stage.
  35492. *
  35493. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35494. * @return {string} The native code section.
  35495. */
  35496. getCodes( shaderStage ) {
  35497. const codes = this.codes[ shaderStage ];
  35498. let code = '';
  35499. if ( codes !== undefined ) {
  35500. for ( const nodeCode of codes ) {
  35501. code += nodeCode.code + '\n';
  35502. }
  35503. }
  35504. return code;
  35505. }
  35506. /**
  35507. * Returns the hash of this node builder.
  35508. *
  35509. * @return {string} The hash.
  35510. */
  35511. getHash() {
  35512. return this.vertexShader + this.fragmentShader + this.computeShader;
  35513. }
  35514. /**
  35515. * Sets the current shader stage.
  35516. *
  35517. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  35518. */
  35519. setShaderStage( shaderStage ) {
  35520. this.shaderStage = shaderStage;
  35521. }
  35522. /**
  35523. * Returns the current shader stage.
  35524. *
  35525. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  35526. */
  35527. getShaderStage() {
  35528. return this.shaderStage;
  35529. }
  35530. /**
  35531. * Sets the current build stage.
  35532. *
  35533. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  35534. */
  35535. setBuildStage( buildStage ) {
  35536. this.buildStage = buildStage;
  35537. }
  35538. /**
  35539. * Returns the current build stage.
  35540. *
  35541. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  35542. */
  35543. getBuildStage() {
  35544. return this.buildStage;
  35545. }
  35546. /**
  35547. * Controls the code build of the shader stages.
  35548. *
  35549. * @abstract
  35550. */
  35551. buildCode() {
  35552. warn( 'Abstract function.' );
  35553. }
  35554. /**
  35555. * Returns the current sub-build layer.
  35556. *
  35557. * @return {SubBuildNode} The current sub-build layers.
  35558. */
  35559. get subBuild() {
  35560. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  35561. }
  35562. /**
  35563. * Adds a sub-build layer to the node builder.
  35564. *
  35565. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  35566. */
  35567. addSubBuild( subBuild ) {
  35568. this.subBuildLayers.push( subBuild );
  35569. }
  35570. /**
  35571. * Removes the last sub-build layer from the node builder.
  35572. *
  35573. * @return {SubBuildNode} The removed sub-build layer.
  35574. */
  35575. removeSubBuild() {
  35576. return this.subBuildLayers.pop();
  35577. }
  35578. /**
  35579. * Returns the closest sub-build layer for the given data.
  35580. *
  35581. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  35582. * @return {?string} The closest sub-build name or null if none found.
  35583. */
  35584. getClosestSubBuild( data ) {
  35585. let subBuilds;
  35586. if ( data && data.isNode ) {
  35587. if ( data.isShaderCallNodeInternal ) {
  35588. subBuilds = data.shaderNode.subBuilds;
  35589. } else if ( data.isStackNode ) {
  35590. subBuilds = [ data.subBuild ];
  35591. } else {
  35592. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  35593. }
  35594. } else if ( data instanceof Set ) {
  35595. subBuilds = [ ...data ];
  35596. } else {
  35597. subBuilds = data;
  35598. }
  35599. if ( ! subBuilds ) return null;
  35600. const subBuildLayers = this.subBuildLayers;
  35601. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  35602. const subBuild = subBuilds[ i ];
  35603. if ( subBuildLayers.includes( subBuild ) ) {
  35604. return subBuild;
  35605. }
  35606. }
  35607. return null;
  35608. }
  35609. /**
  35610. * Returns the output node of a sub-build layer.
  35611. *
  35612. * @param {Node} node - The node to get the output from.
  35613. * @return {string} The output node name.
  35614. */
  35615. getSubBuildOutput( node ) {
  35616. return this.getSubBuildProperty( 'outputNode', node );
  35617. }
  35618. /**
  35619. * Returns the sub-build property name for the given property and node.
  35620. *
  35621. * @param {string} [property=''] - The property name.
  35622. * @param {?Node} [node=null] - The node to get the sub-build from.
  35623. * @return {string} The sub-build property name.
  35624. */
  35625. getSubBuildProperty( property = '', node = null ) {
  35626. let subBuild;
  35627. if ( node !== null ) {
  35628. subBuild = this.getClosestSubBuild( node );
  35629. } else {
  35630. subBuild = this.subBuildFn;
  35631. }
  35632. let result;
  35633. if ( subBuild ) {
  35634. result = property ? ( subBuild + '_' + property ) : subBuild;
  35635. } else {
  35636. result = property;
  35637. }
  35638. return result;
  35639. }
  35640. /**
  35641. * Central build method which controls the build for the given object.
  35642. *
  35643. * @return {NodeBuilder} A reference to this node builder.
  35644. */
  35645. build() {
  35646. const { object, material, renderer } = this;
  35647. if ( material !== null ) {
  35648. let nodeMaterial = renderer.library.fromMaterial( material );
  35649. if ( nodeMaterial === null ) {
  35650. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  35651. nodeMaterial = new NodeMaterial();
  35652. }
  35653. nodeMaterial.build( this );
  35654. } else {
  35655. this.addFlow( 'compute', object );
  35656. }
  35657. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  35658. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  35659. // generate() -> stage 3: generate shader
  35660. for ( const buildStage of defaultBuildStages ) {
  35661. this.setBuildStage( buildStage );
  35662. if ( this.context.vertex && this.context.vertex.isNode ) {
  35663. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  35664. }
  35665. for ( const shaderStage of shaderStages ) {
  35666. this.setShaderStage( shaderStage );
  35667. const flowNodes = this.flowNodes[ shaderStage ];
  35668. for ( const node of flowNodes ) {
  35669. if ( buildStage === 'generate' ) {
  35670. this.flowNode( node );
  35671. } else {
  35672. node.build( this );
  35673. }
  35674. }
  35675. }
  35676. }
  35677. this.setBuildStage( null );
  35678. this.setShaderStage( null );
  35679. // stage 4: build code for a specific output
  35680. this.buildCode();
  35681. this.buildUpdateNodes();
  35682. return this;
  35683. }
  35684. /**
  35685. * Returns a uniform representation which is later used for UBO generation and rendering.
  35686. *
  35687. * @param {NodeUniform} uniformNode - The uniform node.
  35688. * @param {string} type - The requested type.
  35689. * @return {Uniform} The uniform.
  35690. */
  35691. getNodeUniform( uniformNode, type ) {
  35692. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  35693. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  35694. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  35695. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  35696. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  35697. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  35698. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  35699. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  35700. throw new Error( `Uniform "${type}" not declared.` );
  35701. }
  35702. /**
  35703. * Formats the given shader snippet from a given type into another one. E.g.
  35704. * this method might be used to convert a simple float string `"1.0"` into a
  35705. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  35706. *
  35707. * @param {string} snippet - The shader snippet.
  35708. * @param {string} fromType - The source type.
  35709. * @param {string} toType - The target type.
  35710. * @return {string} The updated shader string.
  35711. */
  35712. format( snippet, fromType, toType ) {
  35713. fromType = this.getVectorType( fromType );
  35714. toType = this.getVectorType( toType );
  35715. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  35716. return snippet;
  35717. }
  35718. const fromTypeLength = this.getTypeLength( fromType );
  35719. const toTypeLength = this.getTypeLength( toType );
  35720. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  35721. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  35722. }
  35723. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  35724. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  35725. }
  35726. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  35727. // @TODO: ignore for now
  35728. return snippet;
  35729. }
  35730. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  35731. // @TODO: ignore for now
  35732. return snippet;
  35733. }
  35734. if ( fromTypeLength === toTypeLength ) {
  35735. return `${ this.getType( toType ) }( ${ snippet } )`;
  35736. }
  35737. if ( fromTypeLength > toTypeLength ) {
  35738. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  35739. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  35740. }
  35741. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  35742. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  35743. }
  35744. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  35745. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  35746. }
  35747. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  35748. // convert a number value to vector type, e.g:
  35749. // vec3( 1u ) -> vec3( float( 1u ) )
  35750. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  35751. }
  35752. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  35753. }
  35754. /**
  35755. * Returns a signature with the engine's current revision.
  35756. *
  35757. * @return {string} The signature.
  35758. */
  35759. getSignature() {
  35760. return `// Three.js r${ REVISION } - Node System\n`;
  35761. }
  35762. }
  35763. /**
  35764. * Management class for updating nodes. The module tracks metrics like
  35765. * the elapsed time, delta time, the render and frame ID to correctly
  35766. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  35767. * and {@link Node#updateAfter} depending on the node's configuration.
  35768. */
  35769. class NodeFrame {
  35770. /**
  35771. * Constructs a new node fame.
  35772. */
  35773. constructor() {
  35774. /**
  35775. * The elapsed time in seconds.
  35776. *
  35777. * @type {number}
  35778. * @default 0
  35779. */
  35780. this.time = 0;
  35781. /**
  35782. * The delta time in seconds.
  35783. *
  35784. * @type {number}
  35785. * @default 0
  35786. */
  35787. this.deltaTime = 0;
  35788. /**
  35789. * The frame ID.
  35790. *
  35791. * @type {number}
  35792. * @default 0
  35793. */
  35794. this.frameId = 0;
  35795. /**
  35796. * The render ID.
  35797. *
  35798. * @type {number}
  35799. * @default 0
  35800. */
  35801. this.renderId = 0;
  35802. /**
  35803. * Used to control the {@link Node#update} call.
  35804. *
  35805. * @type {WeakMap<Node, Object>}
  35806. */
  35807. this.updateMap = new WeakMap();
  35808. /**
  35809. * Used to control the {@link Node#updateBefore} call.
  35810. *
  35811. * @type {WeakMap<Node, Object>}
  35812. */
  35813. this.updateBeforeMap = new WeakMap();
  35814. /**
  35815. * Used to control the {@link Node#updateAfter} call.
  35816. *
  35817. * @type {WeakMap<Node, Object>}
  35818. */
  35819. this.updateAfterMap = new WeakMap();
  35820. /**
  35821. * A reference to the current renderer.
  35822. *
  35823. * @type {?Renderer}
  35824. * @default null
  35825. */
  35826. this.renderer = null;
  35827. /**
  35828. * A reference to the current material.
  35829. *
  35830. * @type {?Material}
  35831. * @default null
  35832. */
  35833. this.material = null;
  35834. /**
  35835. * A reference to the current camera.
  35836. *
  35837. * @type {?Camera}
  35838. * @default null
  35839. */
  35840. this.camera = null;
  35841. /**
  35842. * A reference to the current 3D object.
  35843. *
  35844. * @type {?Object3D}
  35845. * @default null
  35846. */
  35847. this.object = null;
  35848. /**
  35849. * A reference to the current scene.
  35850. *
  35851. * @type {?Scene}
  35852. * @default null
  35853. */
  35854. this.scene = null;
  35855. }
  35856. /**
  35857. * Returns a dictionary for a given node and update map which
  35858. * is used to correctly call node update methods per frame or render.
  35859. *
  35860. * @private
  35861. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  35862. * @param {Node} nodeRef - The reference to the current node.
  35863. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  35864. */
  35865. _getMaps( referenceMap, nodeRef ) {
  35866. let maps = referenceMap.get( nodeRef );
  35867. if ( maps === undefined ) {
  35868. maps = {
  35869. renderId: 0,
  35870. frameId: 0,
  35871. };
  35872. referenceMap.set( nodeRef, maps );
  35873. }
  35874. return maps;
  35875. }
  35876. /**
  35877. * This method executes the {@link Node#updateBefore} for the given node.
  35878. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  35879. * is only executed once per frame, render or object depending on the update
  35880. * type.
  35881. *
  35882. * @param {Node} node - The node that should be updated.
  35883. */
  35884. updateBeforeNode( node ) {
  35885. const updateType = node.getUpdateBeforeType();
  35886. const reference = node.updateReference( this );
  35887. if ( updateType === NodeUpdateType.FRAME ) {
  35888. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  35889. if ( nodeUpdateBeforeMap.frameId !== this.frameId ) {
  35890. if ( node.updateBefore( this ) !== false ) {
  35891. nodeUpdateBeforeMap.frameId = this.frameId;
  35892. }
  35893. }
  35894. } else if ( updateType === NodeUpdateType.RENDER ) {
  35895. const nodeUpdateBeforeMap = this._getMaps( this.updateBeforeMap, reference );
  35896. if ( nodeUpdateBeforeMap.renderId !== this.renderId ) {
  35897. if ( node.updateBefore( this ) !== false ) {
  35898. nodeUpdateBeforeMap.renderId = this.renderId;
  35899. }
  35900. }
  35901. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35902. node.updateBefore( this );
  35903. }
  35904. }
  35905. /**
  35906. * This method executes the {@link Node#updateAfter} for the given node.
  35907. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  35908. * is only executed once per frame, render or object depending on the update
  35909. * type.
  35910. *
  35911. * @param {Node} node - The node that should be updated.
  35912. */
  35913. updateAfterNode( node ) {
  35914. const updateType = node.getUpdateAfterType();
  35915. const reference = node.updateReference( this );
  35916. if ( updateType === NodeUpdateType.FRAME ) {
  35917. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  35918. if ( nodeUpdateAfterMap.frameId !== this.frameId ) {
  35919. if ( node.updateAfter( this ) !== false ) {
  35920. nodeUpdateAfterMap.frameId = this.frameId;
  35921. }
  35922. }
  35923. } else if ( updateType === NodeUpdateType.RENDER ) {
  35924. const nodeUpdateAfterMap = this._getMaps( this.updateAfterMap, reference );
  35925. if ( nodeUpdateAfterMap.renderId !== this.renderId ) {
  35926. if ( node.updateAfter( this ) !== false ) {
  35927. nodeUpdateAfterMap.renderId = this.renderId;
  35928. }
  35929. }
  35930. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35931. node.updateAfter( this );
  35932. }
  35933. }
  35934. /**
  35935. * This method executes the {@link Node#update} for the given node.
  35936. * It makes sure {@link Node#updateType} is honored meaning the update
  35937. * is only executed once per frame, render or object depending on the update
  35938. * type.
  35939. *
  35940. * @param {Node} node - The node that should be updated.
  35941. */
  35942. updateNode( node ) {
  35943. const updateType = node.getUpdateType();
  35944. const reference = node.updateReference( this );
  35945. if ( updateType === NodeUpdateType.FRAME ) {
  35946. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  35947. if ( nodeUpdateMap.frameId !== this.frameId ) {
  35948. if ( node.update( this ) !== false ) {
  35949. nodeUpdateMap.frameId = this.frameId;
  35950. }
  35951. }
  35952. } else if ( updateType === NodeUpdateType.RENDER ) {
  35953. const nodeUpdateMap = this._getMaps( this.updateMap, reference );
  35954. if ( nodeUpdateMap.renderId !== this.renderId ) {
  35955. if ( node.update( this ) !== false ) {
  35956. nodeUpdateMap.renderId = this.renderId;
  35957. }
  35958. }
  35959. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35960. node.update( this );
  35961. }
  35962. }
  35963. /**
  35964. * Updates the internal state of the node frame. This method is
  35965. * called by the renderer in its internal animation loop.
  35966. */
  35967. update() {
  35968. this.frameId ++;
  35969. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  35970. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  35971. this.lastTime = performance.now();
  35972. this.time += this.deltaTime;
  35973. }
  35974. }
  35975. /**
  35976. * Describes the input of a {@link NodeFunction}.
  35977. */
  35978. class NodeFunctionInput {
  35979. /**
  35980. * Constructs a new node function input.
  35981. *
  35982. * @param {string} type - The input type.
  35983. * @param {string} name - The input name.
  35984. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  35985. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  35986. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  35987. */
  35988. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  35989. /**
  35990. * The input type.
  35991. *
  35992. * @type {string}
  35993. */
  35994. this.type = type;
  35995. /**
  35996. * The input name.
  35997. *
  35998. * @type {string}
  35999. */
  36000. this.name = name;
  36001. /**
  36002. * If the input is an Array, count will be the length.
  36003. *
  36004. * @type {?number}
  36005. * @default null
  36006. */
  36007. this.count = count;
  36008. /**
  36009. *The parameter qualifier (only relevant for GLSL).
  36010. *
  36011. * @type {('in'|'out'|'inout')}
  36012. * @default ''
  36013. */
  36014. this.qualifier = qualifier;
  36015. /**
  36016. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  36017. *
  36018. * @type {boolean}
  36019. * @default false
  36020. */
  36021. this.isConst = isConst;
  36022. }
  36023. }
  36024. NodeFunctionInput.isNodeFunctionInput = true;
  36025. /**
  36026. * Module for representing directional lights as nodes.
  36027. *
  36028. * @augments AnalyticLightNode
  36029. */
  36030. class DirectionalLightNode extends AnalyticLightNode {
  36031. static get type() {
  36032. return 'DirectionalLightNode';
  36033. }
  36034. /**
  36035. * Constructs a new directional light node.
  36036. *
  36037. * @param {?DirectionalLight} [light=null] - The directional light source.
  36038. */
  36039. constructor( light = null ) {
  36040. super( light );
  36041. }
  36042. setupDirect() {
  36043. const lightColor = this.colorNode;
  36044. const lightDirection = lightTargetDirection( this.light );
  36045. return { lightDirection, lightColor };
  36046. }
  36047. }
  36048. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36049. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36050. let _ltcLib = null;
  36051. /**
  36052. * Module for representing rect area lights as nodes.
  36053. *
  36054. * @augments AnalyticLightNode
  36055. */
  36056. class RectAreaLightNode extends AnalyticLightNode {
  36057. static get type() {
  36058. return 'RectAreaLightNode';
  36059. }
  36060. /**
  36061. * Constructs a new rect area light node.
  36062. *
  36063. * @param {?RectAreaLight} [light=null] - The rect area light source.
  36064. */
  36065. constructor( light = null ) {
  36066. super( light );
  36067. /**
  36068. * Uniform node representing the half height of the are light.
  36069. *
  36070. * @type {UniformNode<vec3>}
  36071. */
  36072. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36073. /**
  36074. * Uniform node representing the half width of the are light.
  36075. *
  36076. * @type {UniformNode<vec3>}
  36077. */
  36078. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36079. /**
  36080. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  36081. * relies on `viewMatrix` which might vary per render call.
  36082. *
  36083. * @type {string}
  36084. * @default 'render'
  36085. */
  36086. this.updateType = NodeUpdateType.RENDER;
  36087. }
  36088. /**
  36089. * Overwritten to updated rect area light specific uniforms.
  36090. *
  36091. * @param {NodeFrame} frame - A reference to the current node frame.
  36092. */
  36093. update( frame ) {
  36094. super.update( frame );
  36095. const { light } = this;
  36096. const viewMatrix = frame.camera.matrixWorldInverse;
  36097. _matrix42.identity();
  36098. _matrix41.copy( light.matrixWorld );
  36099. _matrix41.premultiply( viewMatrix );
  36100. _matrix42.extractRotation( _matrix41 );
  36101. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36102. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36103. this.halfWidth.value.applyMatrix4( _matrix42 );
  36104. this.halfHeight.value.applyMatrix4( _matrix42 );
  36105. }
  36106. setupDirectRectArea( builder ) {
  36107. let ltc_1, ltc_2;
  36108. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36109. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  36110. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  36111. } else {
  36112. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  36113. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  36114. }
  36115. const { colorNode, light } = this;
  36116. const lightPosition = lightViewPosition( light );
  36117. return {
  36118. lightColor: colorNode,
  36119. lightPosition,
  36120. halfWidth: this.halfWidth,
  36121. halfHeight: this.halfHeight,
  36122. ltc_1,
  36123. ltc_2
  36124. };
  36125. }
  36126. /**
  36127. * Used to configure the internal BRDF approximation texture data.
  36128. *
  36129. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  36130. */
  36131. static setLTC( ltc ) {
  36132. _ltcLib = ltc;
  36133. }
  36134. }
  36135. /**
  36136. * Module for representing spot lights as nodes.
  36137. *
  36138. * @augments AnalyticLightNode
  36139. */
  36140. class SpotLightNode extends AnalyticLightNode {
  36141. static get type() {
  36142. return 'SpotLightNode';
  36143. }
  36144. /**
  36145. * Constructs a new spot light node.
  36146. *
  36147. * @param {?SpotLight} [light=null] - The spot light source.
  36148. */
  36149. constructor( light = null ) {
  36150. super( light );
  36151. /**
  36152. * Uniform node representing the cone cosine.
  36153. *
  36154. * @type {UniformNode<float>}
  36155. */
  36156. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36157. /**
  36158. * Uniform node representing the penumbra cosine.
  36159. *
  36160. * @type {UniformNode<float>}
  36161. */
  36162. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36163. /**
  36164. * Uniform node representing the cutoff distance.
  36165. *
  36166. * @type {UniformNode<float>}
  36167. */
  36168. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36169. /**
  36170. * Uniform node representing the decay exponent.
  36171. *
  36172. * @type {UniformNode<float>}
  36173. */
  36174. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36175. /**
  36176. * Uniform node representing the light color.
  36177. *
  36178. * @type {UniformNode<Color>}
  36179. */
  36180. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  36181. }
  36182. /**
  36183. * Overwritten to updated spot light specific uniforms.
  36184. *
  36185. * @param {NodeFrame} frame - A reference to the current node frame.
  36186. */
  36187. update( frame ) {
  36188. super.update( frame );
  36189. const { light } = this;
  36190. this.coneCosNode.value = Math.cos( light.angle );
  36191. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36192. this.cutoffDistanceNode.value = light.distance;
  36193. this.decayExponentNode.value = light.decay;
  36194. }
  36195. /**
  36196. * Computes the spot attenuation for the given angle.
  36197. *
  36198. * @param {NodeBuilder} builder - The node builder.
  36199. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36200. * @return {Node<float>} The spot attenuation.
  36201. */
  36202. getSpotAttenuation( builder, angleCosine ) {
  36203. const { coneCosNode, penumbraCosNode } = this;
  36204. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36205. }
  36206. getLightCoord( builder ) {
  36207. const properties = builder.getNodeProperties( this );
  36208. let projectionUV = properties.projectionUV;
  36209. if ( projectionUV === undefined ) {
  36210. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  36211. properties.projectionUV = projectionUV;
  36212. }
  36213. return projectionUV;
  36214. }
  36215. setupDirect( builder ) {
  36216. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36217. const lightVector = this.getLightVector( builder );
  36218. const lightDirection = lightVector.normalize();
  36219. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36220. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  36221. const lightDistance = lightVector.length();
  36222. const lightAttenuation = getDistanceAttenuation( {
  36223. lightDistance,
  36224. cutoffDistance: cutoffDistanceNode,
  36225. decayExponent: decayExponentNode
  36226. } );
  36227. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36228. let projected, lightCoord;
  36229. if ( light.colorNode ) {
  36230. lightCoord = this.getLightCoord( builder );
  36231. projected = light.colorNode( lightCoord );
  36232. } else if ( light.map ) {
  36233. lightCoord = this.getLightCoord( builder );
  36234. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  36235. }
  36236. if ( projected ) {
  36237. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  36238. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  36239. }
  36240. return { lightColor, lightDirection };
  36241. }
  36242. }
  36243. /**
  36244. * An IES version of the default spot light node.
  36245. *
  36246. * @augments SpotLightNode
  36247. */
  36248. class IESSpotLightNode extends SpotLightNode {
  36249. static get type() {
  36250. return 'IESSpotLightNode';
  36251. }
  36252. /**
  36253. * Overwrites the default implementation to compute an IES conform spot attenuation.
  36254. *
  36255. * @param {NodeBuilder} builder - The node builder.
  36256. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36257. * @return {Node<float>} The spot attenuation.
  36258. */
  36259. getSpotAttenuation( builder, angleCosine ) {
  36260. const iesMap = this.light.iesMap;
  36261. let spotAttenuation = null;
  36262. if ( iesMap && iesMap.isTexture === true ) {
  36263. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36264. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36265. } else {
  36266. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36267. }
  36268. return spotAttenuation;
  36269. }
  36270. }
  36271. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  36272. const d = p.abs().sub( b );
  36273. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  36274. } );
  36275. /**
  36276. * An implementation of a projector light node.
  36277. *
  36278. * @augments SpotLightNode
  36279. */
  36280. class ProjectorLightNode extends SpotLightNode {
  36281. static get type() {
  36282. return 'ProjectorLightNode';
  36283. }
  36284. update( frame ) {
  36285. super.update( frame );
  36286. const light = this.light;
  36287. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  36288. if ( light.aspect === null ) {
  36289. let aspect = 1;
  36290. if ( light.map !== null ) {
  36291. aspect = light.map.width / light.map.height;
  36292. }
  36293. light.shadow.aspect = aspect;
  36294. } else {
  36295. light.shadow.aspect = light.aspect;
  36296. }
  36297. }
  36298. /**
  36299. * Overwrites the default implementation to compute projection attenuation.
  36300. *
  36301. * @param {NodeBuilder} builder - The node builder.
  36302. * @return {Node<float>} The spot attenuation.
  36303. */
  36304. getSpotAttenuation( builder ) {
  36305. const attenuation = float( 0 );
  36306. const penumbraCos = this.penumbraCosNode;
  36307. // compute the fragment's position in the light's clip space
  36308. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  36309. // the sign of w determines whether the current fragment is in front or behind the light.
  36310. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  36311. If( spotLightCoord.w.greaterThan( 0 ), () => {
  36312. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  36313. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  36314. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  36315. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  36316. } );
  36317. return attenuation;
  36318. }
  36319. }
  36320. /**
  36321. * Module for representing ambient lights as nodes.
  36322. *
  36323. * @augments AnalyticLightNode
  36324. */
  36325. class AmbientLightNode extends AnalyticLightNode {
  36326. static get type() {
  36327. return 'AmbientLightNode';
  36328. }
  36329. /**
  36330. * Constructs a new ambient light node.
  36331. *
  36332. * @param {?AmbientLight} [light=null] - The ambient light source.
  36333. */
  36334. constructor( light = null ) {
  36335. super( light );
  36336. }
  36337. setup( { context } ) {
  36338. context.irradiance.addAssign( this.colorNode );
  36339. }
  36340. }
  36341. /**
  36342. * Module for representing hemisphere lights as nodes.
  36343. *
  36344. * @augments AnalyticLightNode
  36345. */
  36346. class HemisphereLightNode extends AnalyticLightNode {
  36347. static get type() {
  36348. return 'HemisphereLightNode';
  36349. }
  36350. /**
  36351. * Constructs a new hemisphere light node.
  36352. *
  36353. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  36354. */
  36355. constructor( light = null ) {
  36356. super( light );
  36357. /**
  36358. * Uniform node representing the light's position.
  36359. *
  36360. * @type {UniformNode<vec3>}
  36361. */
  36362. this.lightPositionNode = lightPosition( light );
  36363. /**
  36364. * A node representing the light's direction.
  36365. *
  36366. * @type {Node<vec3>}
  36367. */
  36368. this.lightDirectionNode = this.lightPositionNode.normalize();
  36369. /**
  36370. * Uniform node representing the light's ground color.
  36371. *
  36372. * @type {UniformNode<vec3>}
  36373. */
  36374. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36375. }
  36376. /**
  36377. * Overwritten to updated hemisphere light specific uniforms.
  36378. *
  36379. * @param {NodeFrame} frame - A reference to the current node frame.
  36380. */
  36381. update( frame ) {
  36382. const { light } = this;
  36383. super.update( frame );
  36384. this.lightPositionNode.object3d = light;
  36385. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36386. }
  36387. setup( builder ) {
  36388. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36389. const dotNL = normalWorld.dot( lightDirectionNode );
  36390. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36391. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36392. builder.context.irradiance.addAssign( irradiance );
  36393. }
  36394. }
  36395. /**
  36396. * Module for representing light probes as nodes.
  36397. *
  36398. * @augments AnalyticLightNode
  36399. */
  36400. class LightProbeNode extends AnalyticLightNode {
  36401. static get type() {
  36402. return 'LightProbeNode';
  36403. }
  36404. /**
  36405. * Constructs a new light probe node.
  36406. *
  36407. * @param {?LightProbe} [light=null] - The light probe.
  36408. */
  36409. constructor( light = null ) {
  36410. super( light );
  36411. const array = [];
  36412. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36413. /**
  36414. * Light probe represented as a uniform of spherical harmonics.
  36415. *
  36416. * @type {UniformArrayNode}
  36417. */
  36418. this.lightProbe = uniformArray( array );
  36419. }
  36420. /**
  36421. * Overwritten to updated light probe specific uniforms.
  36422. *
  36423. * @param {NodeFrame} frame - A reference to the current node frame.
  36424. */
  36425. update( frame ) {
  36426. const { light } = this;
  36427. super.update( frame );
  36428. //
  36429. for ( let i = 0; i < 9; i ++ ) {
  36430. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36431. }
  36432. }
  36433. setup( builder ) {
  36434. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36435. builder.context.irradiance.addAssign( irradiance );
  36436. }
  36437. }
  36438. /**
  36439. * Base class for node parsers. A derived parser must be implemented
  36440. * for each supported native shader language.
  36441. */
  36442. class NodeParser {
  36443. /**
  36444. * The method parses the given native code an returns a node function.
  36445. *
  36446. * @abstract
  36447. * @param {string} source - The native shader code.
  36448. * @return {NodeFunction} A node function.
  36449. */
  36450. parseFunction( /*source*/ ) {
  36451. warn( 'Abstract function.' );
  36452. }
  36453. }
  36454. /**
  36455. * Base class for node functions. A derived module must be implemented
  36456. * for each supported native shader language. Similar to other `Node*` modules,
  36457. * this class is only relevant during the building process and not used
  36458. * in user-level code.
  36459. */
  36460. class NodeFunction {
  36461. /**
  36462. * Constructs a new node function.
  36463. *
  36464. * @param {string} type - The node type. This type is the return type of the node function.
  36465. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  36466. * @param {string} [name=''] - The function's name.
  36467. * @param {string} [precision=''] - The precision qualifier.
  36468. */
  36469. constructor( type, inputs, name = '', precision = '' ) {
  36470. /**
  36471. * The node type. This type is the return type of the node function.
  36472. *
  36473. * @type {string}
  36474. */
  36475. this.type = type;
  36476. /**
  36477. * The function's inputs.
  36478. *
  36479. * @type {Array<NodeFunctionInput>}
  36480. */
  36481. this.inputs = inputs;
  36482. /**
  36483. * The name of the uniform.
  36484. *
  36485. * @type {string}
  36486. * @default ''
  36487. */
  36488. this.name = name;
  36489. /**
  36490. * The precision qualifier.
  36491. *
  36492. * @type {string}
  36493. * @default ''
  36494. */
  36495. this.precision = precision;
  36496. }
  36497. /**
  36498. * This method returns the native code of the node function.
  36499. *
  36500. * @abstract
  36501. * @param {string} name - The function's name.
  36502. * @return {string} A shader code.
  36503. */
  36504. getCode( /*name = this.name*/ ) {
  36505. warn( 'Abstract function.' );
  36506. }
  36507. }
  36508. NodeFunction.isNodeFunction = true;
  36509. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36510. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36511. const pragmaMain = '#pragma main';
  36512. const parse$1 = ( source ) => {
  36513. source = source.trim();
  36514. const pragmaMainIndex = source.indexOf( pragmaMain );
  36515. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36516. const declaration = mainCode.match( declarationRegexp$1 );
  36517. if ( declaration !== null && declaration.length === 5 ) {
  36518. // tokenizer
  36519. const inputsCode = declaration[ 4 ];
  36520. const propsMatches = [];
  36521. let nameMatch = null;
  36522. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36523. propsMatches.push( nameMatch );
  36524. }
  36525. // parser
  36526. const inputs = [];
  36527. let i = 0;
  36528. while ( i < propsMatches.length ) {
  36529. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36530. if ( isConst === true ) {
  36531. i ++;
  36532. }
  36533. let qualifier = propsMatches[ i ][ 0 ];
  36534. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36535. i ++;
  36536. } else {
  36537. qualifier = '';
  36538. }
  36539. const type = propsMatches[ i ++ ][ 0 ];
  36540. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36541. if ( Number.isNaN( count ) === false ) i ++;
  36542. else count = null;
  36543. const name = propsMatches[ i ++ ][ 0 ];
  36544. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36545. }
  36546. //
  36547. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36548. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36549. const type = declaration[ 2 ];
  36550. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36551. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  36552. return {
  36553. type,
  36554. inputs,
  36555. name,
  36556. precision,
  36557. inputsCode,
  36558. blockCode,
  36559. headerCode
  36560. };
  36561. } else {
  36562. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36563. }
  36564. };
  36565. /**
  36566. * This class represents a GLSL node function.
  36567. *
  36568. * @augments NodeFunction
  36569. */
  36570. class GLSLNodeFunction extends NodeFunction {
  36571. /**
  36572. * Constructs a new GLSL node function.
  36573. *
  36574. * @param {string} source - The GLSL source.
  36575. */
  36576. constructor( source ) {
  36577. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36578. super( type, inputs, name, precision );
  36579. this.inputsCode = inputsCode;
  36580. this.blockCode = blockCode;
  36581. this.headerCode = headerCode;
  36582. }
  36583. /**
  36584. * This method returns the GLSL code of the node function.
  36585. *
  36586. * @param {string} [name=this.name] - The function's name.
  36587. * @return {string} The shader code.
  36588. */
  36589. getCode( name = this.name ) {
  36590. let code;
  36591. const blockCode = this.blockCode;
  36592. if ( blockCode !== '' ) {
  36593. const { type, inputsCode, headerCode, precision } = this;
  36594. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36595. if ( precision !== '' ) {
  36596. declarationCode = `${ precision } ${ declarationCode }`;
  36597. }
  36598. code = headerCode + declarationCode + blockCode;
  36599. } else {
  36600. // interface function
  36601. code = '';
  36602. }
  36603. return code;
  36604. }
  36605. }
  36606. /**
  36607. * A GLSL node parser.
  36608. *
  36609. * @augments NodeParser
  36610. */
  36611. class GLSLNodeParser extends NodeParser {
  36612. /**
  36613. * The method parses the given GLSL code an returns a node function.
  36614. *
  36615. * @param {string} source - The GLSL code.
  36616. * @return {GLSLNodeFunction} A node function.
  36617. */
  36618. parseFunction( source ) {
  36619. return new GLSLNodeFunction( source );
  36620. }
  36621. }
  36622. const _outputNodeMap = new WeakMap();
  36623. const _chainKeys$2 = [];
  36624. const _cacheKeyValues = [];
  36625. /**
  36626. * This renderer module manages node-related objects and is the
  36627. * primary interface between the renderer and the node system.
  36628. *
  36629. * @private
  36630. * @augments DataMap
  36631. */
  36632. class Nodes extends DataMap {
  36633. /**
  36634. * Constructs a new nodes management component.
  36635. *
  36636. * @param {Renderer} renderer - The renderer.
  36637. * @param {Backend} backend - The renderer's backend.
  36638. */
  36639. constructor( renderer, backend ) {
  36640. super();
  36641. /**
  36642. * The renderer.
  36643. *
  36644. * @type {Renderer}
  36645. */
  36646. this.renderer = renderer;
  36647. /**
  36648. * The renderer's backend.
  36649. *
  36650. * @type {Backend}
  36651. */
  36652. this.backend = backend;
  36653. /**
  36654. * The node frame.
  36655. *
  36656. * @type {Renderer}
  36657. */
  36658. this.nodeFrame = new NodeFrame();
  36659. /**
  36660. * A cache for managing node builder states.
  36661. *
  36662. * @type {Map<number,NodeBuilderState>}
  36663. */
  36664. this.nodeBuilderCache = new Map();
  36665. /**
  36666. * A cache for managing data cache key data.
  36667. *
  36668. * @type {ChainMap}
  36669. */
  36670. this.callHashCache = new ChainMap();
  36671. /**
  36672. * A cache for managing node uniforms group data.
  36673. *
  36674. * @type {ChainMap}
  36675. */
  36676. this.groupsData = new ChainMap();
  36677. /**
  36678. * A cache for managing node objects of
  36679. * scene properties like fog or environments.
  36680. *
  36681. * @type {Object<string,WeakMap>}
  36682. */
  36683. this.cacheLib = {};
  36684. }
  36685. /**
  36686. * Returns `true` if the given node uniforms group must be updated or not.
  36687. *
  36688. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  36689. * @return {boolean} Whether the node uniforms group requires an update or not.
  36690. */
  36691. updateGroup( nodeUniformsGroup ) {
  36692. const groupNode = nodeUniformsGroup.groupNode;
  36693. const name = groupNode.name;
  36694. // objectGroup is always updated
  36695. if ( name === objectGroup.name ) return true;
  36696. // renderGroup is updated once per render/compute call
  36697. if ( name === renderGroup.name ) {
  36698. const uniformsGroupData = this.get( nodeUniformsGroup );
  36699. const renderId = this.nodeFrame.renderId;
  36700. if ( uniformsGroupData.renderId !== renderId ) {
  36701. uniformsGroupData.renderId = renderId;
  36702. return true;
  36703. }
  36704. return false;
  36705. }
  36706. // frameGroup is updated once per frame
  36707. if ( name === frameGroup.name ) {
  36708. const uniformsGroupData = this.get( nodeUniformsGroup );
  36709. const frameId = this.nodeFrame.frameId;
  36710. if ( uniformsGroupData.frameId !== frameId ) {
  36711. uniformsGroupData.frameId = frameId;
  36712. return true;
  36713. }
  36714. return false;
  36715. }
  36716. // other groups are updated just when groupNode.needsUpdate is true
  36717. _chainKeys$2[ 0 ] = groupNode;
  36718. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  36719. let groupData = this.groupsData.get( _chainKeys$2 );
  36720. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  36721. _chainKeys$2.length = 0;
  36722. if ( groupData.version !== groupNode.version ) {
  36723. groupData.version = groupNode.version;
  36724. return true;
  36725. }
  36726. return false;
  36727. }
  36728. /**
  36729. * Returns the cache key for the given render object.
  36730. *
  36731. * @param {RenderObject} renderObject - The render object.
  36732. * @return {number} The cache key.
  36733. */
  36734. getForRenderCacheKey( renderObject ) {
  36735. return renderObject.initialCacheKey;
  36736. }
  36737. /**
  36738. * Returns a node builder state for the given render object.
  36739. *
  36740. * @param {RenderObject} renderObject - The render object.
  36741. * @return {NodeBuilderState} The node builder state.
  36742. */
  36743. getForRender( renderObject ) {
  36744. const renderObjectData = this.get( renderObject );
  36745. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36746. if ( nodeBuilderState === undefined ) {
  36747. const { nodeBuilderCache } = this;
  36748. const cacheKey = this.getForRenderCacheKey( renderObject );
  36749. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36750. if ( nodeBuilderState === undefined ) {
  36751. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36752. nodeBuilder.scene = renderObject.scene;
  36753. nodeBuilder.material = renderObject.material;
  36754. nodeBuilder.camera = renderObject.camera;
  36755. nodeBuilder.context.material = renderObject.material;
  36756. nodeBuilder.lightsNode = renderObject.lightsNode;
  36757. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36758. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36759. nodeBuilder.clippingContext = renderObject.clippingContext;
  36760. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  36761. nodeBuilder.enableMultiview();
  36762. }
  36763. nodeBuilder.build();
  36764. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36765. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  36766. }
  36767. nodeBuilderState.usedTimes ++;
  36768. renderObjectData.nodeBuilderState = nodeBuilderState;
  36769. }
  36770. return nodeBuilderState;
  36771. }
  36772. /**
  36773. * Deletes the given object from the internal data map
  36774. *
  36775. * @param {any} object - The object to delete.
  36776. * @return {?Object} The deleted dictionary.
  36777. */
  36778. delete( object ) {
  36779. if ( object.isRenderObject ) {
  36780. const nodeBuilderState = this.get( object ).nodeBuilderState;
  36781. nodeBuilderState.usedTimes --;
  36782. if ( nodeBuilderState.usedTimes === 0 ) {
  36783. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  36784. }
  36785. }
  36786. return super.delete( object );
  36787. }
  36788. /**
  36789. * Returns a node builder state for the given compute node.
  36790. *
  36791. * @param {Node} computeNode - The compute node.
  36792. * @return {NodeBuilderState} The node builder state.
  36793. */
  36794. getForCompute( computeNode ) {
  36795. const computeData = this.get( computeNode );
  36796. let nodeBuilderState = computeData.nodeBuilderState;
  36797. if ( nodeBuilderState === undefined ) {
  36798. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  36799. nodeBuilder.build();
  36800. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36801. computeData.nodeBuilderState = nodeBuilderState;
  36802. }
  36803. return nodeBuilderState;
  36804. }
  36805. /**
  36806. * Creates a node builder state for the given node builder.
  36807. *
  36808. * @private
  36809. * @param {NodeBuilder} nodeBuilder - The node builder.
  36810. * @return {NodeBuilderState} The node builder state.
  36811. */
  36812. _createNodeBuilderState( nodeBuilder ) {
  36813. return new NodeBuilderState(
  36814. nodeBuilder.vertexShader,
  36815. nodeBuilder.fragmentShader,
  36816. nodeBuilder.computeShader,
  36817. nodeBuilder.getAttributesArray(),
  36818. nodeBuilder.getBindings(),
  36819. nodeBuilder.updateNodes,
  36820. nodeBuilder.updateBeforeNodes,
  36821. nodeBuilder.updateAfterNodes,
  36822. nodeBuilder.observer,
  36823. nodeBuilder.transforms
  36824. );
  36825. }
  36826. /**
  36827. * Returns an environment node for the current configured
  36828. * scene environment.
  36829. *
  36830. * @param {Scene} scene - The scene.
  36831. * @return {Node} A node representing the current scene environment.
  36832. */
  36833. getEnvironmentNode( scene ) {
  36834. this.updateEnvironment( scene );
  36835. let environmentNode = null;
  36836. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  36837. environmentNode = scene.environmentNode;
  36838. } else {
  36839. const sceneData = this.get( scene );
  36840. if ( sceneData.environmentNode ) {
  36841. environmentNode = sceneData.environmentNode;
  36842. }
  36843. }
  36844. return environmentNode;
  36845. }
  36846. /**
  36847. * Returns a background node for the current configured
  36848. * scene background.
  36849. *
  36850. * @param {Scene} scene - The scene.
  36851. * @return {Node} A node representing the current scene background.
  36852. */
  36853. getBackgroundNode( scene ) {
  36854. this.updateBackground( scene );
  36855. let backgroundNode = null;
  36856. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  36857. backgroundNode = scene.backgroundNode;
  36858. } else {
  36859. const sceneData = this.get( scene );
  36860. if ( sceneData.backgroundNode ) {
  36861. backgroundNode = sceneData.backgroundNode;
  36862. }
  36863. }
  36864. return backgroundNode;
  36865. }
  36866. /**
  36867. * Returns a fog node for the current configured scene fog.
  36868. *
  36869. * @param {Scene} scene - The scene.
  36870. * @return {Node} A node representing the current scene fog.
  36871. */
  36872. getFogNode( scene ) {
  36873. this.updateFog( scene );
  36874. return scene.fogNode || this.get( scene ).fogNode || null;
  36875. }
  36876. /**
  36877. * Returns a cache key for the given scene and lights node.
  36878. * This key is used by `RenderObject` as a part of the dynamic
  36879. * cache key (a key that must be checked every time the render
  36880. * objects is drawn).
  36881. *
  36882. * @param {Scene} scene - The scene.
  36883. * @param {LightsNode} lightsNode - The lights node.
  36884. * @return {number} The cache key.
  36885. */
  36886. getCacheKey( scene, lightsNode ) {
  36887. _chainKeys$2[ 0 ] = scene;
  36888. _chainKeys$2[ 1 ] = lightsNode;
  36889. const callId = this.renderer.info.calls;
  36890. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  36891. if ( cacheKeyData.callId !== callId ) {
  36892. const environmentNode = this.getEnvironmentNode( scene );
  36893. const fogNode = this.getFogNode( scene );
  36894. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  36895. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  36896. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  36897. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  36898. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  36899. cacheKeyData.callId = callId;
  36900. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  36901. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  36902. _cacheKeyValues.length = 0;
  36903. }
  36904. _chainKeys$2.length = 0;
  36905. return cacheKeyData.cacheKey;
  36906. }
  36907. /**
  36908. * A boolean that indicates whether tone mapping should be enabled
  36909. * or not.
  36910. *
  36911. * @type {boolean}
  36912. */
  36913. get isToneMappingState() {
  36914. return this.renderer.getRenderTarget() ? false : true;
  36915. }
  36916. /**
  36917. * If a scene background is configured, this method makes sure to
  36918. * represent the background with a corresponding node-based implementation.
  36919. *
  36920. * @param {Scene} scene - The scene.
  36921. */
  36922. updateBackground( scene ) {
  36923. const sceneData = this.get( scene );
  36924. const background = scene.background;
  36925. if ( background ) {
  36926. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  36927. if ( sceneData.background !== background || forceUpdate ) {
  36928. const backgroundNode = this.getCacheNode( 'background', background, () => {
  36929. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  36930. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  36931. return pmremTexture( background );
  36932. } else {
  36933. let envMap;
  36934. if ( background.isCubeTexture === true ) {
  36935. envMap = cubeTexture( background );
  36936. } else {
  36937. envMap = texture( background );
  36938. }
  36939. return cubeMapNode( envMap );
  36940. }
  36941. } else if ( background.isTexture === true ) {
  36942. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  36943. } else if ( background.isColor !== true ) {
  36944. error( 'WebGPUNodes: Unsupported background configuration.', background );
  36945. }
  36946. }, forceUpdate );
  36947. sceneData.backgroundNode = backgroundNode;
  36948. sceneData.background = background;
  36949. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  36950. }
  36951. } else if ( sceneData.backgroundNode ) {
  36952. delete sceneData.backgroundNode;
  36953. delete sceneData.background;
  36954. }
  36955. }
  36956. /**
  36957. * This method is part of the caching of nodes which are used to represents the
  36958. * scene's background, fog or environment.
  36959. *
  36960. * @param {string} type - The type of object to cache.
  36961. * @param {Object} object - The object.
  36962. * @param {Function} callback - A callback that produces a node representation for the given object.
  36963. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  36964. * @return {Node} The node representation.
  36965. */
  36966. getCacheNode( type, object, callback, forceUpdate = false ) {
  36967. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  36968. let node = nodeCache.get( object );
  36969. if ( node === undefined || forceUpdate ) {
  36970. node = callback();
  36971. nodeCache.set( object, node );
  36972. }
  36973. return node;
  36974. }
  36975. /**
  36976. * If a scene fog is configured, this method makes sure to
  36977. * represent the fog with a corresponding node-based implementation.
  36978. *
  36979. * @param {Scene} scene - The scene.
  36980. */
  36981. updateFog( scene ) {
  36982. const sceneData = this.get( scene );
  36983. const sceneFog = scene.fog;
  36984. if ( sceneFog ) {
  36985. if ( sceneData.fog !== sceneFog ) {
  36986. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  36987. if ( sceneFog.isFogExp2 ) {
  36988. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36989. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  36990. return fog( color, densityFogFactor( density ) );
  36991. } else if ( sceneFog.isFog ) {
  36992. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36993. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  36994. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  36995. return fog( color, rangeFogFactor( near, far ) );
  36996. } else {
  36997. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  36998. }
  36999. } );
  37000. sceneData.fogNode = fogNode;
  37001. sceneData.fog = sceneFog;
  37002. }
  37003. } else {
  37004. delete sceneData.fogNode;
  37005. delete sceneData.fog;
  37006. }
  37007. }
  37008. /**
  37009. * If a scene environment is configured, this method makes sure to
  37010. * represent the environment with a corresponding node-based implementation.
  37011. *
  37012. * @param {Scene} scene - The scene.
  37013. */
  37014. updateEnvironment( scene ) {
  37015. const sceneData = this.get( scene );
  37016. const environment = scene.environment;
  37017. if ( environment ) {
  37018. if ( sceneData.environment !== environment ) {
  37019. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  37020. if ( environment.isCubeTexture === true ) {
  37021. return cubeTexture( environment );
  37022. } else if ( environment.isTexture === true ) {
  37023. return texture( environment );
  37024. } else {
  37025. error( 'Nodes: Unsupported environment configuration.', environment );
  37026. }
  37027. } );
  37028. sceneData.environmentNode = environmentNode;
  37029. sceneData.environment = environment;
  37030. }
  37031. } else if ( sceneData.environmentNode ) {
  37032. delete sceneData.environmentNode;
  37033. delete sceneData.environment;
  37034. }
  37035. }
  37036. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37037. const nodeFrame = this.nodeFrame;
  37038. nodeFrame.renderer = renderer;
  37039. nodeFrame.scene = scene;
  37040. nodeFrame.object = object;
  37041. nodeFrame.camera = camera;
  37042. nodeFrame.material = material;
  37043. return nodeFrame;
  37044. }
  37045. getNodeFrameForRender( renderObject ) {
  37046. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37047. }
  37048. /**
  37049. * Returns the current output cache key.
  37050. *
  37051. * @return {string} The output cache key.
  37052. */
  37053. getOutputCacheKey() {
  37054. const renderer = this.renderer;
  37055. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  37056. }
  37057. /**
  37058. * Checks if the output configuration (tone mapping and color space) for
  37059. * the given target has changed.
  37060. *
  37061. * @param {Texture} outputTarget - The output target.
  37062. * @return {boolean} Whether the output configuration has changed or not.
  37063. */
  37064. hasOutputChange( outputTarget ) {
  37065. const cacheKey = _outputNodeMap.get( outputTarget );
  37066. return cacheKey !== this.getOutputCacheKey();
  37067. }
  37068. /**
  37069. * Returns a node that represents the output configuration (tone mapping and
  37070. * color space) for the current target.
  37071. *
  37072. * @param {Texture} outputTarget - The output target.
  37073. * @return {Node} The output node.
  37074. */
  37075. getOutputNode( outputTarget ) {
  37076. const renderer = this.renderer;
  37077. const cacheKey = this.getOutputCacheKey();
  37078. const output = outputTarget.isArrayTexture ?
  37079. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  37080. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37081. _outputNodeMap.set( outputTarget, cacheKey );
  37082. return output;
  37083. }
  37084. /**
  37085. * Triggers the call of `updateBefore()` methods
  37086. * for all nodes of the given render object.
  37087. *
  37088. * @param {RenderObject} renderObject - The render object.
  37089. */
  37090. updateBefore( renderObject ) {
  37091. const nodeBuilder = renderObject.getNodeBuilderState();
  37092. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37093. // update frame state for each node
  37094. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37095. }
  37096. }
  37097. /**
  37098. * Triggers the call of `updateAfter()` methods
  37099. * for all nodes of the given render object.
  37100. *
  37101. * @param {RenderObject} renderObject - The render object.
  37102. */
  37103. updateAfter( renderObject ) {
  37104. const nodeBuilder = renderObject.getNodeBuilderState();
  37105. for ( const node of nodeBuilder.updateAfterNodes ) {
  37106. // update frame state for each node
  37107. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37108. }
  37109. }
  37110. /**
  37111. * Triggers the call of `update()` methods
  37112. * for all nodes of the given compute node.
  37113. *
  37114. * @param {Node} computeNode - The compute node.
  37115. */
  37116. updateForCompute( computeNode ) {
  37117. const nodeFrame = this.getNodeFrame();
  37118. const nodeBuilder = this.getForCompute( computeNode );
  37119. for ( const node of nodeBuilder.updateNodes ) {
  37120. nodeFrame.updateNode( node );
  37121. }
  37122. }
  37123. /**
  37124. * Triggers the call of `update()` methods
  37125. * for all nodes of the given compute node.
  37126. *
  37127. * @param {RenderObject} renderObject - The render object.
  37128. */
  37129. updateForRender( renderObject ) {
  37130. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37131. const nodeBuilder = renderObject.getNodeBuilderState();
  37132. for ( const node of nodeBuilder.updateNodes ) {
  37133. nodeFrame.updateNode( node );
  37134. }
  37135. }
  37136. /**
  37137. * Returns `true` if the given render object requires a refresh.
  37138. *
  37139. * @param {RenderObject} renderObject - The render object.
  37140. * @return {boolean} Whether the given render object requires a refresh or not.
  37141. */
  37142. needsRefresh( renderObject ) {
  37143. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37144. const monitor = renderObject.getMonitor();
  37145. return monitor.needsRefresh( renderObject, nodeFrame );
  37146. }
  37147. /**
  37148. * Frees the internal resources.
  37149. */
  37150. dispose() {
  37151. super.dispose();
  37152. this.nodeFrame = new NodeFrame();
  37153. this.nodeBuilderCache = new Map();
  37154. this.cacheLib = {};
  37155. }
  37156. }
  37157. const _plane = /*@__PURE__*/ new Plane();
  37158. /**
  37159. * Represents the state that is used to perform clipping via clipping planes.
  37160. * There is a default clipping context for each render context. When the
  37161. * scene holds instances of `ClippingGroup`, there will be a context for each
  37162. * group.
  37163. *
  37164. * @private
  37165. */
  37166. class ClippingContext {
  37167. /**
  37168. * Constructs a new clipping context.
  37169. *
  37170. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  37171. */
  37172. constructor( parentContext = null ) {
  37173. /**
  37174. * The clipping context's version.
  37175. *
  37176. * @type {number}
  37177. * @readonly
  37178. */
  37179. this.version = 0;
  37180. /**
  37181. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  37182. *
  37183. * @type {?boolean}
  37184. * @default null
  37185. */
  37186. this.clipIntersection = null;
  37187. /**
  37188. * The clipping context's cache key.
  37189. *
  37190. * @type {string}
  37191. */
  37192. this.cacheKey = '';
  37193. /**
  37194. * Whether the shadow pass is active or not.
  37195. *
  37196. * @type {boolean}
  37197. * @default false
  37198. */
  37199. this.shadowPass = false;
  37200. /**
  37201. * The view normal matrix.
  37202. *
  37203. * @type {Matrix3}
  37204. */
  37205. this.viewNormalMatrix = new Matrix3();
  37206. /**
  37207. * Internal cache for maintaining clipping contexts.
  37208. *
  37209. * @type {WeakMap<ClippingGroup,ClippingContext>}
  37210. */
  37211. this.clippingGroupContexts = new WeakMap();
  37212. /**
  37213. * The intersection planes.
  37214. *
  37215. * @type {Array<Vector4>}
  37216. */
  37217. this.intersectionPlanes = [];
  37218. /**
  37219. * The intersection planes.
  37220. *
  37221. * @type {Array<Vector4>}
  37222. */
  37223. this.unionPlanes = [];
  37224. /**
  37225. * The version of the clipping context's parent context.
  37226. *
  37227. * @type {?number}
  37228. * @readonly
  37229. */
  37230. this.parentVersion = null;
  37231. if ( parentContext !== null ) {
  37232. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  37233. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  37234. this.shadowPass = parentContext.shadowPass;
  37235. this.viewMatrix = parentContext.viewMatrix;
  37236. }
  37237. }
  37238. /**
  37239. * Projects the given source clipping planes and writes the result into the
  37240. * destination array.
  37241. *
  37242. * @param {Array<Plane>} source - The source clipping planes.
  37243. * @param {Array<Vector4>} destination - The destination.
  37244. * @param {number} offset - The offset.
  37245. */
  37246. projectPlanes( source, destination, offset ) {
  37247. const l = source.length;
  37248. for ( let i = 0; i < l; i ++ ) {
  37249. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  37250. const v = destination[ offset + i ];
  37251. const normal = _plane.normal;
  37252. v.x = - normal.x;
  37253. v.y = - normal.y;
  37254. v.z = - normal.z;
  37255. v.w = _plane.constant;
  37256. }
  37257. }
  37258. /**
  37259. * Updates the root clipping context of a scene.
  37260. *
  37261. * @param {Scene} scene - The scene.
  37262. * @param {Camera} camera - The camera that is used to render the scene.
  37263. */
  37264. updateGlobal( scene, camera ) {
  37265. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  37266. this.viewMatrix = camera.matrixWorldInverse;
  37267. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  37268. }
  37269. /**
  37270. * Updates the clipping context.
  37271. *
  37272. * @param {ClippingContext} parentContext - The parent context.
  37273. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  37274. */
  37275. update( parentContext, clippingGroup ) {
  37276. let update = false;
  37277. if ( parentContext.version !== this.parentVersion ) {
  37278. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  37279. this.unionPlanes = Array.from( parentContext.unionPlanes );
  37280. this.parentVersion = parentContext.version;
  37281. }
  37282. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  37283. this.clipIntersection = clippingGroup.clipIntersection;
  37284. if ( this.clipIntersection ) {
  37285. this.unionPlanes.length = parentContext.unionPlanes.length;
  37286. } else {
  37287. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  37288. }
  37289. }
  37290. const srcClippingPlanes = clippingGroup.clippingPlanes;
  37291. const l = srcClippingPlanes.length;
  37292. let dstClippingPlanes;
  37293. let offset;
  37294. if ( this.clipIntersection ) {
  37295. dstClippingPlanes = this.intersectionPlanes;
  37296. offset = parentContext.intersectionPlanes.length;
  37297. } else {
  37298. dstClippingPlanes = this.unionPlanes;
  37299. offset = parentContext.unionPlanes.length;
  37300. }
  37301. if ( dstClippingPlanes.length !== offset + l ) {
  37302. dstClippingPlanes.length = offset + l;
  37303. for ( let i = 0; i < l; i ++ ) {
  37304. dstClippingPlanes[ offset + i ] = new Vector4();
  37305. }
  37306. update = true;
  37307. }
  37308. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  37309. if ( update ) {
  37310. this.version ++;
  37311. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  37312. }
  37313. }
  37314. /**
  37315. * Returns a clipping context for the given clipping group.
  37316. *
  37317. * @param {ClippingGroup} clippingGroup - The clipping group.
  37318. * @return {ClippingContext} The clipping context.
  37319. */
  37320. getGroupContext( clippingGroup ) {
  37321. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  37322. let context = this.clippingGroupContexts.get( clippingGroup );
  37323. if ( context === undefined ) {
  37324. context = new ClippingContext( this );
  37325. this.clippingGroupContexts.set( clippingGroup, context );
  37326. }
  37327. context.update( this, clippingGroup );
  37328. return context;
  37329. }
  37330. /**
  37331. * The count of union clipping planes.
  37332. *
  37333. * @type {number}
  37334. * @readonly
  37335. */
  37336. get unionClippingCount() {
  37337. return this.unionPlanes.length;
  37338. }
  37339. }
  37340. /**
  37341. * This module is used to represent render bundles inside the renderer
  37342. * for further processing.
  37343. *
  37344. * @private
  37345. */
  37346. class RenderBundle {
  37347. /**
  37348. * Constructs a new bundle group.
  37349. *
  37350. * @param {BundleGroup} bundleGroup - The bundle group.
  37351. * @param {Camera} camera - The camera the bundle group is rendered with.
  37352. */
  37353. constructor( bundleGroup, camera ) {
  37354. this.bundleGroup = bundleGroup;
  37355. this.camera = camera;
  37356. }
  37357. }
  37358. const _chainKeys$1 = [];
  37359. /**
  37360. * This renderer module manages render bundles.
  37361. *
  37362. * @private
  37363. */
  37364. class RenderBundles {
  37365. /**
  37366. * Constructs a new render bundle management component.
  37367. */
  37368. constructor() {
  37369. /**
  37370. * A chain map for maintaining the render bundles.
  37371. *
  37372. * @type {ChainMap}
  37373. */
  37374. this.bundles = new ChainMap();
  37375. }
  37376. /**
  37377. * Returns a render bundle for the given bundle group and camera.
  37378. *
  37379. * @param {BundleGroup} bundleGroup - The bundle group.
  37380. * @param {Camera} camera - The camera the bundle group is rendered with.
  37381. * @return {RenderBundle} The render bundle.
  37382. */
  37383. get( bundleGroup, camera ) {
  37384. const bundles = this.bundles;
  37385. _chainKeys$1[ 0 ] = bundleGroup;
  37386. _chainKeys$1[ 1 ] = camera;
  37387. let bundle = bundles.get( _chainKeys$1 );
  37388. if ( bundle === undefined ) {
  37389. bundle = new RenderBundle( bundleGroup, camera );
  37390. bundles.set( _chainKeys$1, bundle );
  37391. }
  37392. _chainKeys$1.length = 0;
  37393. return bundle;
  37394. }
  37395. /**
  37396. * Frees all internal resources.
  37397. */
  37398. dispose() {
  37399. this.bundles = new ChainMap();
  37400. }
  37401. }
  37402. /**
  37403. * The purpose of a node library is to assign node implementations
  37404. * to existing library features. In `WebGPURenderer` lights, materials
  37405. * which are not based on `NodeMaterial` as well as tone mapping techniques
  37406. * are implemented with node-based modules.
  37407. *
  37408. * @private
  37409. */
  37410. class NodeLibrary {
  37411. /**
  37412. * Constructs a new node library.
  37413. */
  37414. constructor() {
  37415. /**
  37416. * A weak map that maps lights to light nodes.
  37417. *
  37418. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  37419. */
  37420. this.lightNodes = new WeakMap();
  37421. /**
  37422. * A map that maps materials to node materials.
  37423. *
  37424. * @type {Map<string,NodeMaterial.constructor>}
  37425. */
  37426. this.materialNodes = new Map();
  37427. /**
  37428. * A map that maps tone mapping techniques (constants)
  37429. * to tone mapping node functions.
  37430. *
  37431. * @type {Map<number,Function>}
  37432. */
  37433. this.toneMappingNodes = new Map();
  37434. }
  37435. /**
  37436. * Returns a matching node material instance for the given material object.
  37437. *
  37438. * This method also assigns/copies the properties of the given material object
  37439. * to the node material. This is done to make sure the current material
  37440. * configuration carries over to the node version.
  37441. *
  37442. * @param {Material} material - A material.
  37443. * @return {NodeMaterial} The corresponding node material.
  37444. */
  37445. fromMaterial( material ) {
  37446. if ( material.isNodeMaterial ) return material;
  37447. let nodeMaterial = null;
  37448. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37449. if ( nodeMaterialClass !== null ) {
  37450. nodeMaterial = new nodeMaterialClass();
  37451. for ( const key in material ) {
  37452. nodeMaterial[ key ] = material[ key ];
  37453. }
  37454. }
  37455. return nodeMaterial;
  37456. }
  37457. /**
  37458. * Adds a tone mapping node function for a tone mapping technique (constant).
  37459. *
  37460. * @param {Function} toneMappingNode - The tone mapping node function.
  37461. * @param {number} toneMapping - The tone mapping.
  37462. */
  37463. addToneMapping( toneMappingNode, toneMapping ) {
  37464. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37465. }
  37466. /**
  37467. * Returns a tone mapping node function for a tone mapping technique (constant).
  37468. *
  37469. * @param {number} toneMapping - The tone mapping.
  37470. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  37471. */
  37472. getToneMappingFunction( toneMapping ) {
  37473. return this.toneMappingNodes.get( toneMapping ) || null;
  37474. }
  37475. /**
  37476. * Returns a node material class definition for a material type.
  37477. *
  37478. * @param {string} materialType - The material type.
  37479. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  37480. */
  37481. getMaterialNodeClass( materialType ) {
  37482. return this.materialNodes.get( materialType ) || null;
  37483. }
  37484. /**
  37485. * Adds a node material class definition for a given material type.
  37486. *
  37487. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  37488. * @param {string} materialClassType - The material type.
  37489. */
  37490. addMaterial( materialNodeClass, materialClassType ) {
  37491. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  37492. }
  37493. /**
  37494. * Returns a light node class definition for a light class definition.
  37495. *
  37496. * @param {Light.constructor} light - The light class definition.
  37497. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  37498. */
  37499. getLightNodeClass( light ) {
  37500. return this.lightNodes.get( light ) || null;
  37501. }
  37502. /**
  37503. * Adds a light node class definition for a given light class definition.
  37504. *
  37505. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  37506. * @param {Light.constructor} lightClass - The light class definition.
  37507. */
  37508. addLight( lightNodeClass, lightClass ) {
  37509. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37510. }
  37511. /**
  37512. * Adds a node class definition for the given type to the provided type library.
  37513. *
  37514. * @param {Node.constructor} nodeClass - The node class definition.
  37515. * @param {number|string} type - The object type.
  37516. * @param {Map<number|string,Node.constructor>} library - The type library.
  37517. */
  37518. addType( nodeClass, type, library ) {
  37519. if ( library.has( type ) ) {
  37520. warn( `Redefinition of node ${ type }` );
  37521. return;
  37522. }
  37523. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37524. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37525. library.set( type, nodeClass );
  37526. }
  37527. /**
  37528. * Adds a node class definition for the given class definition to the provided type library.
  37529. *
  37530. * @param {Node.constructor} nodeClass - The node class definition.
  37531. * @param {Node.constructor} baseClass - The class definition.
  37532. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  37533. */
  37534. addClass( nodeClass, baseClass, library ) {
  37535. if ( library.has( baseClass ) ) {
  37536. warn( `Redefinition of node ${ baseClass.name }` );
  37537. return;
  37538. }
  37539. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37540. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37541. library.set( baseClass, nodeClass );
  37542. }
  37543. }
  37544. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37545. const _chainKeys = [];
  37546. /**
  37547. * This renderer module manages the lights nodes which are unique
  37548. * per scene and camera combination.
  37549. *
  37550. * The lights node itself is later configured in the render list
  37551. * with the actual lights from the scene.
  37552. *
  37553. * @private
  37554. * @augments ChainMap
  37555. */
  37556. class Lighting extends ChainMap {
  37557. /**
  37558. * Constructs a lighting management component.
  37559. */
  37560. constructor() {
  37561. super();
  37562. }
  37563. /**
  37564. * Creates a new lights node for the given array of lights.
  37565. *
  37566. * @param {Array<Light>} lights - The render object.
  37567. * @return {LightsNode} The lights node.
  37568. */
  37569. createNode( lights = [] ) {
  37570. return new LightsNode().setLights( lights );
  37571. }
  37572. /**
  37573. * Returns a lights node for the given scene and camera.
  37574. *
  37575. * @param {Scene} scene - The scene.
  37576. * @param {Camera} camera - The camera.
  37577. * @return {LightsNode} The lights node.
  37578. */
  37579. getNode( scene, camera ) {
  37580. // ignore post-processing
  37581. if ( scene.isQuadMesh ) return _defaultLights;
  37582. _chainKeys[ 0 ] = scene;
  37583. _chainKeys[ 1 ] = camera;
  37584. let node = this.get( _chainKeys );
  37585. if ( node === undefined ) {
  37586. node = this.createNode();
  37587. this.set( _chainKeys, node );
  37588. }
  37589. _chainKeys.length = 0;
  37590. return node;
  37591. }
  37592. }
  37593. /**
  37594. * A special type of render target that is used when rendering
  37595. * with the WebXR Device API.
  37596. *
  37597. * @private
  37598. * @augments RenderTarget
  37599. */
  37600. class XRRenderTarget extends RenderTarget {
  37601. /**
  37602. * Constructs a new XR render target.
  37603. *
  37604. * @param {number} [width=1] - The width of the render target.
  37605. * @param {number} [height=1] - The height of the render target.
  37606. * @param {Object} [options={}] - The configuration options.
  37607. */
  37608. constructor( width = 1, height = 1, options = {} ) {
  37609. super( width, height, options );
  37610. /**
  37611. * This flag can be used for type testing.
  37612. *
  37613. * @type {boolean}
  37614. * @readonly
  37615. * @default true
  37616. */
  37617. this.isXRRenderTarget = true;
  37618. /**
  37619. * Whether the attachments of the render target
  37620. * are defined by external textures. This flag is
  37621. * set to `true` when using the WebXR Layers API.
  37622. *
  37623. * @private
  37624. * @type {boolean}
  37625. * @default false
  37626. */
  37627. this._hasExternalTextures = false;
  37628. /**
  37629. * Whether a depth buffer should automatically be allocated
  37630. * for this XR render target or not.
  37631. *
  37632. * Allocating a depth buffer is the default behavior of XR render
  37633. * targets. However, when using the WebXR Layers API, this flag
  37634. * must be set to `false` when the `ignoreDepthValues` property of
  37635. * the projection layers evaluates to `false`.
  37636. *
  37637. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  37638. *
  37639. * @private
  37640. * @type {boolean}
  37641. * @default true
  37642. */
  37643. this._autoAllocateDepthBuffer = true;
  37644. /**
  37645. * Whether this render target is associated with a XRWebGLLayer.
  37646. *
  37647. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  37648. * this means that you don't have access to its bound color,
  37649. * stencil and depth buffers. We need to handle this framebuffer
  37650. * differently since its textures are always bound.
  37651. *
  37652. * @private
  37653. * @type {boolean}
  37654. * @default false
  37655. * */
  37656. this._isOpaqueFramebuffer = false;
  37657. }
  37658. copy( source ) {
  37659. super.copy( source );
  37660. this._hasExternalTextures = source._hasExternalTextures;
  37661. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  37662. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  37663. return this;
  37664. }
  37665. }
  37666. const _cameraLPos = /*@__PURE__*/ new Vector3();
  37667. const _cameraRPos = /*@__PURE__*/ new Vector3();
  37668. /**
  37669. * The XR manager is built on top of the WebXR Device API to
  37670. * manage XR sessions with `WebGPURenderer`.
  37671. *
  37672. * XR is currently only supported with a WebGL 2 backend.
  37673. *
  37674. * @augments EventDispatcher
  37675. */
  37676. class XRManager extends EventDispatcher {
  37677. /**
  37678. * Constructs a new XR manager.
  37679. *
  37680. * @param {Renderer} renderer - The renderer.
  37681. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  37682. */
  37683. constructor( renderer, multiview = false ) {
  37684. super();
  37685. /**
  37686. * This flag globally enables XR rendering.
  37687. *
  37688. * @type {boolean}
  37689. * @default false
  37690. */
  37691. this.enabled = false;
  37692. /**
  37693. * Whether the XR device is currently presenting or not.
  37694. *
  37695. * @type {boolean}
  37696. * @default false
  37697. * @readonly
  37698. */
  37699. this.isPresenting = false;
  37700. /**
  37701. * Whether the XR camera should automatically be updated or not.
  37702. *
  37703. * @type {boolean}
  37704. * @default true
  37705. */
  37706. this.cameraAutoUpdate = true;
  37707. /**
  37708. * The renderer.
  37709. *
  37710. * @private
  37711. * @type {Renderer}
  37712. */
  37713. this._renderer = renderer;
  37714. // camera
  37715. /**
  37716. * Represents the camera for the left eye.
  37717. *
  37718. * @private
  37719. * @type {PerspectiveCamera}
  37720. */
  37721. this._cameraL = new PerspectiveCamera();
  37722. this._cameraL.viewport = new Vector4();
  37723. /**
  37724. * Represents the camera for the right eye.
  37725. *
  37726. * @private
  37727. * @type {PerspectiveCamera}
  37728. */
  37729. this._cameraR = new PerspectiveCamera();
  37730. this._cameraR.viewport = new Vector4();
  37731. /**
  37732. * A list of cameras used for rendering the XR views.
  37733. *
  37734. * @private
  37735. * @type {Array<Camera>}
  37736. */
  37737. this._cameras = [ this._cameraL, this._cameraR ];
  37738. /**
  37739. * The main XR camera.
  37740. *
  37741. * @private
  37742. * @type {ArrayCamera}
  37743. */
  37744. this._cameraXR = new ArrayCamera();
  37745. /**
  37746. * The current near value of the XR camera.
  37747. *
  37748. * @private
  37749. * @type {?number}
  37750. * @default null
  37751. */
  37752. this._currentDepthNear = null;
  37753. /**
  37754. * The current far value of the XR camera.
  37755. *
  37756. * @private
  37757. * @type {?number}
  37758. * @default null
  37759. */
  37760. this._currentDepthFar = null;
  37761. /**
  37762. * A list of WebXR controllers requested by the application.
  37763. *
  37764. * @private
  37765. * @type {Array<WebXRController>}
  37766. */
  37767. this._controllers = [];
  37768. /**
  37769. * A list of XR input source. Each input source belongs to
  37770. * an instance of WebXRController.
  37771. *
  37772. * @private
  37773. * @type {Array<XRInputSource?>}
  37774. */
  37775. this._controllerInputSources = [];
  37776. /**
  37777. * The XR render target that represents the rendering destination
  37778. * during an active XR session.
  37779. *
  37780. * @private
  37781. * @type {?RenderTarget}
  37782. * @default null
  37783. */
  37784. this._xrRenderTarget = null;
  37785. /**
  37786. * An array holding all the non-projection layers
  37787. *
  37788. * @private
  37789. * @type {Array<Object>}
  37790. * @default []
  37791. */
  37792. this._layers = [];
  37793. /**
  37794. * Whether the XR session uses layers.
  37795. *
  37796. * @type {boolean}
  37797. * @default false
  37798. */
  37799. this._sessionUsesLayers = false;
  37800. /**
  37801. * Whether the device supports binding gl objects.
  37802. *
  37803. * @private
  37804. * @type {boolean}
  37805. * @readonly
  37806. */
  37807. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  37808. this._frameBufferTargets = null;
  37809. /**
  37810. * Helper function to create native WebXR Layer.
  37811. *
  37812. * @private
  37813. * @type {Function}
  37814. */
  37815. this._createXRLayer = createXRLayer.bind( this );
  37816. /**
  37817. * The current WebGL context.
  37818. *
  37819. * @private
  37820. * @type {?WebGL2RenderingContext}
  37821. * @default null
  37822. */
  37823. this._gl = null;
  37824. /**
  37825. * The current animation context.
  37826. *
  37827. * @private
  37828. * @type {?Window}
  37829. * @default null
  37830. */
  37831. this._currentAnimationContext = null;
  37832. /**
  37833. * The current animation loop.
  37834. *
  37835. * @private
  37836. * @type {?Function}
  37837. * @default null
  37838. */
  37839. this._currentAnimationLoop = null;
  37840. /**
  37841. * The current pixel ratio.
  37842. *
  37843. * @private
  37844. * @type {?number}
  37845. * @default null
  37846. */
  37847. this._currentPixelRatio = null;
  37848. /**
  37849. * The current size of the renderer's canvas
  37850. * in logical pixel unit.
  37851. *
  37852. * @private
  37853. * @type {Vector2}
  37854. */
  37855. this._currentSize = new Vector2();
  37856. /**
  37857. * The default event listener for handling events inside a XR session.
  37858. *
  37859. * @private
  37860. * @type {Function}
  37861. */
  37862. this._onSessionEvent = onSessionEvent.bind( this );
  37863. /**
  37864. * The event listener for handling the end of a XR session.
  37865. *
  37866. * @private
  37867. * @type {Function}
  37868. */
  37869. this._onSessionEnd = onSessionEnd.bind( this );
  37870. /**
  37871. * The event listener for handling the `inputsourceschange` event.
  37872. *
  37873. * @private
  37874. * @type {Function}
  37875. */
  37876. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  37877. /**
  37878. * The animation loop which is used as a replacement for the default
  37879. * animation loop of the application. It is only used when a XR session
  37880. * is active.
  37881. *
  37882. * @private
  37883. * @type {Function}
  37884. */
  37885. this._onAnimationFrame = onAnimationFrame.bind( this );
  37886. /**
  37887. * The current XR reference space.
  37888. *
  37889. * @private
  37890. * @type {?XRReferenceSpace}
  37891. * @default null
  37892. */
  37893. this._referenceSpace = null;
  37894. /**
  37895. * The current XR reference space type.
  37896. *
  37897. * @private
  37898. * @type {XRReferenceSpaceType}
  37899. * @default 'local-floor'
  37900. */
  37901. this._referenceSpaceType = 'local-floor';
  37902. /**
  37903. * A custom reference space defined by the application.
  37904. *
  37905. * @private
  37906. * @type {?XRReferenceSpace}
  37907. * @default null
  37908. */
  37909. this._customReferenceSpace = null;
  37910. /**
  37911. * The framebuffer scale factor.
  37912. *
  37913. * @private
  37914. * @type {number}
  37915. * @default 1
  37916. */
  37917. this._framebufferScaleFactor = 1;
  37918. /**
  37919. * The foveation factor.
  37920. *
  37921. * @private
  37922. * @type {number}
  37923. * @default 1
  37924. */
  37925. this._foveation = 1.0;
  37926. /**
  37927. * A reference to the current XR session.
  37928. *
  37929. * @private
  37930. * @type {?XRSession}
  37931. * @default null
  37932. */
  37933. this._session = null;
  37934. /**
  37935. * A reference to the current XR base layer.
  37936. *
  37937. * @private
  37938. * @type {?XRWebGLLayer}
  37939. * @default null
  37940. */
  37941. this._glBaseLayer = null;
  37942. /**
  37943. * A reference to the current XR binding.
  37944. *
  37945. * @private
  37946. * @type {?XRWebGLBinding}
  37947. * @default null
  37948. */
  37949. this._glBinding = null;
  37950. /**
  37951. * A reference to the current XR projection layer.
  37952. *
  37953. * @private
  37954. * @type {?XRProjectionLayer}
  37955. * @default null
  37956. */
  37957. this._glProjLayer = null;
  37958. /**
  37959. * A reference to the current XR frame.
  37960. *
  37961. * @private
  37962. * @type {?XRFrame}
  37963. * @default null
  37964. */
  37965. this._xrFrame = null;
  37966. /**
  37967. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  37968. *
  37969. * Note: this does not represent XRSession explicitly requesting
  37970. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  37971. *
  37972. * @private
  37973. * @type {boolean}
  37974. * @readonly
  37975. */
  37976. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  37977. /**
  37978. * Whether the usage of multiview has been requested by the application or not.
  37979. *
  37980. * @private
  37981. * @type {boolean}
  37982. * @default false
  37983. * @readonly
  37984. */
  37985. this._useMultiviewIfPossible = multiview;
  37986. /**
  37987. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  37988. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  37989. *
  37990. * @private
  37991. * @type {boolean}
  37992. * @readonly
  37993. */
  37994. this._useMultiview = false;
  37995. }
  37996. /**
  37997. * Returns an instance of `THREE.Group` that represents the transformation
  37998. * of a XR controller in target ray space. The requested controller is defined
  37999. * by the given index.
  38000. *
  38001. * @param {number} index - The index of the XR controller.
  38002. * @return {Group} A group that represents the controller's transformation.
  38003. */
  38004. getController( index ) {
  38005. const controller = this._getController( index );
  38006. return controller.getTargetRaySpace();
  38007. }
  38008. /**
  38009. * Returns an instance of `THREE.Group` that represents the transformation
  38010. * of a XR controller in grip space. The requested controller is defined
  38011. * by the given index.
  38012. *
  38013. * @param {number} index - The index of the XR controller.
  38014. * @return {Group} A group that represents the controller's transformation.
  38015. */
  38016. getControllerGrip( index ) {
  38017. const controller = this._getController( index );
  38018. return controller.getGripSpace();
  38019. }
  38020. /**
  38021. * Returns an instance of `THREE.Group` that represents the transformation
  38022. * of a XR controller in hand space. The requested controller is defined
  38023. * by the given index.
  38024. *
  38025. * @param {number} index - The index of the XR controller.
  38026. * @return {Group} A group that represents the controller's transformation.
  38027. */
  38028. getHand( index ) {
  38029. const controller = this._getController( index );
  38030. return controller.getHandSpace();
  38031. }
  38032. /**
  38033. * Returns the foveation value.
  38034. *
  38035. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  38036. */
  38037. getFoveation() {
  38038. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  38039. return undefined;
  38040. }
  38041. return this._foveation;
  38042. }
  38043. /**
  38044. * Sets the foveation value.
  38045. *
  38046. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  38047. * and `1` means maximum foveation (the edges render at lower resolution).
  38048. */
  38049. setFoveation( foveation ) {
  38050. this._foveation = foveation;
  38051. if ( this._glProjLayer !== null ) {
  38052. this._glProjLayer.fixedFoveation = foveation;
  38053. }
  38054. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  38055. this._glBaseLayer.fixedFoveation = foveation;
  38056. }
  38057. }
  38058. /**
  38059. * Returns the framebuffer scale factor.
  38060. *
  38061. * @return {number} The framebuffer scale factor.
  38062. */
  38063. getFramebufferScaleFactor() {
  38064. return this._framebufferScaleFactor;
  38065. }
  38066. /**
  38067. * Sets the framebuffer scale factor.
  38068. *
  38069. * This method can not be used during a XR session.
  38070. *
  38071. * @param {number} factor - The framebuffer scale factor.
  38072. */
  38073. setFramebufferScaleFactor( factor ) {
  38074. this._framebufferScaleFactor = factor;
  38075. if ( this.isPresenting === true ) {
  38076. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  38077. }
  38078. }
  38079. /**
  38080. * Returns the reference space type.
  38081. *
  38082. * @return {XRReferenceSpaceType} The reference space type.
  38083. */
  38084. getReferenceSpaceType() {
  38085. return this._referenceSpaceType;
  38086. }
  38087. /**
  38088. * Sets the reference space type.
  38089. *
  38090. * This method can not be used during a XR session.
  38091. *
  38092. * @param {XRReferenceSpaceType} type - The reference space type.
  38093. */
  38094. setReferenceSpaceType( type ) {
  38095. this._referenceSpaceType = type;
  38096. if ( this.isPresenting === true ) {
  38097. warn( 'XRManager: Cannot change reference space type while presenting.' );
  38098. }
  38099. }
  38100. /**
  38101. * Returns the XR reference space.
  38102. *
  38103. * @return {XRReferenceSpace} The XR reference space.
  38104. */
  38105. getReferenceSpace() {
  38106. return this._customReferenceSpace || this._referenceSpace;
  38107. }
  38108. /**
  38109. * Sets a custom XR reference space.
  38110. *
  38111. * @param {XRReferenceSpace} space - The XR reference space.
  38112. */
  38113. setReferenceSpace( space ) {
  38114. this._customReferenceSpace = space;
  38115. }
  38116. /**
  38117. * Returns the XR camera.
  38118. *
  38119. * @return {ArrayCamera} The XR camera.
  38120. */
  38121. getCamera() {
  38122. return this._cameraXR;
  38123. }
  38124. /**
  38125. * Returns the environment blend mode from the current XR session.
  38126. *
  38127. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  38128. */
  38129. getEnvironmentBlendMode() {
  38130. if ( this._session !== null ) {
  38131. return this._session.environmentBlendMode;
  38132. }
  38133. }
  38134. /**
  38135. * Returns the current XR binding.
  38136. *
  38137. * Creates a new binding if needed and the browser is
  38138. * capable of doing so.
  38139. *
  38140. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  38141. */
  38142. getBinding() {
  38143. if ( this._glBinding === null && this._supportsGlBinding ) {
  38144. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  38145. }
  38146. return this._glBinding;
  38147. }
  38148. /**
  38149. * Returns the current XR frame.
  38150. *
  38151. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  38152. */
  38153. getFrame() {
  38154. return this._xrFrame;
  38155. }
  38156. /**
  38157. * Returns `true` if the engine renders to a multiview target.
  38158. *
  38159. * @return {boolean} Whether the engine renders to a multiview render target or not.
  38160. */
  38161. useMultiview() {
  38162. return this._useMultiview;
  38163. }
  38164. /**
  38165. * This method can be used in XR applications to create a quadratic layer that presents a separate
  38166. * rendered scene.
  38167. *
  38168. * @param {number} width - The width of the layer plane in world units.
  38169. * @param {number} height - The height of the layer plane in world units.
  38170. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38171. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38172. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38173. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38174. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38175. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38176. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38177. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  38178. */
  38179. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38180. const geometry = new PlaneGeometry( width, height );
  38181. const renderTarget = new XRRenderTarget(
  38182. pixelwidth,
  38183. pixelheight,
  38184. {
  38185. format: RGBAFormat,
  38186. type: UnsignedByteType,
  38187. depthTexture: new DepthTexture(
  38188. pixelwidth,
  38189. pixelheight,
  38190. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38191. undefined,
  38192. undefined,
  38193. undefined,
  38194. undefined,
  38195. undefined,
  38196. undefined,
  38197. attributes.stencil ? DepthStencilFormat : DepthFormat
  38198. ),
  38199. stencilBuffer: attributes.stencil,
  38200. resolveDepthBuffer: false,
  38201. resolveStencilBuffer: false
  38202. } );
  38203. renderTarget._autoAllocateDepthBuffer = true;
  38204. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38205. material.map = renderTarget.texture;
  38206. material.map.offset.y = 1;
  38207. material.map.repeat.y = -1;
  38208. const plane = new Mesh( geometry, material );
  38209. plane.position.copy( translation );
  38210. plane.quaternion.copy( quaternion );
  38211. const layer = {
  38212. type: 'quad',
  38213. width: width,
  38214. height: height,
  38215. translation: translation,
  38216. quaternion: quaternion,
  38217. pixelwidth: pixelwidth,
  38218. pixelheight: pixelheight,
  38219. plane: plane,
  38220. material: material,
  38221. rendercall: rendercall,
  38222. renderTarget: renderTarget };
  38223. this._layers.push( layer );
  38224. if ( this._session !== null ) {
  38225. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  38226. layer.plane.material.blending = CustomBlending;
  38227. layer.plane.material.blendEquation = AddEquation;
  38228. layer.plane.material.blendSrc = ZeroFactor;
  38229. layer.plane.material.blendDst = ZeroFactor;
  38230. layer.xrlayer = this._createXRLayer( layer );
  38231. const xrlayers = this._session.renderState.layers;
  38232. xrlayers.unshift( layer.xrlayer );
  38233. this._session.updateRenderState( { layers: xrlayers } );
  38234. } else {
  38235. renderTarget.isXRRenderTarget = false;
  38236. }
  38237. return plane;
  38238. }
  38239. /**
  38240. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  38241. * rendered scene.
  38242. *
  38243. * @param {number} radius - The radius of the cylinder in world units.
  38244. * @param {number} centralAngle - The central angle of the cylinder in radians.
  38245. * @param {number} aspectratio - The aspect ratio.
  38246. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  38247. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  38248. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  38249. * @param {number} pixelheight - The height of the layer's render target in pixels.
  38250. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  38251. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  38252. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38253. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  38254. */
  38255. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38256. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  38257. const renderTarget = new XRRenderTarget(
  38258. pixelwidth,
  38259. pixelheight,
  38260. {
  38261. format: RGBAFormat,
  38262. type: UnsignedByteType,
  38263. depthTexture: new DepthTexture(
  38264. pixelwidth,
  38265. pixelheight,
  38266. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38267. undefined,
  38268. undefined,
  38269. undefined,
  38270. undefined,
  38271. undefined,
  38272. undefined,
  38273. attributes.stencil ? DepthStencilFormat : DepthFormat
  38274. ),
  38275. stencilBuffer: attributes.stencil,
  38276. resolveDepthBuffer: false,
  38277. resolveStencilBuffer: false
  38278. } );
  38279. renderTarget._autoAllocateDepthBuffer = true;
  38280. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38281. material.map = renderTarget.texture;
  38282. material.map.offset.y = 1;
  38283. material.map.repeat.y = -1;
  38284. const plane = new Mesh( geometry, material );
  38285. plane.position.copy( translation );
  38286. plane.quaternion.copy( quaternion );
  38287. const layer = {
  38288. type: 'cylinder',
  38289. radius: radius,
  38290. centralAngle: centralAngle,
  38291. aspectratio: aspectratio,
  38292. translation: translation,
  38293. quaternion: quaternion,
  38294. pixelwidth: pixelwidth,
  38295. pixelheight: pixelheight,
  38296. plane: plane,
  38297. material: material,
  38298. rendercall: rendercall,
  38299. renderTarget: renderTarget };
  38300. this._layers.push( layer );
  38301. if ( this._session !== null ) {
  38302. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38303. layer.plane.material.blending = CustomBlending;
  38304. layer.plane.material.blendEquation = AddEquation;
  38305. layer.plane.material.blendSrc = ZeroFactor;
  38306. layer.plane.material.blendDst = ZeroFactor;
  38307. layer.xrlayer = this._createXRLayer( layer );
  38308. const xrlayers = this._session.renderState.layers;
  38309. xrlayers.unshift( layer.xrlayer );
  38310. this._session.updateRenderState( { layers: xrlayers } );
  38311. } else {
  38312. renderTarget.isXRRenderTarget = false;
  38313. }
  38314. return plane;
  38315. }
  38316. /**
  38317. * Renders the XR layers that have been previously added to the scene.
  38318. *
  38319. * This method is usually called in your animation loop before rendering
  38320. * the actual scene via `renderer.render( scene, camera );`.
  38321. */
  38322. renderLayers( ) {
  38323. const translationObject = new Vector3();
  38324. const quaternionObject = new Quaternion();
  38325. const renderer = this._renderer;
  38326. const wasPresenting = this.isPresenting;
  38327. const rendererOutputTarget = renderer.getOutputRenderTarget();
  38328. const rendererFramebufferTarget = renderer._frameBufferTarget;
  38329. this.isPresenting = false;
  38330. const rendererSize = new Vector2();
  38331. renderer.getSize( rendererSize );
  38332. const rendererQuad = renderer._quad;
  38333. for ( const layer of this._layers ) {
  38334. layer.renderTarget.isXRRenderTarget = this._session !== null;
  38335. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  38336. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  38337. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  38338. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  38339. renderer.backend.setXRRenderTargetTextures(
  38340. layer.renderTarget,
  38341. glSubImage.colorTexture,
  38342. undefined );
  38343. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  38344. renderer.setOutputRenderTarget( layer.renderTarget );
  38345. renderer.setRenderTarget( null );
  38346. renderer._frameBufferTarget = null;
  38347. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  38348. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  38349. if ( ! frameBufferTarget ) {
  38350. renderer._quad = new QuadMesh( new NodeMaterial() );
  38351. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  38352. } else {
  38353. renderer._frameBufferTarget = frameBufferTarget;
  38354. renderer._quad = quad;
  38355. }
  38356. layer.rendercall();
  38357. renderer._frameBufferTarget = null;
  38358. } else {
  38359. renderer.setRenderTarget( layer.renderTarget );
  38360. layer.rendercall();
  38361. }
  38362. }
  38363. renderer.setRenderTarget( null );
  38364. renderer.setOutputRenderTarget( rendererOutputTarget );
  38365. renderer._frameBufferTarget = rendererFramebufferTarget;
  38366. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  38367. renderer._quad = rendererQuad;
  38368. this.isPresenting = wasPresenting;
  38369. }
  38370. /**
  38371. * Returns the current XR session.
  38372. *
  38373. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  38374. */
  38375. getSession() {
  38376. return this._session;
  38377. }
  38378. /**
  38379. * After a XR session has been requested usually with one of the `*Button` modules, it
  38380. * is injected into the renderer with this method. This method triggers the start of
  38381. * the actual XR rendering.
  38382. *
  38383. * @async
  38384. * @param {XRSession} session - The XR session to set.
  38385. * @return {Promise} A Promise that resolves when the session has been set.
  38386. */
  38387. async setSession( session ) {
  38388. const renderer = this._renderer;
  38389. const backend = renderer.backend;
  38390. this._gl = renderer.getContext();
  38391. const gl = this._gl;
  38392. const attributes = gl.getContextAttributes();
  38393. this._session = session;
  38394. if ( session !== null ) {
  38395. 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.' );
  38396. session.addEventListener( 'select', this._onSessionEvent );
  38397. session.addEventListener( 'selectstart', this._onSessionEvent );
  38398. session.addEventListener( 'selectend', this._onSessionEvent );
  38399. session.addEventListener( 'squeeze', this._onSessionEvent );
  38400. session.addEventListener( 'squeezestart', this._onSessionEvent );
  38401. session.addEventListener( 'squeezeend', this._onSessionEvent );
  38402. session.addEventListener( 'end', this._onSessionEnd );
  38403. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38404. await backend.makeXRCompatible();
  38405. this._currentPixelRatio = renderer.getPixelRatio();
  38406. renderer.getSize( this._currentSize );
  38407. this._currentAnimationContext = renderer._animation.getContext();
  38408. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  38409. renderer._animation.stop();
  38410. //
  38411. if ( this._supportsLayers === true ) {
  38412. // default path using XRProjectionLayer
  38413. let depthFormat = null;
  38414. let depthType = null;
  38415. let glDepthFormat = null;
  38416. if ( renderer.depth ) {
  38417. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  38418. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  38419. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  38420. }
  38421. const projectionlayerInit = {
  38422. colorFormat: gl.RGBA8,
  38423. depthFormat: glDepthFormat,
  38424. scaleFactor: this._framebufferScaleFactor,
  38425. clearOnAccess: false
  38426. };
  38427. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  38428. projectionlayerInit.textureType = 'texture-array';
  38429. this._useMultiview = true;
  38430. }
  38431. this._glBinding = this.getBinding();
  38432. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  38433. const layersArray = [ glProjLayer ];
  38434. this._glProjLayer = glProjLayer;
  38435. renderer.setPixelRatio( 1 );
  38436. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  38437. const depth = this._useMultiview ? 2 : 1;
  38438. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  38439. this._xrRenderTarget = new XRRenderTarget(
  38440. glProjLayer.textureWidth,
  38441. glProjLayer.textureHeight,
  38442. {
  38443. format: RGBAFormat,
  38444. type: UnsignedByteType,
  38445. colorSpace: renderer.outputColorSpace,
  38446. depthTexture: depthTexture,
  38447. stencilBuffer: renderer.stencil,
  38448. samples: attributes.antialias ? 4 : 0,
  38449. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38450. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38451. depth: this._useMultiview ? 2 : 1,
  38452. multiview: this._useMultiview
  38453. } );
  38454. this._xrRenderTarget._hasExternalTextures = true;
  38455. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  38456. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  38457. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38458. if ( this._sessionUsesLayers ) {
  38459. // switch layers to native
  38460. for ( const layer of this._layers ) {
  38461. // change material so it "punches" out a hole to show the XR Layer.
  38462. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  38463. layer.plane.material.blending = CustomBlending;
  38464. layer.plane.material.blendEquation = AddEquation;
  38465. layer.plane.material.blendSrc = ZeroFactor;
  38466. layer.plane.material.blendDst = ZeroFactor;
  38467. layer.xrlayer = this._createXRLayer( layer );
  38468. layersArray.unshift( layer.xrlayer );
  38469. }
  38470. }
  38471. session.updateRenderState( { layers: layersArray } );
  38472. } else {
  38473. // fallback to XRWebGLLayer
  38474. const layerInit = {
  38475. antialias: renderer.currentSamples > 0,
  38476. alpha: true,
  38477. depth: renderer.depth,
  38478. stencil: renderer.stencil,
  38479. framebufferScaleFactor: this.getFramebufferScaleFactor()
  38480. };
  38481. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  38482. this._glBaseLayer = glBaseLayer;
  38483. session.updateRenderState( { baseLayer: glBaseLayer } );
  38484. renderer.setPixelRatio( 1 );
  38485. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  38486. this._xrRenderTarget = new XRRenderTarget(
  38487. glBaseLayer.framebufferWidth,
  38488. glBaseLayer.framebufferHeight,
  38489. {
  38490. format: RGBAFormat,
  38491. type: UnsignedByteType,
  38492. colorSpace: renderer.outputColorSpace,
  38493. stencilBuffer: renderer.stencil,
  38494. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38495. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38496. }
  38497. );
  38498. this._xrRenderTarget._isOpaqueFramebuffer = true;
  38499. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38500. }
  38501. //
  38502. this.setFoveation( this.getFoveation() );
  38503. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  38504. renderer._animation.setContext( session );
  38505. renderer._animation.start();
  38506. this.isPresenting = true;
  38507. this.dispatchEvent( { type: 'sessionstart' } );
  38508. }
  38509. }
  38510. /**
  38511. * This method is called by the renderer per frame and updates the XR camera
  38512. * and it sub cameras based on the given camera. The given camera is the "user"
  38513. * camera created on application level and used for non-XR rendering.
  38514. *
  38515. * @param {PerspectiveCamera} camera - The camera.
  38516. */
  38517. updateCamera( camera ) {
  38518. const session = this._session;
  38519. if ( session === null ) return;
  38520. const depthNear = camera.near;
  38521. const depthFar = camera.far;
  38522. const cameraXR = this._cameraXR;
  38523. const cameraL = this._cameraL;
  38524. const cameraR = this._cameraR;
  38525. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  38526. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  38527. cameraXR.isMultiViewCamera = this._useMultiview;
  38528. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  38529. // Note that the new renderState won't apply until the next frame. See #18320
  38530. session.updateRenderState( {
  38531. depthNear: cameraXR.near,
  38532. depthFar: cameraXR.far
  38533. } );
  38534. this._currentDepthNear = cameraXR.near;
  38535. this._currentDepthFar = cameraXR.far;
  38536. }
  38537. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  38538. cameraXR.layers.mask = camera.layers.mask | 0b110;
  38539. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  38540. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  38541. const parent = camera.parent;
  38542. const cameras = cameraXR.cameras;
  38543. updateCamera( cameraXR, parent );
  38544. for ( let i = 0; i < cameras.length; i ++ ) {
  38545. updateCamera( cameras[ i ], parent );
  38546. }
  38547. // update projection matrix for proper view frustum culling
  38548. if ( cameras.length === 2 ) {
  38549. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  38550. } else {
  38551. // assume single camera setup (AR)
  38552. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  38553. }
  38554. // update user camera and its children
  38555. updateUserCamera( camera, cameraXR, parent );
  38556. }
  38557. /**
  38558. * Returns a WebXR controller for the given controller index.
  38559. *
  38560. * @private
  38561. * @param {number} index - The controller index.
  38562. * @return {WebXRController} The XR controller.
  38563. */
  38564. _getController( index ) {
  38565. let controller = this._controllers[ index ];
  38566. if ( controller === undefined ) {
  38567. controller = new WebXRController();
  38568. this._controllers[ index ] = controller;
  38569. }
  38570. return controller;
  38571. }
  38572. }
  38573. /**
  38574. * Assumes 2 cameras that are parallel and share an X-axis, and that
  38575. * the cameras' projection and world matrices have already been set.
  38576. * And that near and far planes are identical for both cameras.
  38577. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  38578. *
  38579. * @param {ArrayCamera} camera - The camera to update.
  38580. * @param {PerspectiveCamera} cameraL - The left camera.
  38581. * @param {PerspectiveCamera} cameraR - The right camera.
  38582. */
  38583. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  38584. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  38585. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  38586. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  38587. const projL = cameraL.projectionMatrix.elements;
  38588. const projR = cameraR.projectionMatrix.elements;
  38589. // VR systems will have identical far and near planes, and
  38590. // most likely identical top and bottom frustum extents.
  38591. // Use the left camera for these values.
  38592. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  38593. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  38594. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  38595. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  38596. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  38597. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  38598. const left = near * leftFov;
  38599. const right = near * rightFov;
  38600. // Calculate the new camera's position offset from the
  38601. // left camera. xOffset should be roughly half `ipd`.
  38602. const zOffset = ipd / ( - leftFov + rightFov );
  38603. const xOffset = zOffset * - leftFov;
  38604. // TODO: Better way to apply this offset?
  38605. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  38606. camera.translateX( xOffset );
  38607. camera.translateZ( zOffset );
  38608. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  38609. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38610. // Check if the projection uses an infinite far plane.
  38611. if ( projL[ 10 ] === -1 ) {
  38612. // Use the projection matrix from the left eye.
  38613. // The camera offset is sufficient to include the view volumes
  38614. // of both eyes (assuming symmetric projections).
  38615. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  38616. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  38617. } else {
  38618. // Find the union of the frustum values of the cameras and scale
  38619. // the values so that the near plane's position does not change in world space,
  38620. // although must now be relative to the new union camera.
  38621. const near2 = near + zOffset;
  38622. const far2 = far + zOffset;
  38623. const left2 = left - xOffset;
  38624. const right2 = right + ( ipd - xOffset );
  38625. const top2 = topFov * far / far2 * near2;
  38626. const bottom2 = bottomFov * far / far2 * near2;
  38627. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  38628. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38629. }
  38630. }
  38631. /**
  38632. * Updates the world matrices for the given camera based on the parent 3D object.
  38633. *
  38634. * @inner
  38635. * @param {Camera} camera - The camera to update.
  38636. * @param {Object3D} parent - The parent 3D object.
  38637. */
  38638. function updateCamera( camera, parent ) {
  38639. if ( parent === null ) {
  38640. camera.matrixWorld.copy( camera.matrix );
  38641. } else {
  38642. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  38643. }
  38644. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38645. }
  38646. /**
  38647. * Updates the given camera with the transformation of the XR camera and parent object.
  38648. *
  38649. * @inner
  38650. * @param {Camera} camera - The camera to update.
  38651. * @param {ArrayCamera} cameraXR - The XR camera.
  38652. * @param {Object3D} parent - The parent 3D object.
  38653. */
  38654. function updateUserCamera( camera, cameraXR, parent ) {
  38655. if ( parent === null ) {
  38656. camera.matrix.copy( cameraXR.matrixWorld );
  38657. } else {
  38658. camera.matrix.copy( parent.matrixWorld );
  38659. camera.matrix.invert();
  38660. camera.matrix.multiply( cameraXR.matrixWorld );
  38661. }
  38662. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38663. camera.updateMatrixWorld( true );
  38664. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  38665. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  38666. if ( camera.isPerspectiveCamera ) {
  38667. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  38668. camera.zoom = 1;
  38669. }
  38670. }
  38671. function onSessionEvent( event ) {
  38672. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  38673. if ( controllerIndex === -1 ) {
  38674. return;
  38675. }
  38676. const controller = this._controllers[ controllerIndex ];
  38677. if ( controller !== undefined ) {
  38678. const referenceSpace = this.getReferenceSpace();
  38679. controller.update( event.inputSource, event.frame, referenceSpace );
  38680. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  38681. }
  38682. }
  38683. function onSessionEnd() {
  38684. const session = this._session;
  38685. const renderer = this._renderer;
  38686. session.removeEventListener( 'select', this._onSessionEvent );
  38687. session.removeEventListener( 'selectstart', this._onSessionEvent );
  38688. session.removeEventListener( 'selectend', this._onSessionEvent );
  38689. session.removeEventListener( 'squeeze', this._onSessionEvent );
  38690. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  38691. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  38692. session.removeEventListener( 'end', this._onSessionEnd );
  38693. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38694. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38695. const inputSource = this._controllerInputSources[ i ];
  38696. if ( inputSource === null ) continue;
  38697. this._controllerInputSources[ i ] = null;
  38698. this._controllers[ i ].disconnect( inputSource );
  38699. }
  38700. this._currentDepthNear = null;
  38701. this._currentDepthFar = null;
  38702. // restore framebuffer/rendering state
  38703. renderer._resetXRState();
  38704. this._session = null;
  38705. this._xrRenderTarget = null;
  38706. this._glBinding = null;
  38707. this._glBaseLayer = null;
  38708. this._glProjLayer = null;
  38709. // switch layers back to emulated
  38710. if ( this._sessionUsesLayers === true ) {
  38711. for ( const layer of this._layers ) {
  38712. // Recreate layer render target to reset state
  38713. layer.renderTarget = new XRRenderTarget(
  38714. layer.pixelwidth,
  38715. layer.pixelheight,
  38716. {
  38717. format: RGBAFormat,
  38718. type: UnsignedByteType,
  38719. depthTexture: new DepthTexture(
  38720. layer.pixelwidth,
  38721. layer.pixelheight,
  38722. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  38723. undefined,
  38724. undefined,
  38725. undefined,
  38726. undefined,
  38727. undefined,
  38728. undefined,
  38729. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  38730. ),
  38731. stencilBuffer: layer.stencilBuffer,
  38732. resolveDepthBuffer: false,
  38733. resolveStencilBuffer: false
  38734. } );
  38735. layer.renderTarget.isXRRenderTarget = false;
  38736. layer.plane.material = layer.material;
  38737. layer.material.map = layer.renderTarget.texture;
  38738. layer.material.map.offset.y = 1;
  38739. layer.material.map.repeat.y = -1;
  38740. delete layer.xrlayer;
  38741. }
  38742. }
  38743. //
  38744. this.isPresenting = false;
  38745. this._useMultiview = false;
  38746. renderer._animation.stop();
  38747. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  38748. renderer._animation.setContext( this._currentAnimationContext );
  38749. renderer._animation.start();
  38750. renderer.setPixelRatio( this._currentPixelRatio );
  38751. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  38752. this.dispatchEvent( { type: 'sessionend' } );
  38753. }
  38754. function onInputSourcesChange( event ) {
  38755. const controllers = this._controllers;
  38756. const controllerInputSources = this._controllerInputSources;
  38757. // Notify disconnected
  38758. for ( let i = 0; i < event.removed.length; i ++ ) {
  38759. const inputSource = event.removed[ i ];
  38760. const index = controllerInputSources.indexOf( inputSource );
  38761. if ( index >= 0 ) {
  38762. controllerInputSources[ index ] = null;
  38763. controllers[ index ].disconnect( inputSource );
  38764. }
  38765. }
  38766. // Notify connected
  38767. for ( let i = 0; i < event.added.length; i ++ ) {
  38768. const inputSource = event.added[ i ];
  38769. let controllerIndex = controllerInputSources.indexOf( inputSource );
  38770. if ( controllerIndex === -1 ) {
  38771. // Assign input source a controller that currently has no input source
  38772. for ( let i = 0; i < controllers.length; i ++ ) {
  38773. if ( i >= controllerInputSources.length ) {
  38774. controllerInputSources.push( inputSource );
  38775. controllerIndex = i;
  38776. break;
  38777. } else if ( controllerInputSources[ i ] === null ) {
  38778. controllerInputSources[ i ] = inputSource;
  38779. controllerIndex = i;
  38780. break;
  38781. }
  38782. }
  38783. // If all controllers do currently receive input we ignore new ones
  38784. if ( controllerIndex === -1 ) break;
  38785. }
  38786. const controller = controllers[ controllerIndex ];
  38787. if ( controller ) {
  38788. controller.connect( inputSource );
  38789. }
  38790. }
  38791. }
  38792. // Creation method for native WebXR layers
  38793. function createXRLayer( layer ) {
  38794. if ( layer.type === 'quad' ) {
  38795. return this._glBinding.createQuadLayer( {
  38796. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38797. width: layer.width / 2,
  38798. height: layer.height / 2,
  38799. space: this._referenceSpace,
  38800. viewPixelWidth: layer.pixelwidth,
  38801. viewPixelHeight: layer.pixelheight,
  38802. clearOnAccess: false
  38803. } );
  38804. } else {
  38805. return this._glBinding.createCylinderLayer( {
  38806. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38807. radius: layer.radius,
  38808. centralAngle: layer.centralAngle,
  38809. aspectRatio: layer.aspectRatio,
  38810. space: this._referenceSpace,
  38811. viewPixelWidth: layer.pixelwidth,
  38812. viewPixelHeight: layer.pixelheight,
  38813. clearOnAccess: false
  38814. } );
  38815. }
  38816. }
  38817. // Animation Loop
  38818. function onAnimationFrame( time, frame ) {
  38819. if ( frame === undefined ) return;
  38820. const cameraXR = this._cameraXR;
  38821. const renderer = this._renderer;
  38822. const backend = renderer.backend;
  38823. const glBaseLayer = this._glBaseLayer;
  38824. const referenceSpace = this.getReferenceSpace();
  38825. const pose = frame.getViewerPose( referenceSpace );
  38826. this._xrFrame = frame;
  38827. if ( pose !== null ) {
  38828. const views = pose.views;
  38829. if ( this._glBaseLayer !== null ) {
  38830. backend.setXRTarget( glBaseLayer.framebuffer );
  38831. }
  38832. let cameraXRNeedsUpdate = false;
  38833. // check if it's necessary to rebuild cameraXR's camera list
  38834. if ( views.length !== cameraXR.cameras.length ) {
  38835. cameraXR.cameras.length = 0;
  38836. cameraXRNeedsUpdate = true;
  38837. }
  38838. for ( let i = 0; i < views.length; i ++ ) {
  38839. const view = views[ i ];
  38840. let viewport;
  38841. if ( this._supportsLayers === true ) {
  38842. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  38843. viewport = glSubImage.viewport;
  38844. // For side-by-side projection, we only produce a single texture for both eyes.
  38845. if ( i === 0 ) {
  38846. backend.setXRRenderTargetTextures(
  38847. this._xrRenderTarget,
  38848. glSubImage.colorTexture,
  38849. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  38850. );
  38851. }
  38852. } else {
  38853. viewport = glBaseLayer.getViewport( view );
  38854. }
  38855. let camera = this._cameras[ i ];
  38856. if ( camera === undefined ) {
  38857. camera = new PerspectiveCamera();
  38858. camera.layers.enable( i );
  38859. camera.viewport = new Vector4();
  38860. this._cameras[ i ] = camera;
  38861. }
  38862. camera.matrix.fromArray( view.transform.matrix );
  38863. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38864. camera.projectionMatrix.fromArray( view.projectionMatrix );
  38865. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38866. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  38867. if ( i === 0 ) {
  38868. cameraXR.matrix.copy( camera.matrix );
  38869. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  38870. }
  38871. if ( cameraXRNeedsUpdate === true ) {
  38872. cameraXR.cameras.push( camera );
  38873. }
  38874. }
  38875. renderer.setOutputRenderTarget( this._xrRenderTarget );
  38876. }
  38877. //
  38878. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38879. const inputSource = this._controllerInputSources[ i ];
  38880. const controller = this._controllers[ i ];
  38881. if ( inputSource !== null && controller !== undefined ) {
  38882. controller.update( inputSource, frame, referenceSpace );
  38883. }
  38884. }
  38885. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  38886. if ( frame.detectedPlanes ) {
  38887. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  38888. }
  38889. this._xrFrame = null;
  38890. }
  38891. /**
  38892. * InspectorBase is the base class for all inspectors.
  38893. *
  38894. * @class InspectorBase
  38895. */
  38896. class InspectorBase {
  38897. /**
  38898. * Creates a new InspectorBase.
  38899. */
  38900. constructor() {
  38901. /**
  38902. * The renderer associated with this inspector.
  38903. *
  38904. * @type {WebGLRenderer}
  38905. * @private
  38906. */
  38907. this._renderer = null;
  38908. /**
  38909. * The current frame being processed.
  38910. *
  38911. * @type {Object}
  38912. */
  38913. this.currentFrame = null;
  38914. }
  38915. /**
  38916. * Returns the node frame for the current renderer.
  38917. *
  38918. * @return {Object} The node frame.
  38919. */
  38920. get nodeFrame() {
  38921. return this._renderer._nodes.nodeFrame;
  38922. }
  38923. /**
  38924. * Sets the renderer for this inspector.
  38925. *
  38926. * @param {WebGLRenderer} renderer - The renderer to associate with this inspector.
  38927. * @return {InspectorBase} This inspector instance.
  38928. */
  38929. setRenderer( renderer ) {
  38930. this._renderer = renderer;
  38931. return this;
  38932. }
  38933. /**
  38934. * Returns the renderer associated with this inspector.
  38935. *
  38936. * @return {WebGLRenderer} The associated renderer.
  38937. */
  38938. getRenderer() {
  38939. return this._renderer;
  38940. }
  38941. /**
  38942. * Initializes the inspector.
  38943. */
  38944. init() { }
  38945. /**
  38946. * Called when a frame begins.
  38947. */
  38948. begin() { }
  38949. /**
  38950. * Called when a frame ends.
  38951. */
  38952. finish() { }
  38953. /**
  38954. * Inspects a node.
  38955. *
  38956. * @param {Node} node - The node to inspect.
  38957. */
  38958. inspect( /*node*/ ) { }
  38959. /**
  38960. * When a compute operation is performed.
  38961. *
  38962. * @param {ComputeNode} computeNode - The compute node being executed.
  38963. * @param {number|Array<number>} dispatchSizeOrCount - The dispatch size or count.
  38964. */
  38965. computeAsync( /*computeNode, dispatchSizeOrCount*/ ) { }
  38966. /**
  38967. * Called when a compute operation begins.
  38968. *
  38969. * @param {string} uid - A unique identifier for the render context.
  38970. * @param {ComputeNode} computeNode - The compute node being executed.
  38971. */
  38972. beginCompute( /*uid, computeNode*/ ) { }
  38973. /**
  38974. * Called when a compute operation ends.
  38975. *
  38976. * @param {string} uid - A unique identifier for the render context.
  38977. * @param {ComputeNode} computeNode - The compute node being executed.
  38978. */
  38979. finishCompute( /*uid*/ ) { }
  38980. /**
  38981. * Called whean a render operation begins.
  38982. *
  38983. * @param {string} uid - A unique identifier for the render context.
  38984. * @param {Scene} scene - The scene being rendered.
  38985. * @param {Camera} camera - The camera being used for rendering.
  38986. * @param {?WebGLRenderTarget} renderTarget - The render target, if any.
  38987. */
  38988. beginRender( /*uid, scene, camera, renderTarget*/ ) { }
  38989. /**
  38990. * Called when an animation loop ends.
  38991. *
  38992. * @param {string} uid - A unique identifier for the render context.
  38993. */
  38994. finishRender( /*uid*/ ) { }
  38995. /**
  38996. * Called when a texture copy operation is performed.
  38997. *
  38998. * @param {Texture} srcTexture - The source texture.
  38999. * @param {Texture} dstTexture - The destination texture.
  39000. */
  39001. copyTextureToTexture( /*srcTexture, dstTexture*/ ) { }
  39002. /**
  39003. * Called when a framebuffer copy operation is performed.
  39004. *
  39005. * @param {Texture} framebufferTexture - The texture associated with the framebuffer.
  39006. */
  39007. copyFramebufferToTexture( /*framebufferTexture*/ ) { }
  39008. }
  39009. /**
  39010. * CanvasTarget is a class that represents the final output destination of the renderer.
  39011. *
  39012. * @augments EventDispatcher
  39013. */
  39014. class CanvasTarget extends EventDispatcher {
  39015. /**
  39016. * Constructs a new CanvasTarget.
  39017. *
  39018. * @param {HTMLCanvasElement|OffscreenCanvas} domElement - The canvas element to render to.
  39019. */
  39020. constructor( domElement ) {
  39021. super();
  39022. /**
  39023. * A reference to the canvas element the renderer is drawing to.
  39024. * This value of this property will automatically be created by
  39025. * the renderer.
  39026. *
  39027. * @type {HTMLCanvasElement|OffscreenCanvas}
  39028. */
  39029. this.domElement = domElement;
  39030. /**
  39031. * The renderer's pixel ratio.
  39032. *
  39033. * @private
  39034. * @type {number}
  39035. * @default 1
  39036. */
  39037. this._pixelRatio = 1;
  39038. /**
  39039. * The width of the renderer's default framebuffer in logical pixel unit.
  39040. *
  39041. * @private
  39042. * @type {number}
  39043. */
  39044. this._width = this.domElement.width;
  39045. /**
  39046. * The height of the renderer's default framebuffer in logical pixel unit.
  39047. *
  39048. * @private
  39049. * @type {number}
  39050. */
  39051. this._height = this.domElement.height;
  39052. /**
  39053. * The viewport of the renderer in logical pixel unit.
  39054. *
  39055. * @private
  39056. * @type {Vector4}
  39057. */
  39058. this._viewport = new Vector4( 0, 0, this._width, this._height );
  39059. /**
  39060. * The scissor rectangle of the renderer in logical pixel unit.
  39061. *
  39062. * @private
  39063. * @type {Vector4}
  39064. */
  39065. this._scissor = new Vector4( 0, 0, this._width, this._height );
  39066. /**
  39067. * Whether the scissor test should be enabled or not.
  39068. *
  39069. * @private
  39070. * @type {boolean}
  39071. */
  39072. this._scissorTest = false;
  39073. /**
  39074. * The color texture of the default framebuffer.
  39075. *
  39076. * @type {FramebufferTexture}
  39077. */
  39078. this.colorTexture = new FramebufferTexture();
  39079. /**
  39080. * The depth texture of the default framebuffer.
  39081. *
  39082. * @type {DepthTexture}
  39083. */
  39084. this.depthTexture = new DepthTexture();
  39085. }
  39086. /**
  39087. * Returns the pixel ratio.
  39088. *
  39089. * @return {number} The pixel ratio.
  39090. */
  39091. getPixelRatio() {
  39092. return this._pixelRatio;
  39093. }
  39094. /**
  39095. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39096. *
  39097. * @param {Vector2} target - The method writes the result in this target object.
  39098. * @return {Vector2} The drawing buffer size.
  39099. */
  39100. getDrawingBufferSize( target ) {
  39101. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39102. }
  39103. /**
  39104. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39105. *
  39106. * @param {Vector2} target - The method writes the result in this target object.
  39107. * @return {Vector2} The renderer's size in logical pixels.
  39108. */
  39109. getSize( target ) {
  39110. return target.set( this._width, this._height );
  39111. }
  39112. /**
  39113. * Sets the given pixel ratio and resizes the canvas if necessary.
  39114. *
  39115. * @param {number} [value=1] - The pixel ratio.
  39116. */
  39117. setPixelRatio( value = 1 ) {
  39118. if ( this._pixelRatio === value ) return;
  39119. this._pixelRatio = value;
  39120. this.setSize( this._width, this._height, false );
  39121. }
  39122. /**
  39123. * This method allows to define the drawing buffer size by specifying
  39124. * width, height and pixel ratio all at once. The size of the drawing
  39125. * buffer is computed with this formula:
  39126. * ```js
  39127. * size.x = width * pixelRatio;
  39128. * size.y = height * pixelRatio;
  39129. * ```
  39130. *
  39131. * @param {number} width - The width in logical pixels.
  39132. * @param {number} height - The height in logical pixels.
  39133. * @param {number} pixelRatio - The pixel ratio.
  39134. */
  39135. setDrawingBufferSize( width, height, pixelRatio ) {
  39136. // Renderer can't be resized while presenting in XR.
  39137. if ( this.xr && this.xr.isPresenting ) return;
  39138. this._width = width;
  39139. this._height = height;
  39140. this._pixelRatio = pixelRatio;
  39141. this.domElement.width = Math.floor( width * pixelRatio );
  39142. this.domElement.height = Math.floor( height * pixelRatio );
  39143. this.setViewport( 0, 0, width, height );
  39144. this._dispatchResize();
  39145. }
  39146. /**
  39147. * Sets the size of the renderer.
  39148. *
  39149. * @param {number} width - The width in logical pixels.
  39150. * @param {number} height - The height in logical pixels.
  39151. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39152. */
  39153. setSize( width, height, updateStyle = true ) {
  39154. // Renderer can't be resized while presenting in XR.
  39155. if ( this.xr && this.xr.isPresenting ) return;
  39156. this._width = width;
  39157. this._height = height;
  39158. this.domElement.width = Math.floor( width * this._pixelRatio );
  39159. this.domElement.height = Math.floor( height * this._pixelRatio );
  39160. if ( updateStyle === true ) {
  39161. this.domElement.style.width = width + 'px';
  39162. this.domElement.style.height = height + 'px';
  39163. }
  39164. this.setViewport( 0, 0, width, height );
  39165. this._dispatchResize();
  39166. }
  39167. /**
  39168. * Returns the scissor rectangle.
  39169. *
  39170. * @param {Vector4} target - The method writes the result in this target object.
  39171. * @return {Vector4} The scissor rectangle.
  39172. */
  39173. getScissor( target ) {
  39174. const scissor = this._scissor;
  39175. target.x = scissor.x;
  39176. target.y = scissor.y;
  39177. target.width = scissor.width;
  39178. target.height = scissor.height;
  39179. return target;
  39180. }
  39181. /**
  39182. * Defines the scissor rectangle.
  39183. *
  39184. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39185. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39186. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39187. * @param {number} width - The width of the scissor box in logical pixel unit.
  39188. * @param {number} height - The height of the scissor box in logical pixel unit.
  39189. */
  39190. setScissor( x, y, width, height ) {
  39191. const scissor = this._scissor;
  39192. if ( x.isVector4 ) {
  39193. scissor.copy( x );
  39194. } else {
  39195. scissor.set( x, y, width, height );
  39196. }
  39197. }
  39198. /**
  39199. * Returns the scissor test value.
  39200. *
  39201. * @return {boolean} Whether the scissor test should be enabled or not.
  39202. */
  39203. getScissorTest() {
  39204. return this._scissorTest;
  39205. }
  39206. /**
  39207. * Defines the scissor test.
  39208. *
  39209. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39210. */
  39211. setScissorTest( boolean ) {
  39212. this._scissorTest = boolean;
  39213. }
  39214. /**
  39215. * Returns the viewport definition.
  39216. *
  39217. * @param {Vector4} target - The method writes the result in this target object.
  39218. * @return {Vector4} The viewport definition.
  39219. */
  39220. getViewport( target ) {
  39221. return target.copy( this._viewport );
  39222. }
  39223. /**
  39224. * Defines the viewport.
  39225. *
  39226. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39227. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39228. * @param {number} width - The width of the viewport in logical pixel unit.
  39229. * @param {number} height - The height of the viewport in logical pixel unit.
  39230. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  39231. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  39232. */
  39233. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39234. const viewport = this._viewport;
  39235. if ( x.isVector4 ) {
  39236. viewport.copy( x );
  39237. } else {
  39238. viewport.set( x, y, width, height );
  39239. }
  39240. viewport.minDepth = minDepth;
  39241. viewport.maxDepth = maxDepth;
  39242. }
  39243. /**
  39244. * Dispatches the resize event.
  39245. *
  39246. * @private
  39247. */
  39248. _dispatchResize() {
  39249. this.dispatchEvent( { type: 'resize' } );
  39250. }
  39251. /**
  39252. * Frees the GPU-related resources allocated by this instance. Call this
  39253. * method whenever this instance is no longer used in your app.
  39254. *
  39255. * @fires RenderTarget#dispose
  39256. */
  39257. dispose() {
  39258. this.dispatchEvent( { type: 'dispose' } );
  39259. }
  39260. }
  39261. const _scene = /*@__PURE__*/ new Scene();
  39262. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  39263. const _screen = /*@__PURE__*/ new Vector4();
  39264. const _frustum = /*@__PURE__*/ new Frustum();
  39265. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  39266. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  39267. const _vector4 = /*@__PURE__*/ new Vector4();
  39268. /**
  39269. * Base class for renderers.
  39270. */
  39271. class Renderer {
  39272. /**
  39273. * Renderer options.
  39274. *
  39275. * @typedef {Object} Renderer~Options
  39276. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  39277. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  39278. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  39279. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  39280. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  39281. * @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
  39282. * to overwrite the default.
  39283. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39284. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  39285. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  39286. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  39287. */
  39288. /**
  39289. * Constructs a new renderer.
  39290. *
  39291. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  39292. * @param {Renderer~Options} [parameters] - The configuration parameter.
  39293. */
  39294. constructor( backend, parameters = {} ) {
  39295. /**
  39296. * This flag can be used for type testing.
  39297. *
  39298. * @type {boolean}
  39299. * @readonly
  39300. * @default true
  39301. */
  39302. this.isRenderer = true;
  39303. //
  39304. const {
  39305. logarithmicDepthBuffer = false,
  39306. alpha = true,
  39307. depth = true,
  39308. stencil = false,
  39309. antialias = false,
  39310. samples = 0,
  39311. getFallback = null,
  39312. colorBufferType = HalfFloatType,
  39313. multiview = false
  39314. } = parameters;
  39315. /**
  39316. * A reference to the current backend.
  39317. *
  39318. * @type {Backend}
  39319. */
  39320. this.backend = backend;
  39321. /**
  39322. * Whether the renderer should automatically clear the current rendering target
  39323. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  39324. * or the current bound render target (custom framebuffer).
  39325. *
  39326. * @type {boolean}
  39327. * @default true
  39328. */
  39329. this.autoClear = true;
  39330. /**
  39331. * When `autoClear` is set to `true`, this property defines whether the renderer
  39332. * should clear the color buffer.
  39333. *
  39334. * @type {boolean}
  39335. * @default true
  39336. */
  39337. this.autoClearColor = true;
  39338. /**
  39339. * When `autoClear` is set to `true`, this property defines whether the renderer
  39340. * should clear the depth buffer.
  39341. *
  39342. * @type {boolean}
  39343. * @default true
  39344. */
  39345. this.autoClearDepth = true;
  39346. /**
  39347. * When `autoClear` is set to `true`, this property defines whether the renderer
  39348. * should clear the stencil buffer.
  39349. *
  39350. * @type {boolean}
  39351. * @default true
  39352. */
  39353. this.autoClearStencil = true;
  39354. /**
  39355. * Whether the default framebuffer should be transparent or opaque.
  39356. *
  39357. * @type {boolean}
  39358. * @default true
  39359. */
  39360. this.alpha = alpha;
  39361. /**
  39362. * Whether logarithmic depth buffer is enabled or not.
  39363. *
  39364. * @type {boolean}
  39365. * @default false
  39366. */
  39367. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  39368. /**
  39369. * Defines the output color space of the renderer.
  39370. *
  39371. * @type {string}
  39372. * @default SRGBColorSpace
  39373. */
  39374. this.outputColorSpace = SRGBColorSpace;
  39375. /**
  39376. * Defines the tone mapping of the renderer.
  39377. *
  39378. * @type {number}
  39379. * @default NoToneMapping
  39380. */
  39381. this.toneMapping = NoToneMapping;
  39382. /**
  39383. * Defines the tone mapping exposure.
  39384. *
  39385. * @type {number}
  39386. * @default 1
  39387. */
  39388. this.toneMappingExposure = 1.0;
  39389. /**
  39390. * Whether the renderer should sort its render lists or not.
  39391. *
  39392. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  39393. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  39394. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  39395. * e.g. manually determining each object's rendering order.
  39396. *
  39397. * @type {boolean}
  39398. * @default true
  39399. */
  39400. this.sortObjects = true;
  39401. /**
  39402. * Whether the default framebuffer should have a depth buffer or not.
  39403. *
  39404. * @type {boolean}
  39405. * @default true
  39406. */
  39407. this.depth = depth;
  39408. /**
  39409. * Whether the default framebuffer should have a stencil buffer or not.
  39410. *
  39411. * @type {boolean}
  39412. * @default false
  39413. */
  39414. this.stencil = stencil;
  39415. /**
  39416. * Holds a series of statistical information about the GPU memory
  39417. * and the rendering process. Useful for debugging and monitoring.
  39418. *
  39419. * @type {Info}
  39420. */
  39421. this.info = new Info();
  39422. /**
  39423. * Stores override nodes for specific transformations or calculations.
  39424. * These nodes can be used to replace default behavior in the rendering pipeline.
  39425. *
  39426. * @type {Object}
  39427. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  39428. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  39429. */
  39430. this.overrideNodes = {
  39431. modelViewMatrix: null,
  39432. modelNormalViewMatrix: null
  39433. };
  39434. /**
  39435. * The node library defines how certain library objects like materials, lights
  39436. * or tone mapping functions are mapped to node types. This is required since
  39437. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  39438. * be part of the scene graph, they are internally represented as nodes for
  39439. * further processing.
  39440. *
  39441. * @type {NodeLibrary}
  39442. */
  39443. this.library = new NodeLibrary();
  39444. /**
  39445. * A map-like data structure for managing lights.
  39446. *
  39447. * @type {Lighting}
  39448. */
  39449. this.lighting = new Lighting();
  39450. // internals
  39451. /**
  39452. * The number of MSAA samples.
  39453. *
  39454. * @private
  39455. * @type {number}
  39456. * @default 0
  39457. */
  39458. this._samples = samples || ( antialias === true ) ? 4 : 0;
  39459. /**
  39460. * OnCanvasTargetResize callback function.
  39461. *
  39462. * @private
  39463. * @type {Function}
  39464. */
  39465. this._onCanvasTargetResize = this._onCanvasTargetResize.bind( this );
  39466. /**
  39467. * The canvas target for rendering.
  39468. *
  39469. * @private
  39470. * @type {CanvasTarget}
  39471. */
  39472. this._canvasTarget = new CanvasTarget( backend.getDomElement() );
  39473. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  39474. this._canvasTarget.isDefaultCanvasTarget = true;
  39475. /**
  39476. * The inspector provides information about the internal renderer state.
  39477. *
  39478. * @private
  39479. * @type {InspectorBase}
  39480. */
  39481. this._inspector = new InspectorBase();
  39482. this._inspector.setRenderer( this );
  39483. /**
  39484. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  39485. *
  39486. * @private
  39487. * @type {?Function}
  39488. */
  39489. this._getFallback = getFallback;
  39490. /**
  39491. * A reference to a renderer module for managing shader attributes.
  39492. *
  39493. * @private
  39494. * @type {?Attributes}
  39495. * @default null
  39496. */
  39497. this._attributes = null;
  39498. /**
  39499. * A reference to a renderer module for managing geometries.
  39500. *
  39501. * @private
  39502. * @type {?Geometries}
  39503. * @default null
  39504. */
  39505. this._geometries = null;
  39506. /**
  39507. * A reference to a renderer module for managing node related logic.
  39508. *
  39509. * @private
  39510. * @type {?Nodes}
  39511. * @default null
  39512. */
  39513. this._nodes = null;
  39514. /**
  39515. * A reference to a renderer module for managing the internal animation loop.
  39516. *
  39517. * @private
  39518. * @type {?Animation}
  39519. * @default null
  39520. */
  39521. this._animation = null;
  39522. /**
  39523. * A reference to a renderer module for managing shader program bindings.
  39524. *
  39525. * @private
  39526. * @type {?Bindings}
  39527. * @default null
  39528. */
  39529. this._bindings = null;
  39530. /**
  39531. * A reference to a renderer module for managing render objects.
  39532. *
  39533. * @private
  39534. * @type {?RenderObjects}
  39535. * @default null
  39536. */
  39537. this._objects = null;
  39538. /**
  39539. * A reference to a renderer module for managing render and compute pipelines.
  39540. *
  39541. * @private
  39542. * @type {?Pipelines}
  39543. * @default null
  39544. */
  39545. this._pipelines = null;
  39546. /**
  39547. * A reference to a renderer module for managing render bundles.
  39548. *
  39549. * @private
  39550. * @type {?RenderBundles}
  39551. * @default null
  39552. */
  39553. this._bundles = null;
  39554. /**
  39555. * A reference to a renderer module for managing render lists.
  39556. *
  39557. * @private
  39558. * @type {?RenderLists}
  39559. * @default null
  39560. */
  39561. this._renderLists = null;
  39562. /**
  39563. * A reference to a renderer module for managing render contexts.
  39564. *
  39565. * @private
  39566. * @type {?RenderContexts}
  39567. * @default null
  39568. */
  39569. this._renderContexts = null;
  39570. /**
  39571. * A reference to a renderer module for managing textures.
  39572. *
  39573. * @private
  39574. * @type {?Textures}
  39575. * @default null
  39576. */
  39577. this._textures = null;
  39578. /**
  39579. * A reference to a renderer module for backgrounds.
  39580. *
  39581. * @private
  39582. * @type {?Background}
  39583. * @default null
  39584. */
  39585. this._background = null;
  39586. /**
  39587. * This fullscreen quad is used for internal render passes
  39588. * like the tone mapping and color space output pass.
  39589. *
  39590. * @private
  39591. * @type {QuadMesh}
  39592. */
  39593. this._quad = new QuadMesh( new NodeMaterial() );
  39594. this._quad.name = 'Output Color Transform';
  39595. this._quad.material.name = 'outputColorTransform';
  39596. /**
  39597. * A reference to the current render context.
  39598. *
  39599. * @private
  39600. * @type {?RenderContext}
  39601. * @default null
  39602. */
  39603. this._currentRenderContext = null;
  39604. /**
  39605. * A custom sort function for the opaque render list.
  39606. *
  39607. * @private
  39608. * @type {?Function}
  39609. * @default null
  39610. */
  39611. this._opaqueSort = null;
  39612. /**
  39613. * A custom sort function for the transparent render list.
  39614. *
  39615. * @private
  39616. * @type {?Function}
  39617. * @default null
  39618. */
  39619. this._transparentSort = null;
  39620. /**
  39621. * The framebuffer target.
  39622. *
  39623. * @private
  39624. * @type {?RenderTarget}
  39625. * @default null
  39626. */
  39627. this._frameBufferTarget = null;
  39628. const alphaClear = this.alpha === true ? 0 : 1;
  39629. /**
  39630. * The clear color value.
  39631. *
  39632. * @private
  39633. * @type {Color4}
  39634. */
  39635. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  39636. /**
  39637. * The clear depth value.
  39638. *
  39639. * @private
  39640. * @type {number}
  39641. * @default 1
  39642. */
  39643. this._clearDepth = 1;
  39644. /**
  39645. * The clear stencil value.
  39646. *
  39647. * @private
  39648. * @type {number}
  39649. * @default 0
  39650. */
  39651. this._clearStencil = 0;
  39652. /**
  39653. * The current render target.
  39654. *
  39655. * @private
  39656. * @type {?RenderTarget}
  39657. * @default null
  39658. */
  39659. this._renderTarget = null;
  39660. /**
  39661. * The active cube face.
  39662. *
  39663. * @private
  39664. * @type {number}
  39665. * @default 0
  39666. */
  39667. this._activeCubeFace = 0;
  39668. /**
  39669. * The active mipmap level.
  39670. *
  39671. * @private
  39672. * @type {number}
  39673. * @default 0
  39674. */
  39675. this._activeMipmapLevel = 0;
  39676. /**
  39677. * The current output render target.
  39678. *
  39679. * @private
  39680. * @type {?RenderTarget}
  39681. * @default null
  39682. */
  39683. this._outputRenderTarget = null;
  39684. /**
  39685. * The MRT setting.
  39686. *
  39687. * @private
  39688. * @type {?MRTNode}
  39689. * @default null
  39690. */
  39691. this._mrt = null;
  39692. /**
  39693. * This function defines how a render object is going
  39694. * to be rendered.
  39695. *
  39696. * @private
  39697. * @type {?Function}
  39698. * @default null
  39699. */
  39700. this._renderObjectFunction = null;
  39701. /**
  39702. * Used to keep track of the current render object function.
  39703. *
  39704. * @private
  39705. * @type {?Function}
  39706. * @default null
  39707. */
  39708. this._currentRenderObjectFunction = null;
  39709. /**
  39710. * Used to keep track of the current render bundle.
  39711. *
  39712. * @private
  39713. * @type {?RenderBundle}
  39714. * @default null
  39715. */
  39716. this._currentRenderBundle = null;
  39717. /**
  39718. * Next to `_renderObjectFunction()`, this function provides another hook
  39719. * for influencing the render process of a render object. It is meant for internal
  39720. * use and only relevant for `compileAsync()` right now. Instead of using
  39721. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  39722. * a different function might be used which performs no draw but just the node
  39723. * and pipeline updates.
  39724. *
  39725. * @private
  39726. * @type {?Function}
  39727. * @default null
  39728. */
  39729. this._handleObjectFunction = this._renderObjectDirect;
  39730. /**
  39731. * Indicates whether the device has been lost or not. In WebGL terms, the device
  39732. * lost is considered as a context lost. When this is set to `true`, rendering
  39733. * isn't possible anymore.
  39734. *
  39735. * @private
  39736. * @type {boolean}
  39737. * @default false
  39738. */
  39739. this._isDeviceLost = false;
  39740. /**
  39741. * A callback function that defines what should happen when a device/context lost occurs.
  39742. *
  39743. * @type {Function}
  39744. */
  39745. this.onDeviceLost = this._onDeviceLost;
  39746. /**
  39747. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  39748. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  39749. * This will reduce rendering quality though.
  39750. *
  39751. * @private
  39752. * @type {number}
  39753. * @default HalfFloatType
  39754. */
  39755. this._colorBufferType = colorBufferType;
  39756. /**
  39757. * A cache for shadow nodes per material
  39758. *
  39759. * @private
  39760. * @type {WeakMap<Material, Object>}
  39761. */
  39762. this._cacheShadowNodes = new WeakMap();
  39763. /**
  39764. * Whether the renderer has been initialized or not.
  39765. *
  39766. * @private
  39767. * @type {boolean}
  39768. * @default false
  39769. */
  39770. this._initialized = false;
  39771. /**
  39772. * A reference to the promise which initializes the renderer.
  39773. *
  39774. * @private
  39775. * @type {?Promise<this>}
  39776. * @default null
  39777. */
  39778. this._initPromise = null;
  39779. /**
  39780. * An array of compilation promises which are used in `compileAsync()`.
  39781. *
  39782. * @private
  39783. * @type {?Array<Promise>}
  39784. * @default null
  39785. */
  39786. this._compilationPromises = null;
  39787. /**
  39788. * Whether the renderer should render transparent render objects or not.
  39789. *
  39790. * @type {boolean}
  39791. * @default true
  39792. */
  39793. this.transparent = true;
  39794. /**
  39795. * Whether the renderer should render opaque render objects or not.
  39796. *
  39797. * @type {boolean}
  39798. * @default true
  39799. */
  39800. this.opaque = true;
  39801. /**
  39802. * Shadow map configuration
  39803. * @typedef {Object} ShadowMapConfig
  39804. * @property {boolean} enabled - Whether to globally enable shadows or not.
  39805. * @property {number} type - The shadow map type.
  39806. */
  39807. /**
  39808. * The renderer's shadow configuration.
  39809. *
  39810. * @type {ShadowMapConfig}
  39811. */
  39812. this.shadowMap = {
  39813. enabled: false,
  39814. type: PCFShadowMap
  39815. };
  39816. /**
  39817. * XR configuration.
  39818. * @typedef {Object} XRConfig
  39819. * @property {boolean} enabled - Whether to globally enable XR or not.
  39820. */
  39821. /**
  39822. * The renderer's XR manager.
  39823. *
  39824. * @type {XRManager}
  39825. */
  39826. this.xr = new XRManager( this, multiview );
  39827. /**
  39828. * Debug configuration.
  39829. * @typedef {Object} DebugConfig
  39830. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  39831. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  39832. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  39833. */
  39834. /**
  39835. * The renderer's debug configuration.
  39836. *
  39837. * @type {DebugConfig}
  39838. */
  39839. this.debug = {
  39840. checkShaderErrors: true,
  39841. onShaderError: null,
  39842. getShaderAsync: async ( scene, camera, object ) => {
  39843. await this.compileAsync( scene, camera );
  39844. const renderList = this._renderLists.get( scene, camera );
  39845. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  39846. const material = scene.overrideMaterial || object.material;
  39847. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  39848. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  39849. return { fragmentShader, vertexShader };
  39850. }
  39851. };
  39852. }
  39853. /**
  39854. * Initializes the renderer so it is ready for usage.
  39855. *
  39856. * @async
  39857. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  39858. */
  39859. async init() {
  39860. if ( this._initialized ) {
  39861. throw new Error( 'Renderer: Backend has already been initialized.' );
  39862. }
  39863. if ( this._initPromise !== null ) {
  39864. return this._initPromise;
  39865. }
  39866. this._initPromise = new Promise( async ( resolve, reject ) => {
  39867. let backend = this.backend;
  39868. try {
  39869. await backend.init( this );
  39870. } catch ( error ) {
  39871. if ( this._getFallback !== null ) {
  39872. // try the fallback
  39873. try {
  39874. this.backend = backend = this._getFallback( error );
  39875. await backend.init( this );
  39876. } catch ( error ) {
  39877. reject( error );
  39878. return;
  39879. }
  39880. } else {
  39881. reject( error );
  39882. return;
  39883. }
  39884. }
  39885. this._nodes = new Nodes( this, backend );
  39886. this._animation = new Animation( this, this._nodes, this.info );
  39887. this._attributes = new Attributes( backend );
  39888. this._background = new Background( this, this._nodes );
  39889. this._geometries = new Geometries( this._attributes, this.info );
  39890. this._textures = new Textures( this, backend, this.info );
  39891. this._pipelines = new Pipelines( backend, this._nodes );
  39892. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  39893. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  39894. this._renderLists = new RenderLists( this.lighting );
  39895. this._bundles = new RenderBundles();
  39896. this._renderContexts = new RenderContexts();
  39897. //
  39898. this._animation.start();
  39899. this._initialized = true;
  39900. //
  39901. this._inspector.init();
  39902. //
  39903. resolve( this );
  39904. } );
  39905. return this._initPromise;
  39906. }
  39907. /**
  39908. * A reference to the canvas element the renderer is drawing to.
  39909. * This value of this property will automatically be created by
  39910. * the renderer.
  39911. *
  39912. * @type {HTMLCanvasElement|OffscreenCanvas}
  39913. */
  39914. get domElement() {
  39915. return this._canvasTarget.domElement;
  39916. }
  39917. /**
  39918. * The coordinate system of the renderer. The value of this property
  39919. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  39920. * `THREE.WebGPUCoordinateSystem`.
  39921. *
  39922. * @readonly
  39923. * @type {number}
  39924. */
  39925. get coordinateSystem() {
  39926. return this.backend.coordinateSystem;
  39927. }
  39928. /**
  39929. * Compiles all materials in the given scene. This can be useful to avoid a
  39930. * phenomenon which is called "shader compilation stutter", which occurs when
  39931. * rendering an object with a new shader for the first time.
  39932. *
  39933. * If you want to add a 3D object to an existing scene, use the third optional
  39934. * parameter for applying the target scene. Note that the (target) scene's lighting
  39935. * and environment must be configured before calling this method.
  39936. *
  39937. * @async
  39938. * @param {Object3D} scene - The scene or 3D object to precompile.
  39939. * @param {Camera} camera - The camera that is used to render the scene.
  39940. * @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.
  39941. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  39942. */
  39943. async compileAsync( scene, camera, targetScene = null ) {
  39944. if ( this._isDeviceLost === true ) return;
  39945. if ( this._initialized === false ) await this.init();
  39946. // preserve render tree
  39947. const nodeFrame = this._nodes.nodeFrame;
  39948. const previousRenderId = nodeFrame.renderId;
  39949. const previousRenderContext = this._currentRenderContext;
  39950. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  39951. const previousCompilationPromises = this._compilationPromises;
  39952. //
  39953. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  39954. if ( targetScene === null ) targetScene = scene;
  39955. const renderTarget = this._renderTarget;
  39956. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  39957. const activeMipmapLevel = this._activeMipmapLevel;
  39958. const compilationPromises = [];
  39959. this._currentRenderContext = renderContext;
  39960. this._currentRenderObjectFunction = this.renderObject;
  39961. this._handleObjectFunction = this._createObjectPipeline;
  39962. this._compilationPromises = compilationPromises;
  39963. nodeFrame.renderId ++;
  39964. //
  39965. nodeFrame.update();
  39966. //
  39967. renderContext.depth = this.depth;
  39968. renderContext.stencil = this.stencil;
  39969. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  39970. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  39971. //
  39972. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  39973. //
  39974. const renderList = this._renderLists.get( scene, camera );
  39975. renderList.begin();
  39976. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  39977. // include lights from target scene
  39978. if ( targetScene !== scene ) {
  39979. targetScene.traverseVisible( function ( object ) {
  39980. if ( object.isLight && object.layers.test( camera.layers ) ) {
  39981. renderList.pushLight( object );
  39982. }
  39983. } );
  39984. }
  39985. renderList.finish();
  39986. //
  39987. if ( renderTarget !== null ) {
  39988. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  39989. const renderTargetData = this._textures.get( renderTarget );
  39990. renderContext.textures = renderTargetData.textures;
  39991. renderContext.depthTexture = renderTargetData.depthTexture;
  39992. } else {
  39993. renderContext.textures = null;
  39994. renderContext.depthTexture = null;
  39995. }
  39996. //
  39997. this._background.update( sceneRef, renderList, renderContext );
  39998. // process render lists
  39999. const opaqueObjects = renderList.opaque;
  40000. const transparentObjects = renderList.transparent;
  40001. const transparentDoublePassObjects = renderList.transparentDoublePass;
  40002. const lightsNode = renderList.lightsNode;
  40003. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40004. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40005. // restore render tree
  40006. nodeFrame.renderId = previousRenderId;
  40007. this._currentRenderContext = previousRenderContext;
  40008. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40009. this._compilationPromises = previousCompilationPromises;
  40010. this._handleObjectFunction = this._renderObjectDirect;
  40011. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  40012. await Promise.all( compilationPromises );
  40013. }
  40014. /**
  40015. * Renders the scene in an async fashion.
  40016. *
  40017. * @async
  40018. * @param {Object3D} scene - The scene or 3D object to render.
  40019. * @param {Camera} camera - The camera.
  40020. * @return {Promise} A Promise that resolves when the render has been finished.
  40021. */
  40022. async renderAsync( scene, camera ) {
  40023. if ( this._initialized === false ) await this.init();
  40024. this._renderScene( scene, camera );
  40025. }
  40026. /**
  40027. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40028. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40029. *
  40030. * @async
  40031. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40032. */
  40033. async waitForGPU() {
  40034. await this.backend.waitForGPU();
  40035. }
  40036. //
  40037. /**
  40038. * Sets the inspector instance. The inspector can be any class that extends from `InspectorBase`.
  40039. *
  40040. * @param {InspectorBase} value - The new inspector.
  40041. */
  40042. set inspector( value ) {
  40043. if ( this._inspector !== null ) {
  40044. this._inspector.setRenderer( null );
  40045. }
  40046. this._inspector = value;
  40047. this._inspector.setRenderer( this );
  40048. }
  40049. get inspector() {
  40050. return this._inspector;
  40051. }
  40052. /**
  40053. * Enables or disables high precision for model-view and normal-view matrices.
  40054. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  40055. *
  40056. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  40057. *
  40058. * @param {boolean} value - Whether to enable or disable high precision.
  40059. * @type {boolean}
  40060. */
  40061. set highPrecision( value ) {
  40062. if ( value === true ) {
  40063. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  40064. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  40065. } else if ( this.highPrecision ) {
  40066. this.overrideNodes.modelViewMatrix = null;
  40067. this.overrideNodes.modelNormalViewMatrix = null;
  40068. }
  40069. }
  40070. /**
  40071. * Returns whether high precision is enabled or not.
  40072. *
  40073. * @return {boolean} Whether high precision is enabled or not.
  40074. * @type {boolean}
  40075. */
  40076. get highPrecision() {
  40077. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  40078. }
  40079. /**
  40080. * Sets the given MRT configuration.
  40081. *
  40082. * @param {MRTNode} mrt - The MRT node to set.
  40083. * @return {Renderer} A reference to this renderer.
  40084. */
  40085. setMRT( mrt ) {
  40086. this._mrt = mrt;
  40087. return this;
  40088. }
  40089. /**
  40090. * Returns the MRT configuration.
  40091. *
  40092. * @return {MRTNode} The MRT configuration.
  40093. */
  40094. getMRT() {
  40095. return this._mrt;
  40096. }
  40097. /**
  40098. * Returns the color buffer type.
  40099. *
  40100. * @return {number} The color buffer type.
  40101. */
  40102. getColorBufferType() {
  40103. return this._colorBufferType;
  40104. }
  40105. /**
  40106. * Default implementation of the device lost callback.
  40107. *
  40108. * @private
  40109. * @param {Object} info - Information about the context lost.
  40110. */
  40111. _onDeviceLost( info ) {
  40112. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  40113. if ( info.reason ) {
  40114. errorMessage += `\nReason: ${info.reason}`;
  40115. }
  40116. error( errorMessage );
  40117. this._isDeviceLost = true;
  40118. }
  40119. /**
  40120. * Renders the given render bundle.
  40121. *
  40122. * @private
  40123. * @param {Object} bundle - Render bundle data.
  40124. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  40125. * @param {LightsNode} lightsNode - The lights node.
  40126. */
  40127. _renderBundle( bundle, sceneRef, lightsNode ) {
  40128. const { bundleGroup, camera, renderList } = bundle;
  40129. const renderContext = this._currentRenderContext;
  40130. //
  40131. const renderBundle = this._bundles.get( bundleGroup, camera );
  40132. const renderBundleData = this.backend.get( renderBundle );
  40133. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  40134. //
  40135. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  40136. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  40137. renderBundleData.renderContexts.add( renderContext );
  40138. if ( renderBundleNeedsUpdate ) {
  40139. this.backend.beginBundle( renderContext );
  40140. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  40141. renderBundleData.renderObjects = [];
  40142. }
  40143. this._currentRenderBundle = renderBundle;
  40144. const {
  40145. transparentDoublePass: transparentDoublePassObjects,
  40146. transparent: transparentObjects,
  40147. opaque: opaqueObjects
  40148. } = renderList;
  40149. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40150. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40151. this._currentRenderBundle = null;
  40152. //
  40153. this.backend.finishBundle( renderContext, renderBundle );
  40154. renderBundleData.version = bundleGroup.version;
  40155. } else {
  40156. const { renderObjects } = renderBundleData;
  40157. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  40158. const renderObject = renderObjects[ i ];
  40159. if ( this._nodes.needsRefresh( renderObject ) ) {
  40160. this._nodes.updateBefore( renderObject );
  40161. this._nodes.updateForRender( renderObject );
  40162. this._bindings.updateForRender( renderObject );
  40163. this._nodes.updateAfter( renderObject );
  40164. }
  40165. }
  40166. }
  40167. this.backend.addBundle( renderContext, renderBundle );
  40168. }
  40169. /**
  40170. * Renders the scene or 3D object with the given camera. This method can only be called
  40171. * if the renderer has been initialized.
  40172. *
  40173. * The target of the method is the default framebuffer (meaning the canvas)
  40174. * or alternatively a render target when specified via `setRenderTarget()`.
  40175. *
  40176. * @param {Object3D} scene - The scene or 3D object to render.
  40177. * @param {Camera} camera - The camera to render the scene with.
  40178. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  40179. * Only returned when the renderer has not been initialized.
  40180. */
  40181. render( scene, camera ) {
  40182. if ( this._initialized === false ) {
  40183. warn( 'Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  40184. return this.renderAsync( scene, camera );
  40185. }
  40186. this._renderScene( scene, camera );
  40187. }
  40188. /**
  40189. * Returns whether the renderer has been initialized or not.
  40190. *
  40191. * @readonly
  40192. * @return {boolean} Whether the renderer has been initialized or not.
  40193. */
  40194. get initialized() {
  40195. return this._initialized;
  40196. }
  40197. /**
  40198. * Returns an internal render target which is used when computing the output tone mapping
  40199. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  40200. * pass and not inline to achieve more correct results.
  40201. *
  40202. * @private
  40203. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  40204. */
  40205. _getFrameBufferTarget() {
  40206. const { currentToneMapping, currentColorSpace } = this;
  40207. const useToneMapping = currentToneMapping !== NoToneMapping;
  40208. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  40209. if ( useToneMapping === false && useColorSpace === false ) return null;
  40210. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  40211. const { depth, stencil } = this;
  40212. let frameBufferTarget = this._frameBufferTarget;
  40213. if ( frameBufferTarget === null ) {
  40214. frameBufferTarget = new RenderTarget( width, height, {
  40215. depthBuffer: depth,
  40216. stencilBuffer: stencil,
  40217. type: this._colorBufferType,
  40218. format: RGBAFormat,
  40219. colorSpace: ColorManagement.workingColorSpace,
  40220. generateMipmaps: false,
  40221. minFilter: LinearFilter,
  40222. magFilter: LinearFilter,
  40223. samples: this.samples
  40224. } );
  40225. frameBufferTarget.isPostProcessingRenderTarget = true;
  40226. this._frameBufferTarget = frameBufferTarget;
  40227. }
  40228. const outputRenderTarget = this.getOutputRenderTarget();
  40229. frameBufferTarget.depthBuffer = depth;
  40230. frameBufferTarget.stencilBuffer = stencil;
  40231. if ( outputRenderTarget !== null ) {
  40232. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  40233. } else {
  40234. frameBufferTarget.setSize( width, height, 1 );
  40235. }
  40236. const canvasTarget = this._canvasTarget;
  40237. frameBufferTarget.viewport.copy( canvasTarget._viewport );
  40238. frameBufferTarget.scissor.copy( canvasTarget._scissor );
  40239. frameBufferTarget.viewport.multiplyScalar( canvasTarget._pixelRatio );
  40240. frameBufferTarget.scissor.multiplyScalar( canvasTarget._pixelRatio );
  40241. frameBufferTarget.scissorTest = canvasTarget._scissorTest;
  40242. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  40243. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  40244. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  40245. return frameBufferTarget;
  40246. }
  40247. /**
  40248. * Renders the scene or 3D object with the given camera.
  40249. *
  40250. * @private
  40251. * @param {Object3D} scene - The scene or 3D object to render.
  40252. * @param {Camera} camera - The camera to render the scene with.
  40253. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  40254. * @return {RenderContext} The current render context.
  40255. */
  40256. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  40257. if ( this._isDeviceLost === true ) return;
  40258. //
  40259. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  40260. // preserve render tree
  40261. const nodeFrame = this._nodes.nodeFrame;
  40262. const previousRenderId = nodeFrame.renderId;
  40263. const previousRenderContext = this._currentRenderContext;
  40264. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  40265. //
  40266. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  40267. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  40268. const activeCubeFace = this._activeCubeFace;
  40269. const activeMipmapLevel = this._activeMipmapLevel;
  40270. //
  40271. let renderTarget;
  40272. if ( frameBufferTarget !== null ) {
  40273. renderTarget = frameBufferTarget;
  40274. this.setRenderTarget( renderTarget );
  40275. } else {
  40276. renderTarget = outputRenderTarget;
  40277. }
  40278. //
  40279. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  40280. this._currentRenderContext = renderContext;
  40281. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  40282. //
  40283. this.info.calls ++;
  40284. this.info.render.calls ++;
  40285. this.info.render.frameCalls ++;
  40286. nodeFrame.renderId = this.info.calls;
  40287. //
  40288. this.backend.updateTimeStampUID( renderContext );
  40289. this.inspector.beginRender( this.backend.getTimestampUID( renderContext ), scene, camera, renderTarget );
  40290. //
  40291. const coordinateSystem = this.coordinateSystem;
  40292. const xr = this.xr;
  40293. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  40294. camera.coordinateSystem = coordinateSystem;
  40295. camera.updateProjectionMatrix();
  40296. if ( camera.isArrayCamera ) {
  40297. for ( const subCamera of camera.cameras ) {
  40298. subCamera.coordinateSystem = coordinateSystem;
  40299. subCamera.updateProjectionMatrix();
  40300. }
  40301. }
  40302. }
  40303. //
  40304. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  40305. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  40306. if ( xr.enabled === true && xr.isPresenting === true ) {
  40307. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  40308. camera = xr.getCamera(); // use XR camera for rendering
  40309. }
  40310. //
  40311. const canvasTarget = this._canvasTarget;
  40312. let viewport = canvasTarget._viewport;
  40313. let scissor = canvasTarget._scissor;
  40314. let pixelRatio = canvasTarget._pixelRatio;
  40315. if ( renderTarget !== null ) {
  40316. viewport = renderTarget.viewport;
  40317. scissor = renderTarget.scissor;
  40318. pixelRatio = 1;
  40319. }
  40320. this.getDrawingBufferSize( _drawingBufferSize );
  40321. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  40322. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  40323. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  40324. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  40325. renderContext.viewportValue.width >>= activeMipmapLevel;
  40326. renderContext.viewportValue.height >>= activeMipmapLevel;
  40327. renderContext.viewportValue.minDepth = minDepth;
  40328. renderContext.viewportValue.maxDepth = maxDepth;
  40329. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  40330. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  40331. renderContext.scissor = canvasTarget._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  40332. renderContext.scissorValue.width >>= activeMipmapLevel;
  40333. renderContext.scissorValue.height >>= activeMipmapLevel;
  40334. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  40335. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  40336. //
  40337. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  40338. //
  40339. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40340. if ( ! camera.isArrayCamera ) {
  40341. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  40342. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  40343. }
  40344. const renderList = this._renderLists.get( scene, camera );
  40345. renderList.begin();
  40346. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  40347. renderList.finish();
  40348. if ( this.sortObjects === true ) {
  40349. renderList.sort( this._opaqueSort, this._transparentSort );
  40350. }
  40351. //
  40352. if ( renderTarget !== null ) {
  40353. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  40354. const renderTargetData = this._textures.get( renderTarget );
  40355. renderContext.textures = renderTargetData.textures;
  40356. renderContext.depthTexture = renderTargetData.depthTexture;
  40357. renderContext.width = renderTargetData.width;
  40358. renderContext.height = renderTargetData.height;
  40359. renderContext.renderTarget = renderTarget;
  40360. renderContext.depth = renderTarget.depthBuffer;
  40361. renderContext.stencil = renderTarget.stencilBuffer;
  40362. } else {
  40363. renderContext.textures = null;
  40364. renderContext.depthTexture = null;
  40365. renderContext.width = _drawingBufferSize.width;
  40366. renderContext.height = _drawingBufferSize.height;
  40367. renderContext.depth = this.depth;
  40368. renderContext.stencil = this.stencil;
  40369. }
  40370. renderContext.width >>= activeMipmapLevel;
  40371. renderContext.height >>= activeMipmapLevel;
  40372. renderContext.activeCubeFace = activeCubeFace;
  40373. renderContext.activeMipmapLevel = activeMipmapLevel;
  40374. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  40375. //
  40376. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  40377. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  40378. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  40379. }
  40380. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  40381. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  40382. }
  40383. //
  40384. this._background.update( sceneRef, renderList, renderContext );
  40385. //
  40386. renderContext.camera = camera;
  40387. this.backend.beginRender( renderContext );
  40388. // process render lists
  40389. const {
  40390. bundles,
  40391. lightsNode,
  40392. transparentDoublePass: transparentDoublePassObjects,
  40393. transparent: transparentObjects,
  40394. opaque: opaqueObjects
  40395. } = renderList;
  40396. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  40397. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  40398. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  40399. // finish render pass
  40400. this.backend.finishRender( renderContext );
  40401. // restore render tree
  40402. nodeFrame.renderId = previousRenderId;
  40403. this._currentRenderContext = previousRenderContext;
  40404. this._currentRenderObjectFunction = previousRenderObjectFunction;
  40405. //
  40406. if ( frameBufferTarget !== null ) {
  40407. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  40408. this._renderOutput( renderTarget );
  40409. }
  40410. //
  40411. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  40412. //
  40413. this.inspector.finishRender( this.backend.getTimestampUID( renderContext ) );
  40414. //
  40415. return renderContext;
  40416. }
  40417. _setXRLayerSize( width, height ) {
  40418. // TODO: Find a better solution to resize the canvas when in XR.
  40419. this._canvasTarget._width = width;
  40420. this._canvasTarget._height = height;
  40421. this.setViewport( 0, 0, width, height );
  40422. }
  40423. /**
  40424. * The output pass performs tone mapping and color space conversion.
  40425. *
  40426. * @private
  40427. * @param {RenderTarget} renderTarget - The current render target.
  40428. */
  40429. _renderOutput( renderTarget ) {
  40430. const quad = this._quad;
  40431. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  40432. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  40433. quad.material.needsUpdate = true;
  40434. }
  40435. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  40436. const currentAutoClear = this.autoClear;
  40437. const currentXR = this.xr.enabled;
  40438. this.autoClear = false;
  40439. this.xr.enabled = false;
  40440. this._renderScene( quad, quad.camera, false );
  40441. this.autoClear = currentAutoClear;
  40442. this.xr.enabled = currentXR;
  40443. }
  40444. /**
  40445. * Returns the maximum available anisotropy for texture filtering.
  40446. *
  40447. * @return {number} The maximum available anisotropy.
  40448. */
  40449. getMaxAnisotropy() {
  40450. return this.backend.getMaxAnisotropy();
  40451. }
  40452. /**
  40453. * Returns the active cube face.
  40454. *
  40455. * @return {number} The active cube face.
  40456. */
  40457. getActiveCubeFace() {
  40458. return this._activeCubeFace;
  40459. }
  40460. /**
  40461. * Returns the active mipmap level.
  40462. *
  40463. * @return {number} The active mipmap level.
  40464. */
  40465. getActiveMipmapLevel() {
  40466. return this._activeMipmapLevel;
  40467. }
  40468. /**
  40469. * Applications are advised to always define the animation loop
  40470. * with this method and not manually with `requestAnimationFrame()`
  40471. * for best compatibility.
  40472. *
  40473. * @async
  40474. * @param {?onAnimationCallback} callback - The application's animation loop.
  40475. * @return {Promise} A Promise that resolves when the set has been executed.
  40476. */
  40477. async setAnimationLoop( callback ) {
  40478. if ( this._initialized === false ) await this.init();
  40479. this._animation.setAnimationLoop( callback );
  40480. }
  40481. /**
  40482. * Returns the current animation loop callback.
  40483. *
  40484. * @return {?Function} The current animation loop callback.
  40485. */
  40486. getAnimationLoop() {
  40487. return this._animation.getAnimationLoop();
  40488. }
  40489. /**
  40490. * Can be used to transfer buffer data from a storage buffer attribute
  40491. * from the GPU to the CPU in context of compute shaders.
  40492. *
  40493. * @async
  40494. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40495. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40496. */
  40497. async getArrayBufferAsync( attribute ) {
  40498. return await this.backend.getArrayBufferAsync( attribute );
  40499. }
  40500. /**
  40501. * Returns the rendering context.
  40502. *
  40503. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  40504. */
  40505. getContext() {
  40506. return this.backend.getContext();
  40507. }
  40508. /**
  40509. * Returns the pixel ratio.
  40510. *
  40511. * @return {number} The pixel ratio.
  40512. */
  40513. getPixelRatio() {
  40514. return this._canvasTarget.getPixelRatio();
  40515. }
  40516. /**
  40517. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  40518. *
  40519. * @param {Vector2} target - The method writes the result in this target object.
  40520. * @return {Vector2} The drawing buffer size.
  40521. */
  40522. getDrawingBufferSize( target ) {
  40523. return this._canvasTarget.getDrawingBufferSize( target );
  40524. }
  40525. /**
  40526. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  40527. *
  40528. * @param {Vector2} target - The method writes the result in this target object.
  40529. * @return {Vector2} The renderer's size in logical pixels.
  40530. */
  40531. getSize( target ) {
  40532. return this._canvasTarget.getSize( target );
  40533. }
  40534. /**
  40535. * Sets the given pixel ratio and resizes the canvas if necessary.
  40536. *
  40537. * @param {number} [value=1] - The pixel ratio.
  40538. */
  40539. setPixelRatio( value = 1 ) {
  40540. this._canvasTarget.setPixelRatio( value );
  40541. }
  40542. /**
  40543. * This method allows to define the drawing buffer size by specifying
  40544. * width, height and pixel ratio all at once. The size of the drawing
  40545. * buffer is computed with this formula:
  40546. * ```js
  40547. * size.x = width * pixelRatio;
  40548. * size.y = height * pixelRatio;
  40549. * ```
  40550. *
  40551. * @param {number} width - The width in logical pixels.
  40552. * @param {number} height - The height in logical pixels.
  40553. * @param {number} pixelRatio - The pixel ratio.
  40554. */
  40555. setDrawingBufferSize( width, height, pixelRatio ) {
  40556. // Renderer can't be resized while presenting in XR.
  40557. if ( this.xr && this.xr.isPresenting ) return;
  40558. this._canvasTarget.setDrawingBufferSize( width, height, pixelRatio );
  40559. }
  40560. /**
  40561. * Sets the size of the renderer.
  40562. *
  40563. * @param {number} width - The width in logical pixels.
  40564. * @param {number} height - The height in logical pixels.
  40565. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  40566. */
  40567. setSize( width, height, updateStyle = true ) {
  40568. // Renderer can't be resized while presenting in XR.
  40569. if ( this.xr && this.xr.isPresenting ) return;
  40570. this._canvasTarget.setSize( width, height, updateStyle );
  40571. }
  40572. /**
  40573. * Defines a manual sort function for the opaque render list.
  40574. * Pass `null` to use the default sort.
  40575. *
  40576. * @param {Function} method - The sort function.
  40577. */
  40578. setOpaqueSort( method ) {
  40579. this._opaqueSort = method;
  40580. }
  40581. /**
  40582. * Defines a manual sort function for the transparent render list.
  40583. * Pass `null` to use the default sort.
  40584. *
  40585. * @param {Function} method - The sort function.
  40586. */
  40587. setTransparentSort( method ) {
  40588. this._transparentSort = method;
  40589. }
  40590. /**
  40591. * Returns the scissor rectangle.
  40592. *
  40593. * @param {Vector4} target - The method writes the result in this target object.
  40594. * @return {Vector4} The scissor rectangle.
  40595. */
  40596. getScissor( target ) {
  40597. return this._canvasTarget.getScissor( target );
  40598. }
  40599. /**
  40600. * Defines the scissor rectangle.
  40601. *
  40602. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  40603. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  40604. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  40605. * @param {number} width - The width of the scissor box in logical pixel unit.
  40606. * @param {number} height - The height of the scissor box in logical pixel unit.
  40607. */
  40608. setScissor( x, y, width, height ) {
  40609. this._canvasTarget.setScissor( x, y, width, height );
  40610. }
  40611. /**
  40612. * Returns the scissor test value.
  40613. *
  40614. * @return {boolean} Whether the scissor test should be enabled or not.
  40615. */
  40616. getScissorTest() {
  40617. return this._canvasTarget.getScissorTest();
  40618. }
  40619. /**
  40620. * Defines the scissor test.
  40621. *
  40622. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40623. */
  40624. setScissorTest( boolean ) {
  40625. this._canvasTarget.setScissorTest( boolean );
  40626. // TODO: Move it to CanvasTarget event listener.
  40627. this.backend.setScissorTest( boolean );
  40628. }
  40629. /**
  40630. * Returns the viewport definition.
  40631. *
  40632. * @param {Vector4} target - The method writes the result in this target object.
  40633. * @return {Vector4} The viewport definition.
  40634. */
  40635. getViewport( target ) {
  40636. return this._canvasTarget.getViewport( target );
  40637. }
  40638. /**
  40639. * Defines the viewport.
  40640. *
  40641. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40642. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40643. * @param {number} width - The width of the viewport in logical pixel unit.
  40644. * @param {number} height - The height of the viewport in logical pixel unit.
  40645. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40646. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40647. */
  40648. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40649. this._canvasTarget.setViewport( x, y, width, height, minDepth, maxDepth );
  40650. }
  40651. /**
  40652. * Returns the clear color.
  40653. *
  40654. * @param {Color} target - The method writes the result in this target object.
  40655. * @return {Color} The clear color.
  40656. */
  40657. getClearColor( target ) {
  40658. return target.copy( this._clearColor );
  40659. }
  40660. /**
  40661. * Defines the clear color and optionally the clear alpha.
  40662. *
  40663. * @param {Color} color - The clear color.
  40664. * @param {number} [alpha=1] - The clear alpha.
  40665. */
  40666. setClearColor( color, alpha = 1 ) {
  40667. this._clearColor.set( color );
  40668. this._clearColor.a = alpha;
  40669. }
  40670. /**
  40671. * Returns the clear alpha.
  40672. *
  40673. * @return {number} The clear alpha.
  40674. */
  40675. getClearAlpha() {
  40676. return this._clearColor.a;
  40677. }
  40678. /**
  40679. * Defines the clear alpha.
  40680. *
  40681. * @param {number} alpha - The clear alpha.
  40682. */
  40683. setClearAlpha( alpha ) {
  40684. this._clearColor.a = alpha;
  40685. }
  40686. /**
  40687. * Returns the clear depth.
  40688. *
  40689. * @return {number} The clear depth.
  40690. */
  40691. getClearDepth() {
  40692. return this._clearDepth;
  40693. }
  40694. /**
  40695. * Defines the clear depth.
  40696. *
  40697. * @param {number} depth - The clear depth.
  40698. */
  40699. setClearDepth( depth ) {
  40700. this._clearDepth = depth;
  40701. }
  40702. /**
  40703. * Returns the clear stencil.
  40704. *
  40705. * @return {number} The clear stencil.
  40706. */
  40707. getClearStencil() {
  40708. return this._clearStencil;
  40709. }
  40710. /**
  40711. * Defines the clear stencil.
  40712. *
  40713. * @param {number} stencil - The clear stencil.
  40714. */
  40715. setClearStencil( stencil ) {
  40716. this._clearStencil = stencil;
  40717. }
  40718. /**
  40719. * This method performs an occlusion query for the given 3D object.
  40720. * It returns `true` if the given 3D object is fully occluded by other
  40721. * 3D objects in the scene.
  40722. *
  40723. * @param {Object3D} object - The 3D object to test.
  40724. * @return {boolean} Whether the 3D object is fully occluded or not.
  40725. */
  40726. isOccluded( object ) {
  40727. const renderContext = this._currentRenderContext;
  40728. return renderContext && this.backend.isOccluded( renderContext, object );
  40729. }
  40730. /**
  40731. * Performs a manual clear operation. This method ignores `autoClear` properties.
  40732. *
  40733. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40734. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40735. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40736. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40737. * Only returned when the renderer has not been initialized.
  40738. */
  40739. clear( color = true, depth = true, stencil = true ) {
  40740. if ( this._initialized === false ) {
  40741. warn( 'Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  40742. return this.clearAsync( color, depth, stencil );
  40743. }
  40744. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40745. let renderContext = null;
  40746. if ( renderTarget !== null ) {
  40747. this._textures.updateRenderTarget( renderTarget );
  40748. const renderTargetData = this._textures.get( renderTarget );
  40749. renderContext = this._renderContexts.getForClear( renderTarget );
  40750. renderContext.textures = renderTargetData.textures;
  40751. renderContext.depthTexture = renderTargetData.depthTexture;
  40752. renderContext.width = renderTargetData.width;
  40753. renderContext.height = renderTargetData.height;
  40754. renderContext.renderTarget = renderTarget;
  40755. renderContext.depth = renderTarget.depthBuffer;
  40756. renderContext.stencil = renderTarget.stencilBuffer;
  40757. // #30329
  40758. renderContext.clearColorValue = this.backend.getClearColor();
  40759. renderContext.activeCubeFace = this.getActiveCubeFace();
  40760. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  40761. }
  40762. this.backend.clear( color, depth, stencil, renderContext );
  40763. if ( renderTarget !== null && this._renderTarget === null ) {
  40764. this._renderOutput( renderTarget );
  40765. }
  40766. }
  40767. /**
  40768. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  40769. *
  40770. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40771. * Only returned when the renderer has not been initialized.
  40772. */
  40773. clearColor() {
  40774. return this.clear( true, false, false );
  40775. }
  40776. /**
  40777. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  40778. *
  40779. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40780. * Only returned when the renderer has not been initialized.
  40781. */
  40782. clearDepth() {
  40783. return this.clear( false, true, false );
  40784. }
  40785. /**
  40786. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  40787. *
  40788. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40789. * Only returned when the renderer has not been initialized.
  40790. */
  40791. clearStencil() {
  40792. return this.clear( false, false, true );
  40793. }
  40794. /**
  40795. * Async version of {@link Renderer#clear}.
  40796. *
  40797. * @async
  40798. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40799. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40800. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40801. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40802. */
  40803. async clearAsync( color = true, depth = true, stencil = true ) {
  40804. if ( this._initialized === false ) await this.init();
  40805. this.clear( color, depth, stencil );
  40806. }
  40807. /**
  40808. * Async version of {@link Renderer#clearColor}.
  40809. *
  40810. * @async
  40811. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40812. */
  40813. async clearColorAsync() {
  40814. this.clearAsync( true, false, false );
  40815. }
  40816. /**
  40817. * Async version of {@link Renderer#clearDepth}.
  40818. *
  40819. * @async
  40820. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40821. */
  40822. async clearDepthAsync() {
  40823. this.clearAsync( false, true, false );
  40824. }
  40825. /**
  40826. * Async version of {@link Renderer#clearStencil}.
  40827. *
  40828. * @async
  40829. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40830. */
  40831. async clearStencilAsync() {
  40832. this.clearAsync( false, false, true );
  40833. }
  40834. /**
  40835. * Returns `true` if a framebuffer target is needed to perform tone mapping or color space conversion.
  40836. * If this is the case, the renderer allocates an internal render target for that purpose.
  40837. *
  40838. */
  40839. get needsFrameBufferTarget() {
  40840. const useToneMapping = this.currentToneMapping !== NoToneMapping;
  40841. const useColorSpace = this.currentColorSpace !== ColorManagement.workingColorSpace;
  40842. return useToneMapping || useColorSpace;
  40843. }
  40844. /**
  40845. * The number of samples used for multi-sample anti-aliasing (MSAA).
  40846. *
  40847. * @type {number}
  40848. * @default 0
  40849. */
  40850. get samples() {
  40851. return this._samples;
  40852. }
  40853. /**
  40854. * The current number of samples used for multi-sample anti-aliasing (MSAA).
  40855. *
  40856. * When rendering to a custom render target, the number of samples of that render target is used.
  40857. * If the renderer needs an internal framebuffer target for tone mapping or color space conversion,
  40858. * the number of samples is set to 0.
  40859. *
  40860. * @type {number}
  40861. */
  40862. get currentSamples() {
  40863. let samples = this._samples;
  40864. if ( this._renderTarget !== null ) {
  40865. samples = this._renderTarget.samples;
  40866. } else if ( this.needsFrameBufferTarget ) {
  40867. samples = 0;
  40868. }
  40869. return samples;
  40870. }
  40871. /**
  40872. * The current tone mapping of the renderer. When not producing screen output,
  40873. * the tone mapping is always `NoToneMapping`.
  40874. *
  40875. * @type {number}
  40876. */
  40877. get currentToneMapping() {
  40878. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  40879. }
  40880. /**
  40881. * The current color space of the renderer. When not producing screen output,
  40882. * the color space is always the working color space.
  40883. *
  40884. * @type {string}
  40885. */
  40886. get currentColorSpace() {
  40887. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  40888. }
  40889. /**
  40890. * Returns `true` if the rendering settings are set to screen output.
  40891. *
  40892. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  40893. */
  40894. get isOutputTarget() {
  40895. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  40896. }
  40897. /**
  40898. * Frees all internal resources of the renderer. Call this method if the renderer
  40899. * is no longer in use by your app.
  40900. */
  40901. dispose() {
  40902. if ( this._initialized === true ) {
  40903. this.info.dispose();
  40904. this.backend.dispose();
  40905. this._animation.dispose();
  40906. this._objects.dispose();
  40907. this._geometries.dispose();
  40908. this._pipelines.dispose();
  40909. this._nodes.dispose();
  40910. this._bindings.dispose();
  40911. this._renderLists.dispose();
  40912. this._renderContexts.dispose();
  40913. this._textures.dispose();
  40914. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  40915. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  40916. if ( queryPool !== null ) queryPool.dispose();
  40917. } );
  40918. }
  40919. this.setRenderTarget( null );
  40920. this.setAnimationLoop( null );
  40921. }
  40922. /**
  40923. * Sets the given render target. Calling this method means the renderer does not
  40924. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  40925. * Use `null` as the first argument to reset the state.
  40926. *
  40927. * @param {?RenderTarget} renderTarget - The render target to set.
  40928. * @param {number} [activeCubeFace=0] - The active cube face.
  40929. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  40930. */
  40931. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  40932. this._renderTarget = renderTarget;
  40933. this._activeCubeFace = activeCubeFace;
  40934. this._activeMipmapLevel = activeMipmapLevel;
  40935. }
  40936. /**
  40937. * Returns the current render target.
  40938. *
  40939. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  40940. */
  40941. getRenderTarget() {
  40942. return this._renderTarget;
  40943. }
  40944. /**
  40945. * Sets the output render target for the renderer.
  40946. *
  40947. * @param {Object} renderTarget - The render target to set as the output target.
  40948. */
  40949. setOutputRenderTarget( renderTarget ) {
  40950. this._outputRenderTarget = renderTarget;
  40951. }
  40952. /**
  40953. * Returns the current output target.
  40954. *
  40955. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  40956. */
  40957. getOutputRenderTarget() {
  40958. return this._outputRenderTarget;
  40959. }
  40960. /**
  40961. * Sets the canvas target. The canvas target manages the HTML canvas
  40962. * or the offscreen canvas the renderer draws into.
  40963. *
  40964. * @param {CanvasTarget} canvasTarget - The canvas target.
  40965. */
  40966. setCanvasTarget( canvasTarget ) {
  40967. this._canvasTarget.removeEventListener( 'resize', this._onCanvasTargetResize );
  40968. this._canvasTarget = canvasTarget;
  40969. this._canvasTarget.addEventListener( 'resize', this._onCanvasTargetResize );
  40970. }
  40971. /**
  40972. * Returns the current canvas target.
  40973. *
  40974. * @return {CanvasTarget} The current canvas target.
  40975. */
  40976. getCanvasTarget() {
  40977. return this._canvasTarget;
  40978. }
  40979. /**
  40980. * Resets the renderer to the initial state before WebXR started.
  40981. *
  40982. */
  40983. _resetXRState() {
  40984. this.backend.setXRTarget( null );
  40985. this.setOutputRenderTarget( null );
  40986. this.setRenderTarget( null );
  40987. this._frameBufferTarget.dispose();
  40988. this._frameBufferTarget = null;
  40989. }
  40990. /**
  40991. * Callback for {@link Renderer#setRenderObjectFunction}.
  40992. *
  40993. * @callback renderObjectFunction
  40994. * @param {Object3D} object - The 3D object.
  40995. * @param {Scene} scene - The scene the 3D object belongs to.
  40996. * @param {Camera} camera - The camera the object should be rendered with.
  40997. * @param {BufferGeometry} geometry - The object's geometry.
  40998. * @param {Material} material - The object's material.
  40999. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41000. * @param {LightsNode} lightsNode - The current lights node.
  41001. * @param {ClippingContext} clippingContext - The clipping context.
  41002. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41003. */
  41004. /**
  41005. * Sets the given render object function. Calling this method overwrites the default implementation
  41006. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  41007. * if you want to modify the way objects are rendered. For example you can define things like "every
  41008. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  41009. * The custom function must always call `renderObject()` in its implementation.
  41010. *
  41011. * Use `null` as the first argument to reset the state.
  41012. *
  41013. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  41014. */
  41015. setRenderObjectFunction( renderObjectFunction ) {
  41016. this._renderObjectFunction = renderObjectFunction;
  41017. }
  41018. /**
  41019. * Returns the current render object function.
  41020. *
  41021. * @return {?Function} The current render object function. Returns `null` if no function is set.
  41022. */
  41023. getRenderObjectFunction() {
  41024. return this._renderObjectFunction;
  41025. }
  41026. /**
  41027. * Execute a single or an array of compute nodes. This method can only be called
  41028. * if the renderer has been initialized.
  41029. *
  41030. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41031. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  41032. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  41033. */
  41034. compute( computeNodes, dispatchSizeOrCount = null ) {
  41035. if ( this._isDeviceLost === true ) return;
  41036. if ( this._initialized === false ) {
  41037. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  41038. return this.computeAsync( computeNodes );
  41039. }
  41040. //
  41041. const nodeFrame = this._nodes.nodeFrame;
  41042. const previousRenderId = nodeFrame.renderId;
  41043. //
  41044. this.info.calls ++;
  41045. this.info.compute.calls ++;
  41046. this.info.compute.frameCalls ++;
  41047. nodeFrame.renderId = this.info.calls;
  41048. //
  41049. this.backend.updateTimeStampUID( computeNodes );
  41050. this.inspector.beginCompute( this.backend.getTimestampUID( computeNodes ), computeNodes );
  41051. //
  41052. const backend = this.backend;
  41053. const pipelines = this._pipelines;
  41054. const bindings = this._bindings;
  41055. const nodes = this._nodes;
  41056. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  41057. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  41058. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  41059. }
  41060. backend.beginCompute( computeNodes );
  41061. for ( const computeNode of computeList ) {
  41062. // onInit
  41063. if ( pipelines.has( computeNode ) === false ) {
  41064. const dispose = () => {
  41065. computeNode.removeEventListener( 'dispose', dispose );
  41066. pipelines.delete( computeNode );
  41067. bindings.deleteForCompute( computeNode );
  41068. nodes.delete( computeNode );
  41069. };
  41070. computeNode.addEventListener( 'dispose', dispose );
  41071. //
  41072. const onInitFn = computeNode.onInitFunction;
  41073. if ( onInitFn !== null ) {
  41074. onInitFn.call( computeNode, { renderer: this } );
  41075. }
  41076. }
  41077. nodes.updateForCompute( computeNode );
  41078. bindings.updateForCompute( computeNode );
  41079. const computeBindings = bindings.getForCompute( computeNode );
  41080. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  41081. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  41082. }
  41083. backend.finishCompute( computeNodes );
  41084. //
  41085. nodeFrame.renderId = previousRenderId;
  41086. //
  41087. this.inspector.finishCompute( this.backend.getTimestampUID( computeNodes ) );
  41088. }
  41089. /**
  41090. * Execute a single or an array of compute nodes.
  41091. *
  41092. * @async
  41093. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  41094. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  41095. * @return {Promise} A Promise that resolve when the compute has finished.
  41096. */
  41097. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  41098. if ( this._initialized === false ) await this.init();
  41099. this._inspector.computeAsync( computeNodes, dispatchSizeOrCount );
  41100. this.compute( computeNodes, dispatchSizeOrCount );
  41101. }
  41102. /**
  41103. * Checks if the given feature is supported by the selected backend.
  41104. *
  41105. * @async
  41106. * @param {string} name - The feature's name.
  41107. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  41108. */
  41109. async hasFeatureAsync( name ) {
  41110. if ( this._initialized === false ) await this.init();
  41111. return this.backend.hasFeature( name );
  41112. }
  41113. async resolveTimestampsAsync( type = 'render' ) {
  41114. if ( this._initialized === false ) await this.init();
  41115. return this.backend.resolveTimestampsAsync( type );
  41116. }
  41117. /**
  41118. * Checks if the given feature is supported by the selected backend. If the
  41119. * renderer has not been initialized, this method always returns `false`.
  41120. *
  41121. * @param {string} name - The feature's name.
  41122. * @return {boolean} Whether the feature is supported or not.
  41123. */
  41124. hasFeature( name ) {
  41125. if ( this._initialized === false ) {
  41126. warn( 'Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  41127. return false;
  41128. }
  41129. return this.backend.hasFeature( name );
  41130. }
  41131. /**
  41132. * Returns `true` when the renderer has been initialized.
  41133. *
  41134. * @return {boolean} Whether the renderer has been initialized or not.
  41135. */
  41136. hasInitialized() {
  41137. return this._initialized;
  41138. }
  41139. /**
  41140. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  41141. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41142. *
  41143. * @async
  41144. * @param {Texture} texture - The texture.
  41145. * @return {Promise} A Promise that resolves when the texture has been initialized.
  41146. */
  41147. async initTextureAsync( texture ) {
  41148. if ( this._initialized === false ) await this.init();
  41149. this._textures.updateTexture( texture );
  41150. }
  41151. /**
  41152. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  41153. * (which can cause noticeable lags due to decode and GPU upload overhead).
  41154. *
  41155. * This method can only be used if the renderer has been initialized.
  41156. *
  41157. * @param {Texture} texture - The texture.
  41158. */
  41159. initTexture( texture ) {
  41160. if ( this._initialized === false ) {
  41161. warn( 'Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  41162. }
  41163. this._textures.updateTexture( texture );
  41164. }
  41165. /**
  41166. * Copies the current bound framebuffer into the given texture.
  41167. *
  41168. * @param {FramebufferTexture} framebufferTexture - The texture.
  41169. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  41170. */
  41171. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  41172. if ( rectangle !== null ) {
  41173. if ( rectangle.isVector2 ) {
  41174. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  41175. } else if ( rectangle.isVector4 ) {
  41176. rectangle = _vector4.copy( rectangle ).floor();
  41177. } else {
  41178. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  41179. return;
  41180. }
  41181. } else {
  41182. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  41183. }
  41184. //
  41185. let renderContext = this._currentRenderContext;
  41186. let renderTarget;
  41187. if ( renderContext !== null ) {
  41188. renderTarget = renderContext.renderTarget;
  41189. } else {
  41190. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  41191. if ( renderTarget !== null ) {
  41192. this._textures.updateRenderTarget( renderTarget );
  41193. renderContext = this._textures.get( renderTarget );
  41194. }
  41195. }
  41196. //
  41197. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  41198. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  41199. this._inspector.copyFramebufferToTexture( framebufferTexture );
  41200. }
  41201. /**
  41202. * Copies data of the given source texture into a destination texture.
  41203. *
  41204. * @param {Texture} srcTexture - The source texture.
  41205. * @param {Texture} dstTexture - The destination texture.
  41206. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  41207. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  41208. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41209. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41210. */
  41211. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  41212. this._textures.updateTexture( srcTexture );
  41213. this._textures.updateTexture( dstTexture );
  41214. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  41215. this._inspector.copyTextureToTexture( srcTexture, dstTexture );
  41216. }
  41217. /**
  41218. * Reads pixel data from the given render target.
  41219. *
  41220. * @async
  41221. * @param {RenderTarget} renderTarget - The render target to read from.
  41222. * @param {number} x - The `x` coordinate of the copy region's origin.
  41223. * @param {number} y - The `y` coordinate of the copy region's origin.
  41224. * @param {number} width - The width of the copy region.
  41225. * @param {number} height - The height of the copy region.
  41226. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  41227. * @param {number} [faceIndex=0] - The active cube face index.
  41228. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  41229. */
  41230. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  41231. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  41232. }
  41233. /**
  41234. * Analyzes the given 3D object's hierarchy and builds render lists from the
  41235. * processed hierarchy.
  41236. *
  41237. * @param {Object3D} object - The 3D object to process (usually a scene).
  41238. * @param {Camera} camera - The camera the object is rendered with.
  41239. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  41240. * @param {RenderList} renderList - The current render list.
  41241. * @param {ClippingContext} clippingContext - The current clipping context.
  41242. */
  41243. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  41244. if ( object.visible === false ) return;
  41245. const visible = object.layers.test( camera.layers );
  41246. if ( visible ) {
  41247. if ( object.isGroup ) {
  41248. groupOrder = object.renderOrder;
  41249. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  41250. } else if ( object.isLOD ) {
  41251. if ( object.autoUpdate === true ) object.update( camera );
  41252. } else if ( object.isLight ) {
  41253. renderList.pushLight( object );
  41254. } else if ( object.isSprite ) {
  41255. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41256. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  41257. if ( this.sortObjects === true ) {
  41258. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  41259. }
  41260. const { geometry, material } = object;
  41261. if ( material.visible ) {
  41262. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41263. }
  41264. }
  41265. } else if ( object.isLineLoop ) {
  41266. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  41267. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  41268. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  41269. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  41270. const { geometry, material } = object;
  41271. if ( this.sortObjects === true ) {
  41272. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  41273. _vector4
  41274. .copy( geometry.boundingSphere.center )
  41275. .applyMatrix4( object.matrixWorld )
  41276. .applyMatrix4( _projScreenMatrix );
  41277. }
  41278. if ( Array.isArray( material ) ) {
  41279. const groups = geometry.groups;
  41280. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  41281. const group = groups[ i ];
  41282. const groupMaterial = material[ group.materialIndex ];
  41283. if ( groupMaterial && groupMaterial.visible ) {
  41284. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  41285. }
  41286. }
  41287. } else if ( material.visible ) {
  41288. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  41289. }
  41290. }
  41291. }
  41292. }
  41293. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  41294. const baseRenderList = renderList;
  41295. // replace render list
  41296. renderList = this._renderLists.get( object, camera );
  41297. renderList.begin();
  41298. baseRenderList.pushBundle( {
  41299. bundleGroup: object,
  41300. camera,
  41301. renderList,
  41302. } );
  41303. renderList.finish();
  41304. }
  41305. const children = object.children;
  41306. for ( let i = 0, l = children.length; i < l; i ++ ) {
  41307. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  41308. }
  41309. }
  41310. /**
  41311. * Renders the given render bundles.
  41312. *
  41313. * @private
  41314. * @param {Array<Object>} bundles - Array with render bundle data.
  41315. * @param {Scene} sceneRef - The scene the render bundles belong to.
  41316. * @param {LightsNode} lightsNode - The current lights node.
  41317. */
  41318. _renderBundles( bundles, sceneRef, lightsNode ) {
  41319. for ( const bundle of bundles ) {
  41320. this._renderBundle( bundle, sceneRef, lightsNode );
  41321. }
  41322. }
  41323. /**
  41324. * Renders the transparent objects from the given render lists.
  41325. *
  41326. * @private
  41327. * @param {Array<Object>} renderList - The transparent render list.
  41328. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  41329. * @param {Camera} camera - The camera the render list should be rendered with.
  41330. * @param {Scene} scene - The scene the render list belongs to.
  41331. * @param {LightsNode} lightsNode - The current lights node.
  41332. */
  41333. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  41334. if ( doublePassList.length > 0 ) {
  41335. // render back side
  41336. for ( const { material } of doublePassList ) {
  41337. material.side = BackSide;
  41338. }
  41339. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  41340. // render front side
  41341. for ( const { material } of doublePassList ) {
  41342. material.side = FrontSide;
  41343. }
  41344. this._renderObjects( renderList, camera, scene, lightsNode );
  41345. // restore
  41346. for ( const { material } of doublePassList ) {
  41347. material.side = DoubleSide;
  41348. }
  41349. } else {
  41350. this._renderObjects( renderList, camera, scene, lightsNode );
  41351. }
  41352. }
  41353. /**
  41354. * Renders the objects from the given render list.
  41355. *
  41356. * @private
  41357. * @param {Array<Object>} renderList - The render list.
  41358. * @param {Camera} camera - The camera the render list should be rendered with.
  41359. * @param {Scene} scene - The scene the render list belongs to.
  41360. * @param {LightsNode} lightsNode - The current lights node.
  41361. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41362. */
  41363. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  41364. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  41365. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  41366. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  41367. }
  41368. }
  41369. /**
  41370. * Retrieves shadow nodes for the given material. This is used to setup shadow passes.
  41371. * The result is cached per material and updated when the material's version changes.
  41372. *
  41373. * @param {Material} material
  41374. * @returns {Object} - The shadow nodes for the material.
  41375. */
  41376. _getShadowNodes( material ) {
  41377. const version = material.version;
  41378. let cache = this._cacheShadowNodes.get( material );
  41379. if ( cache === undefined || cache.version !== version ) {
  41380. const hasMap = material.map !== null;
  41381. const hasColorNode = material.colorNode && material.colorNode.isNode;
  41382. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  41383. let positionNode = null;
  41384. let colorNode = null;
  41385. let depthNode = null;
  41386. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  41387. let shadowRGB;
  41388. let shadowAlpha;
  41389. if ( hasCastShadowNode ) {
  41390. shadowRGB = material.castShadowNode.rgb;
  41391. shadowAlpha = material.castShadowNode.a;
  41392. } else {
  41393. shadowRGB = vec3( 0 );
  41394. shadowAlpha = float( 1 );
  41395. }
  41396. if ( hasMap ) {
  41397. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  41398. }
  41399. if ( hasColorNode ) {
  41400. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  41401. }
  41402. colorNode = vec4( shadowRGB, shadowAlpha );
  41403. }
  41404. if ( material.depthNode && material.depthNode.isNode ) {
  41405. depthNode = material.depthNode;
  41406. }
  41407. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  41408. positionNode = material.castShadowPositionNode;
  41409. } else if ( material.positionNode && material.positionNode.isNode ) {
  41410. positionNode = material.positionNode;
  41411. }
  41412. cache = {
  41413. version,
  41414. colorNode,
  41415. depthNode,
  41416. positionNode
  41417. };
  41418. this._cacheShadowNodes.set( material, cache );
  41419. }
  41420. return cache;
  41421. }
  41422. /**
  41423. * This method represents the default render object function that manages the render lifecycle
  41424. * of the object.
  41425. *
  41426. * @param {Object3D} object - The 3D object.
  41427. * @param {Scene} scene - The scene the 3D object belongs to.
  41428. * @param {Camera} camera - The camera the object should be rendered with.
  41429. * @param {BufferGeometry} geometry - The object's geometry.
  41430. * @param {Material} material - The object's material.
  41431. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41432. * @param {LightsNode} lightsNode - The current lights node.
  41433. * @param {?ClippingContext} clippingContext - The clipping context.
  41434. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  41435. */
  41436. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  41437. let materialOverride = false;
  41438. let materialColorNode;
  41439. let materialDepthNode;
  41440. let materialPositionNode;
  41441. let materialSide;
  41442. //
  41443. object.onBeforeRender( this, scene, camera, geometry, material, group );
  41444. //
  41445. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  41446. const overrideMaterial = scene.overrideMaterial;
  41447. materialOverride = true;
  41448. // store original nodes
  41449. materialColorNode = scene.overrideMaterial.colorNode;
  41450. materialDepthNode = scene.overrideMaterial.depthNode;
  41451. materialPositionNode = scene.overrideMaterial.positionNode;
  41452. materialSide = scene.overrideMaterial.side;
  41453. if ( material.positionNode && material.positionNode.isNode ) {
  41454. overrideMaterial.positionNode = material.positionNode;
  41455. }
  41456. overrideMaterial.alphaTest = material.alphaTest;
  41457. overrideMaterial.alphaMap = material.alphaMap;
  41458. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  41459. if ( overrideMaterial.isShadowPassMaterial ) {
  41460. const { colorNode, depthNode, positionNode } = this._getShadowNodes( material );
  41461. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  41462. if ( colorNode !== null ) overrideMaterial.colorNode = colorNode;
  41463. if ( depthNode !== null ) overrideMaterial.depthNode = depthNode;
  41464. if ( positionNode !== null ) overrideMaterial.positionNode = positionNode;
  41465. }
  41466. material = overrideMaterial;
  41467. }
  41468. //
  41469. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  41470. material.side = BackSide;
  41471. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  41472. material.side = FrontSide;
  41473. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  41474. material.side = DoubleSide;
  41475. } else {
  41476. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  41477. }
  41478. //
  41479. if ( materialOverride ) {
  41480. scene.overrideMaterial.colorNode = materialColorNode;
  41481. scene.overrideMaterial.depthNode = materialDepthNode;
  41482. scene.overrideMaterial.positionNode = materialPositionNode;
  41483. scene.overrideMaterial.side = materialSide;
  41484. }
  41485. //
  41486. object.onAfterRender( this, scene, camera, geometry, material, group );
  41487. }
  41488. /**
  41489. * This method represents the default `_handleObjectFunction` implementation which creates
  41490. * a render object from the given data and performs the draw command with the selected backend.
  41491. *
  41492. * @private
  41493. * @param {Object3D} object - The 3D object.
  41494. * @param {Material} material - The object's material.
  41495. * @param {Scene} scene - The scene the 3D object belongs to.
  41496. * @param {Camera} camera - The camera the object should be rendered with.
  41497. * @param {LightsNode} lightsNode - The current lights node.
  41498. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41499. * @param {ClippingContext} clippingContext - The clipping context.
  41500. * @param {string} [passId] - An optional ID for identifying the pass.
  41501. */
  41502. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  41503. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  41504. renderObject.drawRange = object.geometry.drawRange;
  41505. renderObject.group = group;
  41506. //
  41507. const needsRefresh = this._nodes.needsRefresh( renderObject );
  41508. if ( needsRefresh ) {
  41509. this._nodes.updateBefore( renderObject );
  41510. this._geometries.updateForRender( renderObject );
  41511. this._nodes.updateForRender( renderObject );
  41512. this._bindings.updateForRender( renderObject );
  41513. }
  41514. this._pipelines.updateForRender( renderObject );
  41515. //
  41516. if ( this._currentRenderBundle !== null ) {
  41517. const renderBundleData = this.backend.get( this._currentRenderBundle );
  41518. renderBundleData.renderObjects.push( renderObject );
  41519. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  41520. }
  41521. this.backend.draw( renderObject, this.info );
  41522. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  41523. }
  41524. /**
  41525. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  41526. * Used in `compileAsync()`.
  41527. *
  41528. * @private
  41529. * @param {Object3D} object - The 3D object.
  41530. * @param {Material} material - The object's material.
  41531. * @param {Scene} scene - The scene the 3D object belongs to.
  41532. * @param {Camera} camera - The camera the object should be rendered with.
  41533. * @param {LightsNode} lightsNode - The current lights node.
  41534. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  41535. * @param {ClippingContext} clippingContext - The clipping context.
  41536. * @param {string} [passId] - An optional ID for identifying the pass.
  41537. */
  41538. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  41539. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  41540. renderObject.drawRange = object.geometry.drawRange;
  41541. renderObject.group = group;
  41542. //
  41543. this._nodes.updateBefore( renderObject );
  41544. this._geometries.updateForRender( renderObject );
  41545. this._nodes.updateForRender( renderObject );
  41546. this._bindings.updateForRender( renderObject );
  41547. this._pipelines.getForRender( renderObject, this._compilationPromises );
  41548. this._nodes.updateAfter( renderObject );
  41549. }
  41550. /**
  41551. * Callback when the canvas has been resized.
  41552. *
  41553. * @private
  41554. */
  41555. _onCanvasTargetResize() {
  41556. if ( this._initialized ) this.backend.updateSize();
  41557. }
  41558. /**
  41559. * Alias for `compileAsync()`.
  41560. *
  41561. * @method
  41562. * @param {Object3D} scene - The scene or 3D object to precompile.
  41563. * @param {Camera} camera - The camera that is used to render the scene.
  41564. * @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.
  41565. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  41566. */
  41567. get compile() {
  41568. return this.compileAsync;
  41569. }
  41570. }
  41571. /**
  41572. * A binding represents the connection between a resource (like a texture, sampler
  41573. * or uniform buffer) and the resource definition in a shader stage.
  41574. *
  41575. * This module is an abstract base class for all concrete bindings types.
  41576. *
  41577. * @abstract
  41578. * @private
  41579. */
  41580. class Binding {
  41581. /**
  41582. * Constructs a new binding.
  41583. *
  41584. * @param {string} [name=''] - The binding's name.
  41585. */
  41586. constructor( name = '' ) {
  41587. /**
  41588. * The binding's name.
  41589. *
  41590. * @type {string}
  41591. */
  41592. this.name = name;
  41593. /**
  41594. * A bitmask that defines in what shader stages the
  41595. * binding's resource is accessible.
  41596. *
  41597. * @type {number}
  41598. */
  41599. this.visibility = 0;
  41600. }
  41601. /**
  41602. * Makes sure binding's resource is visible for the given shader stage.
  41603. *
  41604. * @param {number} visibility - The shader stage.
  41605. */
  41606. setVisibility( visibility ) {
  41607. this.visibility |= visibility;
  41608. }
  41609. /**
  41610. * Clones the binding.
  41611. *
  41612. * @return {Binding} The cloned binding.
  41613. */
  41614. clone() {
  41615. return Object.assign( new this.constructor(), this );
  41616. }
  41617. }
  41618. /**
  41619. * This function is usually called with the length in bytes of an array buffer.
  41620. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  41621. *
  41622. * @function
  41623. * @param {number} floatLength - The buffer length.
  41624. * @return {number} The padded length.
  41625. */
  41626. function getFloatLength( floatLength ) {
  41627. // ensure chunk size alignment (STD140 layout)
  41628. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  41629. }
  41630. /**
  41631. * Represents a buffer binding type.
  41632. *
  41633. * @private
  41634. * @abstract
  41635. * @augments Binding
  41636. */
  41637. class Buffer extends Binding {
  41638. /**
  41639. * Constructs a new buffer.
  41640. *
  41641. * @param {string} name - The buffer's name.
  41642. * @param {TypedArray} [buffer=null] - The buffer.
  41643. */
  41644. constructor( name, buffer = null ) {
  41645. super( name );
  41646. /**
  41647. * This flag can be used for type testing.
  41648. *
  41649. * @type {boolean}
  41650. * @readonly
  41651. * @default true
  41652. */
  41653. this.isBuffer = true;
  41654. /**
  41655. * The bytes per element.
  41656. *
  41657. * @type {number}
  41658. */
  41659. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  41660. /**
  41661. * A reference to the internal buffer.
  41662. *
  41663. * @private
  41664. * @type {TypedArray}
  41665. */
  41666. this._buffer = buffer;
  41667. }
  41668. /**
  41669. * The buffer's byte length.
  41670. *
  41671. * @type {number}
  41672. * @readonly
  41673. */
  41674. get byteLength() {
  41675. return getFloatLength( this._buffer.byteLength );
  41676. }
  41677. /**
  41678. * A reference to the internal buffer.
  41679. *
  41680. * @type {Float32Array}
  41681. * @readonly
  41682. */
  41683. get buffer() {
  41684. return this._buffer;
  41685. }
  41686. /**
  41687. * Updates the binding.
  41688. *
  41689. * @return {boolean} Whether the buffer has been updated and must be
  41690. * uploaded to the GPU.
  41691. */
  41692. update() {
  41693. return true;
  41694. }
  41695. }
  41696. /**
  41697. * Represents a uniform buffer binding type.
  41698. *
  41699. * @private
  41700. * @augments Buffer
  41701. */
  41702. class UniformBuffer extends Buffer {
  41703. /**
  41704. * Constructs a new uniform buffer.
  41705. *
  41706. * @param {string} name - The buffer's name.
  41707. * @param {TypedArray} [buffer=null] - The buffer.
  41708. */
  41709. constructor( name, buffer = null ) {
  41710. super( name, buffer );
  41711. /**
  41712. * This flag can be used for type testing.
  41713. *
  41714. * @type {boolean}
  41715. * @readonly
  41716. * @default true
  41717. */
  41718. this.isUniformBuffer = true;
  41719. }
  41720. }
  41721. let _id$4 = 0;
  41722. /**
  41723. * A special form of uniform buffer binding type.
  41724. * It's buffer value is managed by a node object.
  41725. *
  41726. * @private
  41727. * @augments UniformBuffer
  41728. */
  41729. class NodeUniformBuffer extends UniformBuffer {
  41730. /**
  41731. * Constructs a new node-based uniform buffer.
  41732. *
  41733. * @param {BufferNode} nodeUniform - The uniform buffer node.
  41734. * @param {UniformGroupNode} groupNode - The uniform group node.
  41735. */
  41736. constructor( nodeUniform, groupNode ) {
  41737. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  41738. /**
  41739. * The uniform buffer node.
  41740. *
  41741. * @type {BufferNode}
  41742. */
  41743. this.nodeUniform = nodeUniform;
  41744. /**
  41745. * The uniform group node.
  41746. *
  41747. * @type {UniformGroupNode}
  41748. */
  41749. this.groupNode = groupNode;
  41750. }
  41751. /**
  41752. * The uniform buffer.
  41753. *
  41754. * @type {Float32Array}
  41755. */
  41756. get buffer() {
  41757. return this.nodeUniform.value;
  41758. }
  41759. }
  41760. /**
  41761. * This class represents a uniform buffer binding but with
  41762. * an API that allows to maintain individual uniform objects.
  41763. *
  41764. * @private
  41765. * @augments UniformBuffer
  41766. */
  41767. class UniformsGroup extends UniformBuffer {
  41768. /**
  41769. * Constructs a new uniforms group.
  41770. *
  41771. * @param {string} name - The group's name.
  41772. */
  41773. constructor( name ) {
  41774. super( name );
  41775. /**
  41776. * This flag can be used for type testing.
  41777. *
  41778. * @type {boolean}
  41779. * @readonly
  41780. * @default true
  41781. */
  41782. this.isUniformsGroup = true;
  41783. /**
  41784. * An array with the raw uniform values.
  41785. *
  41786. * @private
  41787. * @type {?Array<number>}
  41788. * @default null
  41789. */
  41790. this._values = null;
  41791. /**
  41792. * An array of uniform objects.
  41793. *
  41794. * The order of uniforms in this array must match the order of uniforms in the shader.
  41795. *
  41796. * @type {Array<Uniform>}
  41797. */
  41798. this.uniforms = [];
  41799. }
  41800. /**
  41801. * Adds a uniform to this group.
  41802. *
  41803. * @param {Uniform} uniform - The uniform to add.
  41804. * @return {UniformsGroup} A reference to this group.
  41805. */
  41806. addUniform( uniform ) {
  41807. this.uniforms.push( uniform );
  41808. return this;
  41809. }
  41810. /**
  41811. * Removes a uniform from this group.
  41812. *
  41813. * @param {Uniform} uniform - The uniform to remove.
  41814. * @return {UniformsGroup} A reference to this group.
  41815. */
  41816. removeUniform( uniform ) {
  41817. const index = this.uniforms.indexOf( uniform );
  41818. if ( index !== -1 ) {
  41819. this.uniforms.splice( index, 1 );
  41820. }
  41821. return this;
  41822. }
  41823. /**
  41824. * An array with the raw uniform values.
  41825. *
  41826. * @type {Array<number>}
  41827. */
  41828. get values() {
  41829. if ( this._values === null ) {
  41830. this._values = Array.from( this.buffer );
  41831. }
  41832. return this._values;
  41833. }
  41834. /**
  41835. * A Float32 array buffer with the uniform values.
  41836. *
  41837. * @type {Float32Array}
  41838. */
  41839. get buffer() {
  41840. let buffer = this._buffer;
  41841. if ( buffer === null ) {
  41842. const byteLength = this.byteLength;
  41843. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  41844. this._buffer = buffer;
  41845. }
  41846. return buffer;
  41847. }
  41848. /**
  41849. * The byte length of the buffer with correct buffer alignment.
  41850. *
  41851. * @type {number}
  41852. */
  41853. get byteLength() {
  41854. const bytesPerElement = this.bytesPerElement;
  41855. let offset = 0; // global buffer offset in bytes
  41856. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  41857. const uniform = this.uniforms[ i ];
  41858. const boundary = uniform.boundary;
  41859. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  41860. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  41861. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  41862. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  41863. offset += chunkPadding;
  41864. // Check for chunk overflow
  41865. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  41866. // Add padding to the end of the chunk
  41867. offset += ( GPU_CHUNK_BYTES - chunkStart );
  41868. }
  41869. uniform.offset = offset / bytesPerElement;
  41870. offset += itemSize;
  41871. }
  41872. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  41873. }
  41874. /**
  41875. * Updates this group by updating each uniform object of
  41876. * the internal uniform list. The uniform objects check if their
  41877. * values has actually changed so this method only returns
  41878. * `true` if there is a real value change.
  41879. *
  41880. * @return {boolean} Whether the uniforms have been updated and
  41881. * must be uploaded to the GPU.
  41882. */
  41883. update() {
  41884. let updated = false;
  41885. for ( const uniform of this.uniforms ) {
  41886. if ( this.updateByType( uniform ) === true ) {
  41887. updated = true;
  41888. }
  41889. }
  41890. return updated;
  41891. }
  41892. /**
  41893. * Updates a given uniform by calling an update method matching
  41894. * the uniforms type.
  41895. *
  41896. * @param {Uniform} uniform - The uniform to update.
  41897. * @return {boolean} Whether the uniform has been updated or not.
  41898. */
  41899. updateByType( uniform ) {
  41900. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  41901. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  41902. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  41903. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  41904. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  41905. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  41906. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  41907. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  41908. }
  41909. /**
  41910. * Updates a given Number uniform.
  41911. *
  41912. * @param {NumberUniform} uniform - The Number uniform.
  41913. * @return {boolean} Whether the uniform has been updated or not.
  41914. */
  41915. updateNumber( uniform ) {
  41916. let updated = false;
  41917. const a = this.values;
  41918. const v = uniform.getValue();
  41919. const offset = uniform.offset;
  41920. const type = uniform.getType();
  41921. if ( a[ offset ] !== v ) {
  41922. const b = this._getBufferForType( type );
  41923. b[ offset ] = a[ offset ] = v;
  41924. updated = true;
  41925. }
  41926. return updated;
  41927. }
  41928. /**
  41929. * Updates a given Vector2 uniform.
  41930. *
  41931. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  41932. * @return {boolean} Whether the uniform has been updated or not.
  41933. */
  41934. updateVector2( uniform ) {
  41935. let updated = false;
  41936. const a = this.values;
  41937. const v = uniform.getValue();
  41938. const offset = uniform.offset;
  41939. const type = uniform.getType();
  41940. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  41941. const b = this._getBufferForType( type );
  41942. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  41943. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  41944. updated = true;
  41945. }
  41946. return updated;
  41947. }
  41948. /**
  41949. * Updates a given Vector3 uniform.
  41950. *
  41951. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  41952. * @return {boolean} Whether the uniform has been updated or not.
  41953. */
  41954. updateVector3( uniform ) {
  41955. let updated = false;
  41956. const a = this.values;
  41957. const v = uniform.getValue();
  41958. const offset = uniform.offset;
  41959. const type = uniform.getType();
  41960. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  41961. const b = this._getBufferForType( type );
  41962. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  41963. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  41964. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  41965. updated = true;
  41966. }
  41967. return updated;
  41968. }
  41969. /**
  41970. * Updates a given Vector4 uniform.
  41971. *
  41972. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  41973. * @return {boolean} Whether the uniform has been updated or not.
  41974. */
  41975. updateVector4( uniform ) {
  41976. let updated = false;
  41977. const a = this.values;
  41978. const v = uniform.getValue();
  41979. const offset = uniform.offset;
  41980. const type = uniform.getType();
  41981. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  41982. const b = this._getBufferForType( type );
  41983. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  41984. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  41985. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  41986. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  41987. updated = true;
  41988. }
  41989. return updated;
  41990. }
  41991. /**
  41992. * Updates a given Color uniform.
  41993. *
  41994. * @param {ColorUniform} uniform - The Color uniform.
  41995. * @return {boolean} Whether the uniform has been updated or not.
  41996. */
  41997. updateColor( uniform ) {
  41998. let updated = false;
  41999. const a = this.values;
  42000. const c = uniform.getValue();
  42001. const offset = uniform.offset;
  42002. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  42003. const b = this.buffer;
  42004. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  42005. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  42006. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  42007. updated = true;
  42008. }
  42009. return updated;
  42010. }
  42011. /**
  42012. * Updates a given Matrix3 uniform.
  42013. *
  42014. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  42015. * @return {boolean} Whether the uniform has been updated or not.
  42016. */
  42017. updateMatrix3( uniform ) {
  42018. let updated = false;
  42019. const a = this.values;
  42020. const e = uniform.getValue().elements;
  42021. const offset = uniform.offset;
  42022. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  42023. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  42024. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  42025. const b = this.buffer;
  42026. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  42027. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  42028. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  42029. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  42030. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  42031. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  42032. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  42033. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  42034. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  42035. updated = true;
  42036. }
  42037. return updated;
  42038. }
  42039. /**
  42040. * Updates a given Matrix4 uniform.
  42041. *
  42042. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  42043. * @return {boolean} Whether the uniform has been updated or not.
  42044. */
  42045. updateMatrix4( uniform ) {
  42046. let updated = false;
  42047. const a = this.values;
  42048. const e = uniform.getValue().elements;
  42049. const offset = uniform.offset;
  42050. if ( arraysEqual( a, e, offset ) === false ) {
  42051. const b = this.buffer;
  42052. b.set( e, offset );
  42053. setArray( a, e, offset );
  42054. updated = true;
  42055. }
  42056. return updated;
  42057. }
  42058. /**
  42059. * Returns a typed array that matches the given data type.
  42060. *
  42061. * @param {string} type - The data type.
  42062. * @return {TypedArray} The typed array.
  42063. */
  42064. _getBufferForType( type ) {
  42065. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  42066. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  42067. return this.buffer;
  42068. }
  42069. }
  42070. /**
  42071. * Sets the values of the second array to the first array.
  42072. *
  42073. * @private
  42074. * @param {TypedArray} a - The first array.
  42075. * @param {TypedArray} b - The second array.
  42076. * @param {number} offset - An index offset for the first array.
  42077. */
  42078. function setArray( a, b, offset ) {
  42079. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42080. a[ offset + i ] = b[ i ];
  42081. }
  42082. }
  42083. /**
  42084. * Returns `true` if the given arrays are equal.
  42085. *
  42086. * @private
  42087. * @param {TypedArray} a - The first array.
  42088. * @param {TypedArray} b - The second array.
  42089. * @param {number} offset - An index offset for the first array.
  42090. * @return {boolean} Whether the given arrays are equal or not.
  42091. */
  42092. function arraysEqual( a, b, offset ) {
  42093. for ( let i = 0, l = b.length; i < l; i ++ ) {
  42094. if ( a[ offset + i ] !== b[ i ] ) return false;
  42095. }
  42096. return true;
  42097. }
  42098. let _id$3 = 0;
  42099. /**
  42100. * A special form of uniforms group that represents
  42101. * the individual uniforms as node-based uniforms.
  42102. *
  42103. * @private
  42104. * @augments UniformsGroup
  42105. */
  42106. class NodeUniformsGroup extends UniformsGroup {
  42107. /**
  42108. * Constructs a new node-based uniforms group.
  42109. *
  42110. * @param {string} name - The group's name.
  42111. * @param {UniformGroupNode} groupNode - The uniform group node.
  42112. */
  42113. constructor( name, groupNode ) {
  42114. super( name );
  42115. /**
  42116. * The group's ID.
  42117. *
  42118. * @type {number}
  42119. */
  42120. this.id = _id$3 ++;
  42121. /**
  42122. * The uniform group node.
  42123. *
  42124. * @type {UniformGroupNode}
  42125. */
  42126. this.groupNode = groupNode;
  42127. /**
  42128. * This flag can be used for type testing.
  42129. *
  42130. * @type {boolean}
  42131. * @readonly
  42132. * @default true
  42133. */
  42134. this.isNodeUniformsGroup = true;
  42135. }
  42136. }
  42137. /**
  42138. * Represents a sampler binding type.
  42139. *
  42140. * @private
  42141. * @augments Binding
  42142. */
  42143. class Sampler extends Binding {
  42144. /**
  42145. * Constructs a new sampler.
  42146. *
  42147. * @param {string} name - The samplers's name.
  42148. * @param {?Texture} texture - The texture this binding is referring to.
  42149. */
  42150. constructor( name, texture ) {
  42151. super( name );
  42152. /**
  42153. * The texture the sampler is referring to.
  42154. *
  42155. * @private
  42156. * @type {?Texture}
  42157. */
  42158. this._texture = null;
  42159. /**
  42160. * An event listener which is added to {@link texture}'s dispose event.
  42161. *
  42162. * @private
  42163. * @type {Function}
  42164. */
  42165. this._onTextureDispose = () => {
  42166. this.generation = null;
  42167. this.version = 0;
  42168. };
  42169. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  42170. this.texture = texture;
  42171. /**
  42172. * The binding's version.
  42173. *
  42174. * @type {number}
  42175. */
  42176. this.version = texture ? texture.version : 0;
  42177. /**
  42178. * The binding's generation which is an additional version
  42179. * qualifier.
  42180. *
  42181. * @type {?number}
  42182. * @default null
  42183. */
  42184. this.generation = null;
  42185. /**
  42186. * The binding's sampler key.
  42187. *
  42188. * @type {string}
  42189. * @default ''
  42190. */
  42191. this.samplerKey = '';
  42192. /**
  42193. * This flag can be used for type testing.
  42194. *
  42195. * @type {boolean}
  42196. * @readonly
  42197. * @default true
  42198. */
  42199. this.isSampler = true;
  42200. }
  42201. /**
  42202. * Sets the texture of this sampler.
  42203. *
  42204. * @param {Texture} value - The texture to set.
  42205. */
  42206. set texture( value ) {
  42207. if ( this._texture === value ) return;
  42208. if ( this._texture ) {
  42209. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  42210. }
  42211. this._texture = value;
  42212. this.generation = null;
  42213. this.version = 0;
  42214. if ( this._texture ) {
  42215. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  42216. }
  42217. }
  42218. /**
  42219. * Gets the texture of this sampler.
  42220. * @return {?Texture} The texture.
  42221. */
  42222. get texture() {
  42223. return this._texture;
  42224. }
  42225. /**
  42226. * Updates the binding.
  42227. *
  42228. * @return {boolean} Whether the texture has been updated and must be
  42229. * uploaded to the GPU.
  42230. */
  42231. update() {
  42232. const { texture, version } = this;
  42233. if ( version !== texture.version ) {
  42234. this.version = texture.version;
  42235. return true;
  42236. }
  42237. return false;
  42238. }
  42239. clone() {
  42240. const clonedSampler = super.clone();
  42241. // fix dispose handler for cloned instances
  42242. // TODO: Find better solution, see #31747
  42243. clonedSampler._texture = null;
  42244. clonedSampler._onTextureDispose = () => {
  42245. clonedSampler.generation = null;
  42246. clonedSampler.version = 0;
  42247. };
  42248. clonedSampler.texture = this.texture;
  42249. return clonedSampler;
  42250. }
  42251. }
  42252. let _id$2 = 0;
  42253. /**
  42254. * Represents a sampled texture binding type.
  42255. *
  42256. * @private
  42257. * @augments Sampler
  42258. */
  42259. class SampledTexture extends Sampler {
  42260. /**
  42261. * Constructs a new sampled texture.
  42262. *
  42263. * @param {string} name - The sampled texture's name.
  42264. * @param {?Texture} texture - The texture this binding is referring to.
  42265. */
  42266. constructor( name, texture ) {
  42267. super( name, texture );
  42268. /**
  42269. * This identifier.
  42270. *
  42271. * @type {number}
  42272. */
  42273. this.id = _id$2 ++;
  42274. /**
  42275. * Whether the texture is a storage texture or not.
  42276. *
  42277. * @type {boolean}
  42278. * @default false
  42279. */
  42280. this.store = false;
  42281. /**
  42282. * This flag can be used for type testing.
  42283. *
  42284. * @type {boolean}
  42285. * @readonly
  42286. * @default true
  42287. */
  42288. this.isSampledTexture = true;
  42289. }
  42290. }
  42291. /**
  42292. * A special form of sampled texture binding type.
  42293. * It's texture value is managed by a node object.
  42294. *
  42295. * @private
  42296. * @augments SampledTexture
  42297. */
  42298. class NodeSampledTexture extends SampledTexture {
  42299. /**
  42300. * Constructs a new node-based sampled texture.
  42301. *
  42302. * @param {string} name - The textures's name.
  42303. * @param {TextureNode} textureNode - The texture node.
  42304. * @param {UniformGroupNode} groupNode - The uniform group node.
  42305. * @param {?string} [access=null] - The access type.
  42306. */
  42307. constructor( name, textureNode, groupNode, access = null ) {
  42308. super( name, textureNode ? textureNode.value : null );
  42309. /**
  42310. * The texture node.
  42311. *
  42312. * @type {TextureNode}
  42313. */
  42314. this.textureNode = textureNode;
  42315. /**
  42316. * The uniform group node.
  42317. *
  42318. * @type {UniformGroupNode}
  42319. */
  42320. this.groupNode = groupNode;
  42321. /**
  42322. * The access type.
  42323. *
  42324. * @type {?string}
  42325. * @default null
  42326. */
  42327. this.access = access;
  42328. }
  42329. /**
  42330. * Updates the binding.
  42331. *
  42332. * @return {boolean} Whether the texture has been updated and must be
  42333. * uploaded to the GPU.
  42334. */
  42335. update() {
  42336. const { textureNode } = this;
  42337. if ( this.texture !== textureNode.value ) {
  42338. this.texture = textureNode.value;
  42339. return true;
  42340. }
  42341. return super.update();
  42342. }
  42343. }
  42344. /**
  42345. * A special form of sampled cube texture binding type.
  42346. * It's texture value is managed by a node object.
  42347. *
  42348. * @private
  42349. * @augments NodeSampledTexture
  42350. */
  42351. class NodeSampledCubeTexture extends NodeSampledTexture {
  42352. /**
  42353. * Constructs a new node-based sampled cube texture.
  42354. *
  42355. * @param {string} name - The textures's name.
  42356. * @param {TextureNode} textureNode - The texture node.
  42357. * @param {UniformGroupNode} groupNode - The uniform group node.
  42358. * @param {?string} [access=null] - The access type.
  42359. */
  42360. constructor( name, textureNode, groupNode, access = null ) {
  42361. super( name, textureNode, groupNode, access );
  42362. /**
  42363. * This flag can be used for type testing.
  42364. *
  42365. * @type {boolean}
  42366. * @readonly
  42367. * @default true
  42368. */
  42369. this.isSampledCubeTexture = true;
  42370. }
  42371. }
  42372. /**
  42373. * A special form of sampled 3D texture binding type.
  42374. * It's texture value is managed by a node object.
  42375. *
  42376. * @private
  42377. * @augments NodeSampledTexture
  42378. */
  42379. class NodeSampledTexture3D extends NodeSampledTexture {
  42380. /**
  42381. * Constructs a new node-based sampled 3D texture.
  42382. *
  42383. * @param {string} name - The textures's name.
  42384. * @param {TextureNode} textureNode - The texture node.
  42385. * @param {UniformGroupNode} groupNode - The uniform group node.
  42386. * @param {?string} [access=null] - The access type.
  42387. */
  42388. constructor( name, textureNode, groupNode, access = null ) {
  42389. super( name, textureNode, groupNode, access );
  42390. /**
  42391. * This flag can be used for type testing.
  42392. *
  42393. * @type {boolean}
  42394. * @readonly
  42395. * @default true
  42396. */
  42397. this.isSampledTexture3D = true;
  42398. }
  42399. }
  42400. const glslMethods = {
  42401. textureDimensions: 'textureSize',
  42402. equals: 'equal',
  42403. bitcast_float_int: 'floatBitsToInt',
  42404. bitcast_int_float: 'intBitsToFloat',
  42405. bitcast_uint_float: 'uintBitsToFloat',
  42406. bitcast_float_uint: 'floatBitsToUint',
  42407. };
  42408. const precisionLib = {
  42409. low: 'lowp',
  42410. medium: 'mediump',
  42411. high: 'highp'
  42412. };
  42413. const supports$1 = {
  42414. swizzleAssign: true,
  42415. storageBuffer: false
  42416. };
  42417. const interpolationTypeMap = {
  42418. perspective: 'smooth',
  42419. linear: 'noperspective'
  42420. };
  42421. const interpolationModeMap = {
  42422. 'centroid': 'centroid'
  42423. };
  42424. const defaultPrecisions = `
  42425. precision highp float;
  42426. precision highp int;
  42427. precision highp sampler2D;
  42428. precision highp sampler3D;
  42429. precision highp samplerCube;
  42430. precision highp sampler2DArray;
  42431. precision highp usampler2D;
  42432. precision highp usampler3D;
  42433. precision highp usamplerCube;
  42434. precision highp usampler2DArray;
  42435. precision highp isampler2D;
  42436. precision highp isampler3D;
  42437. precision highp isamplerCube;
  42438. precision highp isampler2DArray;
  42439. precision lowp sampler2DShadow;
  42440. precision lowp sampler2DArrayShadow;
  42441. precision lowp samplerCubeShadow;
  42442. `;
  42443. /**
  42444. * A node builder targeting GLSL.
  42445. *
  42446. * This module generates GLSL shader code from node materials and also
  42447. * generates the respective bindings and vertex buffer definitions. These
  42448. * data are later used by the renderer to create render and compute pipelines
  42449. * for render objects.
  42450. *
  42451. * @augments NodeBuilder
  42452. */
  42453. class GLSLNodeBuilder extends NodeBuilder {
  42454. /**
  42455. * Constructs a new GLSL node builder renderer.
  42456. *
  42457. * @param {Object3D} object - The 3D object.
  42458. * @param {Renderer} renderer - The renderer.
  42459. */
  42460. constructor( object, renderer ) {
  42461. super( object, renderer, new GLSLNodeParser() );
  42462. /**
  42463. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  42464. * another dictionary which manages UBOs per group ('render','frame','object').
  42465. *
  42466. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  42467. */
  42468. this.uniformGroups = {};
  42469. /**
  42470. * An array that holds objects defining the varying and attribute data in
  42471. * context of Transform Feedback.
  42472. *
  42473. * @type {Array<Object<string,AttributeNode|string>>}
  42474. */
  42475. this.transforms = [];
  42476. /**
  42477. * A dictionary that holds for each shader stage a Map of used extensions.
  42478. *
  42479. * @type {Object<string,Map<string,Object>>}
  42480. */
  42481. this.extensions = {};
  42482. /**
  42483. * A dictionary that holds for each shader stage an Array of used builtins.
  42484. *
  42485. * @type {Object<string,Array<string>>}
  42486. */
  42487. this.builtins = { vertex: [], fragment: [], compute: [] };
  42488. }
  42489. /**
  42490. * Checks if the given texture requires a manual conversion to the working color space.
  42491. *
  42492. * @param {Texture} texture - The texture to check.
  42493. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  42494. */
  42495. needsToWorkingColorSpace( texture ) {
  42496. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42497. }
  42498. /**
  42499. * Returns the native shader method name for a given generic name.
  42500. *
  42501. * @param {string} method - The method name to resolve.
  42502. * @return {string} The resolved GLSL method name.
  42503. */
  42504. getMethod( method ) {
  42505. return glslMethods[ method ] || method;
  42506. }
  42507. /**
  42508. * Returns the bitcast method name for a given input and outputType.
  42509. *
  42510. * @param {string} type - The output type to bitcast to.
  42511. * @param {string} inputType - The input type of the.
  42512. * @return {string} The resolved WGSL bitcast invocation.
  42513. */
  42514. getBitcastMethod( type, inputType ) {
  42515. return glslMethods[ `bitcast_${ inputType }_${ type }` ];
  42516. }
  42517. /**
  42518. * Returns the native snippet for a ternary operation.
  42519. *
  42520. * @param {string} condSnippet - The condition determining which expression gets resolved.
  42521. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  42522. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  42523. * @return {string} The resolved method name.
  42524. */
  42525. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  42526. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  42527. }
  42528. /**
  42529. * Returns the output struct name. Not relevant for GLSL.
  42530. *
  42531. * @return {string}
  42532. */
  42533. getOutputStructName() {
  42534. return '';
  42535. }
  42536. /**
  42537. * Builds the given shader node.
  42538. *
  42539. * @param {ShaderNodeInternal} shaderNode - The shader node.
  42540. * @return {string} The GLSL function code.
  42541. */
  42542. buildFunctionCode( shaderNode ) {
  42543. const layout = shaderNode.layout;
  42544. const flowData = this.flowShaderNode( shaderNode );
  42545. const parameters = [];
  42546. for ( const input of layout.inputs ) {
  42547. parameters.push( this.getType( input.type ) + ' ' + input.name );
  42548. }
  42549. //
  42550. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  42551. ${ flowData.vars }
  42552. ${ flowData.code }
  42553. return ${ flowData.result };
  42554. }`;
  42555. //
  42556. return code;
  42557. }
  42558. /**
  42559. * Setups the Pixel Buffer Object (PBO) for the given storage
  42560. * buffer node.
  42561. *
  42562. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  42563. */
  42564. setupPBO( storageBufferNode ) {
  42565. const attribute = storageBufferNode.value;
  42566. if ( attribute.pbo === undefined ) {
  42567. const originalArray = attribute.array;
  42568. const numElements = attribute.count * attribute.itemSize;
  42569. const { itemSize } = attribute;
  42570. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  42571. let format = isInteger ? RedIntegerFormat : RedFormat;
  42572. if ( itemSize === 2 ) {
  42573. format = isInteger ? RGIntegerFormat : RGFormat;
  42574. } else if ( itemSize === 3 ) {
  42575. format = isInteger ? RGBIntegerFormat : RGBFormat;
  42576. } else if ( itemSize === 4 ) {
  42577. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  42578. }
  42579. const typeMap = {
  42580. Float32Array: FloatType,
  42581. Uint8Array: UnsignedByteType,
  42582. Uint16Array: UnsignedShortType,
  42583. Uint32Array: UnsignedIntType,
  42584. Int8Array: ByteType,
  42585. Int16Array: ShortType,
  42586. Int32Array: IntType,
  42587. Uint8ClampedArray: UnsignedByteType,
  42588. };
  42589. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  42590. let height = Math.ceil( ( numElements / itemSize ) / width );
  42591. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  42592. const newSize = width * height * itemSize;
  42593. const newArray = new originalArray.constructor( newSize );
  42594. newArray.set( originalArray, 0 );
  42595. attribute.array = newArray;
  42596. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  42597. pboTexture.needsUpdate = true;
  42598. pboTexture.isPBOTexture = true;
  42599. const pbo = new TextureNode( pboTexture, null, null );
  42600. pbo.setPrecision( 'high' );
  42601. attribute.pboNode = pbo;
  42602. attribute.pbo = pbo.value;
  42603. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  42604. }
  42605. }
  42606. /**
  42607. * Returns a GLSL snippet that represents the property name of the given node.
  42608. *
  42609. * @param {Node} node - The node.
  42610. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42611. * @return {string} The property name.
  42612. */
  42613. getPropertyName( node, shaderStage = this.shaderStage ) {
  42614. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  42615. return shaderStage.charAt( 0 ) + '_' + node.name;
  42616. }
  42617. return super.getPropertyName( node, shaderStage );
  42618. }
  42619. /**
  42620. * Setups the Pixel Buffer Object (PBO) for the given storage
  42621. * buffer node.
  42622. *
  42623. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  42624. * @return {string} The property name.
  42625. */
  42626. generatePBO( storageArrayElementNode ) {
  42627. const { node, indexNode } = storageArrayElementNode;
  42628. const attribute = node.value;
  42629. if ( this.renderer.backend.has( attribute ) ) {
  42630. const attributeData = this.renderer.backend.get( attribute );
  42631. attributeData.pbo = attribute.pbo;
  42632. }
  42633. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  42634. const textureName = this.getPropertyName( nodeUniform );
  42635. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  42636. const indexSnippet = indexNode.build( this, 'uint' );
  42637. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  42638. let propertyName = elementNodeData.propertyName;
  42639. if ( propertyName === undefined ) {
  42640. // property element
  42641. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  42642. propertyName = this.getPropertyName( nodeVar );
  42643. // property size
  42644. const bufferNodeData = this.getDataFromNode( node );
  42645. let propertySizeName = bufferNodeData.propertySizeName;
  42646. if ( propertySizeName === undefined ) {
  42647. propertySizeName = propertyName + 'Size';
  42648. this.getVarFromNode( node, propertySizeName, 'uint' );
  42649. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  42650. bufferNodeData.propertySizeName = propertySizeName;
  42651. }
  42652. //
  42653. const { itemSize } = attribute;
  42654. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  42655. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  42656. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  42657. //
  42658. let prefix = 'vec4';
  42659. if ( attribute.pbo.type === UnsignedIntType ) {
  42660. prefix = 'uvec4';
  42661. } else if ( attribute.pbo.type === IntType ) {
  42662. prefix = 'ivec4';
  42663. }
  42664. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  42665. elementNodeData.propertyName = propertyName;
  42666. }
  42667. return propertyName;
  42668. }
  42669. /**
  42670. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  42671. *
  42672. * @param {?Texture} texture - The texture.
  42673. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42674. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42675. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42676. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  42677. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42678. * @return {string} The GLSL snippet.
  42679. */
  42680. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  42681. if ( levelSnippet === null ) levelSnippet = '0';
  42682. let snippet;
  42683. if ( depthSnippet ) {
  42684. if ( offsetSnippet ) {
  42685. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  42686. } else {
  42687. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  42688. }
  42689. } else {
  42690. if ( offsetSnippet ) {
  42691. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  42692. } else {
  42693. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42694. }
  42695. }
  42696. if ( texture !== null && texture.isDepthTexture ) {
  42697. snippet += '.x';
  42698. }
  42699. return snippet;
  42700. }
  42701. /**
  42702. * Generates the GLSL snippet for sampling/loading the given texture.
  42703. *
  42704. * @param {Texture} texture - The texture.
  42705. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42706. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42707. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  42708. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42709. * @return {string} The GLSL snippet.
  42710. */
  42711. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  42712. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  42713. if ( texture.isDepthTexture ) {
  42714. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  42715. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  42716. }
  42717. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  42718. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  42719. }
  42720. /**
  42721. * Generates the GLSL snippet when sampling textures with explicit mip level.
  42722. *
  42723. * @param {Texture} texture - The texture.
  42724. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42725. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42726. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  42727. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42728. * @return {string} The GLSL snippet.
  42729. */
  42730. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  42731. if ( offsetSnippet ) {
  42732. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  42733. }
  42734. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  42735. }
  42736. /**
  42737. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  42738. *
  42739. * @param {Texture} texture - The texture.
  42740. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42741. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42742. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  42743. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42744. * @return {string} The GLSL snippet.
  42745. */
  42746. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  42747. if ( offsetSnippet ) {
  42748. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  42749. }
  42750. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  42751. }
  42752. /**
  42753. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  42754. *
  42755. * @param {Texture} texture - The texture.
  42756. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42757. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42758. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  42759. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42760. * @return {string} The GLSL snippet.
  42761. */
  42762. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  42763. if ( offsetSnippet ) {
  42764. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  42765. }
  42766. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42767. }
  42768. /**
  42769. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  42770. * against a reference value.
  42771. *
  42772. * @param {Texture} texture - The texture.
  42773. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42774. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42775. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  42776. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  42777. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42778. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42779. * @return {string} The GLSL snippet.
  42780. */
  42781. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  42782. if ( shaderStage === 'fragment' ) {
  42783. if ( depthSnippet ) {
  42784. if ( offsetSnippet ) {
  42785. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  42786. }
  42787. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  42788. }
  42789. if ( offsetSnippet ) {
  42790. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  42791. }
  42792. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  42793. } else {
  42794. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42795. }
  42796. }
  42797. /**
  42798. * Returns the variables of the given shader stage as a GLSL string.
  42799. *
  42800. * @param {string} shaderStage - The shader stage.
  42801. * @return {string} The GLSL snippet that defines the variables.
  42802. */
  42803. getVars( shaderStage ) {
  42804. const snippets = [];
  42805. const vars = this.vars[ shaderStage ];
  42806. if ( vars !== undefined ) {
  42807. for ( const variable of vars ) {
  42808. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  42809. }
  42810. }
  42811. return snippets.join( '\n\t' );
  42812. }
  42813. /**
  42814. * Returns the uniforms of the given shader stage as a GLSL string.
  42815. *
  42816. * @param {string} shaderStage - The shader stage.
  42817. * @return {string} The GLSL snippet that defines the uniforms.
  42818. */
  42819. getUniforms( shaderStage ) {
  42820. const uniforms = this.uniforms[ shaderStage ];
  42821. const bindingSnippets = [];
  42822. const uniformGroups = {};
  42823. for ( const uniform of uniforms ) {
  42824. let snippet = null;
  42825. let group = false;
  42826. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  42827. const texture = uniform.node.value;
  42828. let typePrefix = '';
  42829. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  42830. if ( texture.type === UnsignedIntType ) {
  42831. typePrefix = 'u';
  42832. } else if ( texture.type === IntType ) {
  42833. typePrefix = 'i';
  42834. }
  42835. }
  42836. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  42837. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  42838. } else if ( texture.compareFunction ) {
  42839. if ( texture.isArrayTexture === true ) {
  42840. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  42841. } else {
  42842. snippet = `sampler2DShadow ${ uniform.name };`;
  42843. }
  42844. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  42845. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  42846. } else {
  42847. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  42848. }
  42849. } else if ( uniform.type === 'cubeTexture' ) {
  42850. snippet = `samplerCube ${ uniform.name };`;
  42851. } else if ( uniform.type === 'buffer' ) {
  42852. const bufferNode = uniform.node;
  42853. const bufferType = this.getType( bufferNode.bufferType );
  42854. const bufferCount = bufferNode.bufferCount;
  42855. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  42856. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  42857. } else {
  42858. const vectorType = this.getVectorType( uniform.type );
  42859. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  42860. group = true;
  42861. }
  42862. const precision = uniform.node.precision;
  42863. if ( precision !== null ) {
  42864. snippet = precisionLib[ precision ] + ' ' + snippet;
  42865. }
  42866. if ( group ) {
  42867. snippet = '\t' + snippet;
  42868. const groupName = uniform.groupNode.name;
  42869. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  42870. groupSnippets.push( snippet );
  42871. } else {
  42872. snippet = 'uniform ' + snippet;
  42873. bindingSnippets.push( snippet );
  42874. }
  42875. }
  42876. let output = '';
  42877. for ( const name in uniformGroups ) {
  42878. const groupSnippets = uniformGroups[ name ];
  42879. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  42880. }
  42881. output += bindingSnippets.join( '\n' );
  42882. return output;
  42883. }
  42884. /**
  42885. * Returns the type for a given buffer attribute.
  42886. *
  42887. * @param {BufferAttribute} attribute - The buffer attribute.
  42888. * @return {string} The type.
  42889. */
  42890. getTypeFromAttribute( attribute ) {
  42891. let nodeType = super.getTypeFromAttribute( attribute );
  42892. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  42893. let dataAttribute = attribute;
  42894. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  42895. const array = dataAttribute.array;
  42896. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  42897. nodeType = nodeType.slice( 1 );
  42898. }
  42899. }
  42900. return nodeType;
  42901. }
  42902. /**
  42903. * Returns the shader attributes of the given shader stage as a GLSL string.
  42904. *
  42905. * @param {string} shaderStage - The shader stage.
  42906. * @return {string} The GLSL snippet that defines the shader attributes.
  42907. */
  42908. getAttributes( shaderStage ) {
  42909. let snippet = '';
  42910. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  42911. const attributes = this.getAttributesArray();
  42912. let location = 0;
  42913. for ( const attribute of attributes ) {
  42914. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  42915. }
  42916. }
  42917. return snippet;
  42918. }
  42919. /**
  42920. * Returns the members of the given struct type node as a GLSL string.
  42921. *
  42922. * @param {StructTypeNode} struct - The struct type node.
  42923. * @return {string} The GLSL snippet that defines the struct members.
  42924. */
  42925. getStructMembers( struct ) {
  42926. const snippets = [];
  42927. for ( const member of struct.members ) {
  42928. snippets.push( `\t${ member.type } ${ member.name };` );
  42929. }
  42930. return snippets.join( '\n' );
  42931. }
  42932. /**
  42933. * Returns the structs of the given shader stage as a GLSL string.
  42934. *
  42935. * @param {string} shaderStage - The shader stage.
  42936. * @return {string} The GLSL snippet that defines the structs.
  42937. */
  42938. getStructs( shaderStage ) {
  42939. const snippets = [];
  42940. const structs = this.structs[ shaderStage ];
  42941. const outputSnippet = [];
  42942. for ( const struct of structs ) {
  42943. if ( struct.output ) {
  42944. for ( const member of struct.members ) {
  42945. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  42946. }
  42947. } else {
  42948. let snippet = 'struct ' + struct.name + ' {\n';
  42949. snippet += this.getStructMembers( struct );
  42950. snippet += '\n};\n';
  42951. snippets.push( snippet );
  42952. }
  42953. }
  42954. if ( outputSnippet.length === 0 ) {
  42955. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  42956. }
  42957. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  42958. }
  42959. /**
  42960. * Returns the varyings of the given shader stage as a GLSL string.
  42961. *
  42962. * @param {string} shaderStage - The shader stage.
  42963. * @return {string} The GLSL snippet that defines the varyings.
  42964. */
  42965. getVaryings( shaderStage ) {
  42966. let snippet = '';
  42967. const varyings = this.varyings;
  42968. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  42969. for ( const varying of varyings ) {
  42970. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  42971. const type = this.getType( varying.type );
  42972. if ( varying.needsInterpolation ) {
  42973. if ( varying.interpolationType ) {
  42974. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  42975. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  42976. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  42977. } else {
  42978. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  42979. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  42980. }
  42981. } else {
  42982. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  42983. }
  42984. }
  42985. } else if ( shaderStage === 'fragment' ) {
  42986. for ( const varying of varyings ) {
  42987. if ( varying.needsInterpolation ) {
  42988. const type = this.getType( varying.type );
  42989. if ( varying.interpolationType ) {
  42990. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  42991. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  42992. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  42993. } else {
  42994. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  42995. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  42996. }
  42997. }
  42998. }
  42999. }
  43000. for ( const builtin of this.builtins[ shaderStage ] ) {
  43001. snippet += `${builtin};\n`;
  43002. }
  43003. return snippet;
  43004. }
  43005. /**
  43006. * Returns the vertex index builtin.
  43007. *
  43008. * @return {string} The vertex index.
  43009. */
  43010. getVertexIndex() {
  43011. return 'uint( gl_VertexID )';
  43012. }
  43013. /**
  43014. * Contextually returns either the vertex stage instance index builtin
  43015. * or the linearized index of an compute invocation within a grid of workgroups.
  43016. *
  43017. * @return {string} The instance index.
  43018. */
  43019. getInstanceIndex() {
  43020. return 'uint( gl_InstanceID )';
  43021. }
  43022. /**
  43023. * Returns a builtin representing the index of an invocation within its workgroup.
  43024. *
  43025. * @return {string} The invocation local index.
  43026. */
  43027. getInvocationLocalIndex() {
  43028. const workgroupSize = this.object.workgroupSize;
  43029. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  43030. return `uint( gl_InstanceID ) % ${size}u`;
  43031. }
  43032. /**
  43033. * Returns a builtin representing the size of a subgroup within the current shader.
  43034. */
  43035. getSubgroupSize() {
  43036. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node' );
  43037. }
  43038. /**
  43039. * Returns a builtin representing the index of an invocation within its subgroup.
  43040. */
  43041. getInvocationSubgroupIndex() {
  43042. error( 'GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node' );
  43043. }
  43044. /**
  43045. * Returns a builtin representing the index of the current invocation's subgroup within its workgroup.
  43046. */
  43047. getSubgroupIndex() {
  43048. error( 'GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node' );
  43049. }
  43050. /**
  43051. * Returns the draw index builtin.
  43052. *
  43053. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  43054. */
  43055. getDrawIndex() {
  43056. const extensions = this.renderer.backend.extensions;
  43057. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  43058. return 'uint( gl_DrawID )';
  43059. }
  43060. return null;
  43061. }
  43062. /**
  43063. * Returns the front facing builtin.
  43064. *
  43065. * @return {string} The front facing builtin.
  43066. */
  43067. getFrontFacing() {
  43068. return 'gl_FrontFacing';
  43069. }
  43070. /**
  43071. * Returns the frag coord builtin.
  43072. *
  43073. * @return {string} The frag coord builtin.
  43074. */
  43075. getFragCoord() {
  43076. return 'gl_FragCoord.xy';
  43077. }
  43078. /**
  43079. * Returns the frag depth builtin.
  43080. *
  43081. * @return {string} The frag depth builtin.
  43082. */
  43083. getFragDepth() {
  43084. return 'gl_FragDepth';
  43085. }
  43086. /**
  43087. * Enables the given extension.
  43088. *
  43089. * @param {string} name - The extension name.
  43090. * @param {string} behavior - The extension behavior.
  43091. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  43092. */
  43093. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  43094. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  43095. if ( map.has( name ) === false ) {
  43096. map.set( name, {
  43097. name,
  43098. behavior
  43099. } );
  43100. }
  43101. }
  43102. /**
  43103. * Returns the enabled extensions of the given shader stage as a GLSL string.
  43104. *
  43105. * @param {string} shaderStage - The shader stage.
  43106. * @return {string} The GLSL snippet that defines the enabled extensions.
  43107. */
  43108. getExtensions( shaderStage ) {
  43109. const snippets = [];
  43110. if ( shaderStage === 'vertex' ) {
  43111. const ext = this.renderer.backend.extensions;
  43112. const isBatchedMesh = this.object.isBatchedMesh;
  43113. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  43114. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  43115. }
  43116. }
  43117. const extensions = this.extensions[ shaderStage ];
  43118. if ( extensions !== undefined ) {
  43119. for ( const { name, behavior } of extensions.values() ) {
  43120. snippets.push( `#extension ${name} : ${behavior}` );
  43121. }
  43122. }
  43123. return snippets.join( '\n' );
  43124. }
  43125. /**
  43126. * Returns the clip distances builtin.
  43127. *
  43128. * @return {string} The clip distances builtin.
  43129. */
  43130. getClipDistance() {
  43131. return 'gl_ClipDistance';
  43132. }
  43133. /**
  43134. * Whether the requested feature is available or not.
  43135. *
  43136. * @param {string} name - The requested feature.
  43137. * @return {boolean} Whether the requested feature is supported or not.
  43138. */
  43139. isAvailable( name ) {
  43140. let result = supports$1[ name ];
  43141. if ( result === undefined ) {
  43142. let extensionName;
  43143. result = false;
  43144. switch ( name ) {
  43145. case 'float32Filterable':
  43146. extensionName = 'OES_texture_float_linear';
  43147. break;
  43148. case 'clipDistance':
  43149. extensionName = 'WEBGL_clip_cull_distance';
  43150. break;
  43151. }
  43152. if ( extensionName !== undefined ) {
  43153. const extensions = this.renderer.backend.extensions;
  43154. if ( extensions.has( extensionName ) ) {
  43155. extensions.get( extensionName );
  43156. result = true;
  43157. }
  43158. }
  43159. supports$1[ name ] = result;
  43160. }
  43161. return result;
  43162. }
  43163. /**
  43164. * Whether to flip texture data along its vertical axis or not.
  43165. *
  43166. * @return {boolean} Returns always `true` in context of GLSL.
  43167. */
  43168. isFlipY() {
  43169. return true;
  43170. }
  43171. /**
  43172. * Enables hardware clipping.
  43173. *
  43174. * @param {string} planeCount - The clipping plane count.
  43175. */
  43176. enableHardwareClipping( planeCount ) {
  43177. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  43178. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  43179. }
  43180. /**
  43181. * Enables multiview.
  43182. */
  43183. enableMultiview() {
  43184. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  43185. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  43186. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  43187. }
  43188. /**
  43189. * Registers a transform in context of Transform Feedback.
  43190. *
  43191. * @param {string} varyingName - The varying name.
  43192. * @param {AttributeNode} attributeNode - The attribute node.
  43193. */
  43194. registerTransform( varyingName, attributeNode ) {
  43195. this.transforms.push( { varyingName, attributeNode } );
  43196. }
  43197. /**
  43198. * Returns the transforms of the given shader stage as a GLSL string.
  43199. *
  43200. * @param {string} shaderStage - The shader stage.
  43201. * @return {string} The GLSL snippet that defines the transforms.
  43202. */
  43203. getTransforms( /* shaderStage */ ) {
  43204. const transforms = this.transforms;
  43205. let snippet = '';
  43206. for ( let i = 0; i < transforms.length; i ++ ) {
  43207. const transform = transforms[ i ];
  43208. const attributeName = this.getPropertyName( transform.attributeNode );
  43209. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  43210. }
  43211. return snippet;
  43212. }
  43213. /**
  43214. * Returns a GLSL struct based on the given name and variables.
  43215. *
  43216. * @private
  43217. * @param {string} name - The struct name.
  43218. * @param {string} vars - The struct variables.
  43219. * @return {string} The GLSL snippet representing a struct.
  43220. */
  43221. _getGLSLUniformStruct( name, vars ) {
  43222. return `
  43223. layout( std140 ) uniform ${name} {
  43224. ${vars}
  43225. };`;
  43226. }
  43227. /**
  43228. * Returns a GLSL vertex shader based on the given shader data.
  43229. *
  43230. * @private
  43231. * @param {Object} shaderData - The shader data.
  43232. * @return {string} The vertex shader.
  43233. */
  43234. _getGLSLVertexCode( shaderData ) {
  43235. return `#version 300 es
  43236. ${ this.getSignature() }
  43237. // extensions
  43238. ${shaderData.extensions}
  43239. // precision
  43240. ${ defaultPrecisions }
  43241. // uniforms
  43242. ${shaderData.uniforms}
  43243. // varyings
  43244. ${shaderData.varyings}
  43245. // attributes
  43246. ${shaderData.attributes}
  43247. // codes
  43248. ${shaderData.codes}
  43249. void main() {
  43250. // vars
  43251. ${shaderData.vars}
  43252. // transforms
  43253. ${shaderData.transforms}
  43254. // flow
  43255. ${shaderData.flow}
  43256. gl_PointSize = 1.0;
  43257. }
  43258. `;
  43259. }
  43260. /**
  43261. * Returns a GLSL fragment shader based on the given shader data.
  43262. *
  43263. * @private
  43264. * @param {Object} shaderData - The shader data.
  43265. * @return {string} The vertex shader.
  43266. */
  43267. _getGLSLFragmentCode( shaderData ) {
  43268. return `#version 300 es
  43269. ${ this.getSignature() }
  43270. // extensions
  43271. ${shaderData.extensions}
  43272. // precision
  43273. ${ defaultPrecisions }
  43274. // uniforms
  43275. ${shaderData.uniforms}
  43276. // varyings
  43277. ${shaderData.varyings}
  43278. // codes
  43279. ${shaderData.codes}
  43280. // structs
  43281. ${shaderData.structs}
  43282. void main() {
  43283. // vars
  43284. ${shaderData.vars}
  43285. // flow
  43286. ${shaderData.flow}
  43287. }
  43288. `;
  43289. }
  43290. /**
  43291. * Controls the code build of the shader stages.
  43292. */
  43293. buildCode() {
  43294. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43295. this.sortBindingGroups();
  43296. for ( const shaderStage in shadersData ) {
  43297. let flow = '// code\n\n';
  43298. flow += this.flowCode[ shaderStage ];
  43299. const flowNodes = this.flowNodes[ shaderStage ];
  43300. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43301. for ( const node of flowNodes ) {
  43302. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43303. const slotName = node.name;
  43304. if ( slotName ) {
  43305. if ( flow.length > 0 ) flow += '\n';
  43306. flow += `\t// flow -> ${ slotName }\n\t`;
  43307. }
  43308. flow += `${ flowSlotData.code }\n\t`;
  43309. if ( node === mainNode && shaderStage !== 'compute' ) {
  43310. flow += '// result\n\t';
  43311. if ( shaderStage === 'vertex' ) {
  43312. flow += 'gl_Position = ';
  43313. flow += `${ flowSlotData.result };`;
  43314. } else if ( shaderStage === 'fragment' ) {
  43315. if ( ! node.outputNode.isOutputStructNode ) {
  43316. flow += 'fragColor = ';
  43317. flow += `${ flowSlotData.result };`;
  43318. }
  43319. }
  43320. }
  43321. }
  43322. const stageData = shadersData[ shaderStage ];
  43323. stageData.extensions = this.getExtensions( shaderStage );
  43324. stageData.uniforms = this.getUniforms( shaderStage );
  43325. stageData.attributes = this.getAttributes( shaderStage );
  43326. stageData.varyings = this.getVaryings( shaderStage );
  43327. stageData.vars = this.getVars( shaderStage );
  43328. stageData.structs = this.getStructs( shaderStage );
  43329. stageData.codes = this.getCodes( shaderStage );
  43330. stageData.transforms = this.getTransforms( shaderStage );
  43331. stageData.flow = flow;
  43332. }
  43333. if ( this.material !== null ) {
  43334. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  43335. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  43336. } else {
  43337. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  43338. }
  43339. }
  43340. /**
  43341. * This method is one of the more important ones since it's responsible
  43342. * for generating a matching binding instance for the given uniform node.
  43343. *
  43344. * These bindings are later used in the renderer to create bind groups
  43345. * and layouts.
  43346. *
  43347. * @param {UniformNode} node - The uniform node.
  43348. * @param {string} type - The node data type.
  43349. * @param {string} shaderStage - The shader stage.
  43350. * @param {?string} [name=null] - An optional uniform name.
  43351. * @return {NodeUniform} The node uniform object.
  43352. */
  43353. getUniformFromNode( node, type, shaderStage, name = null ) {
  43354. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  43355. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  43356. let uniformGPU = nodeData.uniformGPU;
  43357. if ( uniformGPU === undefined ) {
  43358. const group = node.groupNode;
  43359. const groupName = group.name;
  43360. const bindings = this.getBindGroupArray( groupName, shaderStage );
  43361. if ( type === 'texture' ) {
  43362. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  43363. bindings.push( uniformGPU );
  43364. } else if ( type === 'cubeTexture' ) {
  43365. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  43366. bindings.push( uniformGPU );
  43367. } else if ( type === 'texture3D' ) {
  43368. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  43369. bindings.push( uniformGPU );
  43370. } else if ( type === 'buffer' ) {
  43371. node.name = `NodeBuffer_${ node.id }`;
  43372. uniformNode.name = `buffer${ node.id }`;
  43373. const buffer = new NodeUniformBuffer( node, group );
  43374. buffer.name = node.name;
  43375. bindings.push( buffer );
  43376. uniformGPU = buffer;
  43377. } else {
  43378. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  43379. let uniformsGroup = uniformsStage[ groupName ];
  43380. if ( uniformsGroup === undefined ) {
  43381. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  43382. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  43383. uniformsStage[ groupName ] = uniformsGroup;
  43384. bindings.push( uniformsGroup );
  43385. }
  43386. uniformGPU = this.getNodeUniform( uniformNode, type );
  43387. uniformsGroup.addUniform( uniformGPU );
  43388. }
  43389. nodeData.uniformGPU = uniformGPU;
  43390. }
  43391. return uniformNode;
  43392. }
  43393. }
  43394. let _vector2 = null;
  43395. let _color4 = null;
  43396. /**
  43397. * Most of the rendering related logic is implemented in the
  43398. * {@link Renderer} module and related management components.
  43399. * Sometimes it is required though to execute commands which are
  43400. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  43401. * This abstract base class defines an interface that encapsulates
  43402. * all backend-related logic. Derived classes for each backend must
  43403. * implement the interface.
  43404. *
  43405. * @abstract
  43406. * @private
  43407. */
  43408. class Backend {
  43409. /**
  43410. * Constructs a new backend.
  43411. *
  43412. * @param {Object} parameters - An object holding parameters for the backend.
  43413. */
  43414. constructor( parameters = {} ) {
  43415. /**
  43416. * The parameters of the backend.
  43417. *
  43418. * @type {Object}
  43419. */
  43420. this.parameters = Object.assign( {}, parameters );
  43421. /**
  43422. * This weak map holds backend-specific data of objects
  43423. * like textures, attributes or render targets.
  43424. *
  43425. * @type {WeakMap<Object, Object>}
  43426. */
  43427. this.data = new WeakMap();
  43428. /**
  43429. * A reference to the renderer.
  43430. *
  43431. * @type {?Renderer}
  43432. * @default null
  43433. */
  43434. this.renderer = null;
  43435. /**
  43436. * A reference to the canvas element the renderer is drawing to.
  43437. *
  43438. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  43439. * @default null
  43440. */
  43441. this.domElement = null;
  43442. /**
  43443. * A reference to the timestamp query pool.
  43444. *
  43445. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  43446. */
  43447. this.timestampQueryPool = {
  43448. [ TimestampQuery.RENDER ]: null,
  43449. [ TimestampQuery.COMPUTE ]: null
  43450. };
  43451. /**
  43452. * Whether to track timestamps with a Timestamp Query API or not.
  43453. *
  43454. * @type {boolean}
  43455. * @default false
  43456. */
  43457. this.trackTimestamp = ( parameters.trackTimestamp === true );
  43458. }
  43459. /**
  43460. * Initializes the backend so it is ready for usage. Concrete backends
  43461. * are supposed to implement their rendering context creation and related
  43462. * operations in this method.
  43463. *
  43464. * @async
  43465. * @param {Renderer} renderer - The renderer.
  43466. * @return {Promise} A Promise that resolves when the backend has been initialized.
  43467. */
  43468. async init( renderer ) {
  43469. this.renderer = renderer;
  43470. }
  43471. /**
  43472. * The coordinate system of the backend.
  43473. *
  43474. * @abstract
  43475. * @type {number}
  43476. * @readonly
  43477. */
  43478. get coordinateSystem() {}
  43479. // render context
  43480. /**
  43481. * This method is executed at the beginning of a render call and
  43482. * can be used by the backend to prepare the state for upcoming
  43483. * draw calls.
  43484. *
  43485. * @abstract
  43486. * @param {RenderContext} renderContext - The render context.
  43487. */
  43488. beginRender( /*renderContext*/ ) {}
  43489. /**
  43490. * This method is executed at the end of a render call and
  43491. * can be used by the backend to finalize work after draw
  43492. * calls.
  43493. *
  43494. * @abstract
  43495. * @param {RenderContext} renderContext - The render context.
  43496. */
  43497. finishRender( /*renderContext*/ ) {}
  43498. /**
  43499. * This method is executed at the beginning of a compute call and
  43500. * can be used by the backend to prepare the state for upcoming
  43501. * compute tasks.
  43502. *
  43503. * @abstract
  43504. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43505. */
  43506. beginCompute( /*computeGroup*/ ) {}
  43507. /**
  43508. * This method is executed at the end of a compute call and
  43509. * can be used by the backend to finalize work after compute
  43510. * tasks.
  43511. *
  43512. * @abstract
  43513. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43514. */
  43515. finishCompute( /*computeGroup*/ ) {}
  43516. // render object
  43517. /**
  43518. * Executes a draw command for the given render object.
  43519. *
  43520. * @abstract
  43521. * @param {RenderObject} renderObject - The render object to draw.
  43522. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  43523. */
  43524. draw( /*renderObject, info*/ ) { }
  43525. // compute node
  43526. /**
  43527. * Executes a compute command for the given compute node.
  43528. *
  43529. * @abstract
  43530. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  43531. * @param {Node} computeNode - The compute node.
  43532. * @param {Array<BindGroup>} bindings - The bindings.
  43533. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43534. */
  43535. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  43536. // program
  43537. /**
  43538. * Creates a shader program from the given programmable stage.
  43539. *
  43540. * @abstract
  43541. * @param {ProgrammableStage} program - The programmable stage.
  43542. */
  43543. createProgram( /*program*/ ) { }
  43544. /**
  43545. * Destroys the shader program of the given programmable stage.
  43546. *
  43547. * @abstract
  43548. * @param {ProgrammableStage} program - The programmable stage.
  43549. */
  43550. destroyProgram( /*program*/ ) { }
  43551. // bindings
  43552. /**
  43553. * Creates bindings from the given bind group definition.
  43554. *
  43555. * @abstract
  43556. * @param {BindGroup} bindGroup - The bind group.
  43557. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43558. * @param {number} cacheIndex - The cache index.
  43559. * @param {number} version - The version.
  43560. */
  43561. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  43562. /**
  43563. * Updates the given bind group definition.
  43564. *
  43565. * @abstract
  43566. * @param {BindGroup} bindGroup - The bind group.
  43567. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43568. * @param {number} cacheIndex - The cache index.
  43569. * @param {number} version - The version.
  43570. */
  43571. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  43572. /**
  43573. * Updates a buffer binding.
  43574. *
  43575. * @abstract
  43576. * @param {Buffer} binding - The buffer binding to update.
  43577. */
  43578. updateBinding( /*binding*/ ) { }
  43579. // pipeline
  43580. /**
  43581. * Creates a render pipeline for the given render object.
  43582. *
  43583. * @abstract
  43584. * @param {RenderObject} renderObject - The render object.
  43585. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  43586. */
  43587. createRenderPipeline( /*renderObject, promises*/ ) { }
  43588. /**
  43589. * Creates a compute pipeline for the given compute node.
  43590. *
  43591. * @abstract
  43592. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43593. * @param {Array<BindGroup>} bindings - The bindings.
  43594. */
  43595. createComputePipeline( /*computePipeline, bindings*/ ) { }
  43596. // cache key
  43597. /**
  43598. * Returns `true` if the render pipeline requires an update.
  43599. *
  43600. * @abstract
  43601. * @param {RenderObject} renderObject - The render object.
  43602. * @return {boolean} Whether the render pipeline requires an update or not.
  43603. */
  43604. needsRenderUpdate( /*renderObject*/ ) { }
  43605. /**
  43606. * Returns a cache key that is used to identify render pipelines.
  43607. *
  43608. * @abstract
  43609. * @param {RenderObject} renderObject - The render object.
  43610. * @return {string} The cache key.
  43611. */
  43612. getRenderCacheKey( /*renderObject*/ ) { }
  43613. // node builder
  43614. /**
  43615. * Returns a node builder for the given render object.
  43616. *
  43617. * @abstract
  43618. * @param {RenderObject} renderObject - The render object.
  43619. * @param {Renderer} renderer - The renderer.
  43620. * @return {NodeBuilder} The node builder.
  43621. */
  43622. createNodeBuilder( /*renderObject, renderer*/ ) { }
  43623. // textures
  43624. /**
  43625. * Updates a GPU sampler for the given texture.
  43626. *
  43627. * @abstract
  43628. * @param {Texture} texture - The texture to update the sampler for.
  43629. * @return {string} The current sampler key.
  43630. */
  43631. updateSampler( /*texture*/ ) { }
  43632. /**
  43633. * Creates a default texture for the given texture that can be used
  43634. * as a placeholder until the actual texture is ready for usage.
  43635. *
  43636. * @abstract
  43637. * @param {Texture} texture - The texture to create a default texture for.
  43638. */
  43639. createDefaultTexture( /*texture*/ ) { }
  43640. /**
  43641. * Defines a texture on the GPU for the given texture object.
  43642. *
  43643. * @abstract
  43644. * @param {Texture} texture - The texture.
  43645. * @param {Object} [options={}] - Optional configuration parameter.
  43646. */
  43647. createTexture( /*texture, options={}*/ ) { }
  43648. /**
  43649. * Uploads the updated texture data to the GPU.
  43650. *
  43651. * @abstract
  43652. * @param {Texture} texture - The texture.
  43653. * @param {Object} [options={}] - Optional configuration parameter.
  43654. */
  43655. updateTexture( /*texture, options = {}*/ ) { }
  43656. /**
  43657. * Generates mipmaps for the given texture.
  43658. *
  43659. * @abstract
  43660. * @param {Texture} texture - The texture.
  43661. */
  43662. generateMipmaps( /*texture*/ ) { }
  43663. /**
  43664. * Destroys the GPU data for the given texture object.
  43665. *
  43666. * @abstract
  43667. * @param {Texture} texture - The texture.
  43668. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  43669. */
  43670. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  43671. /**
  43672. * Returns texture data as a typed array.
  43673. *
  43674. * @abstract
  43675. * @async
  43676. * @param {Texture} texture - The texture to copy.
  43677. * @param {number} x - The x coordinate of the copy origin.
  43678. * @param {number} y - The y coordinate of the copy origin.
  43679. * @param {number} width - The width of the copy.
  43680. * @param {number} height - The height of the copy.
  43681. * @param {number} faceIndex - The face index.
  43682. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43683. */
  43684. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  43685. /**
  43686. * Copies data of the given source texture to the given destination texture.
  43687. *
  43688. * @abstract
  43689. * @param {Texture} srcTexture - The source texture.
  43690. * @param {Texture} dstTexture - The destination texture.
  43691. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  43692. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  43693. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43694. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43695. */
  43696. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  43697. /**
  43698. * Copies the current bound framebuffer to the given texture.
  43699. *
  43700. * @abstract
  43701. * @param {Texture} texture - The destination texture.
  43702. * @param {RenderContext} renderContext - The render context.
  43703. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43704. */
  43705. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  43706. // attributes
  43707. /**
  43708. * Creates the GPU buffer of a shader attribute.
  43709. *
  43710. * @abstract
  43711. * @param {BufferAttribute} attribute - The buffer attribute.
  43712. */
  43713. createAttribute( /*attribute*/ ) { }
  43714. /**
  43715. * Creates the GPU buffer of an indexed shader attribute.
  43716. *
  43717. * @abstract
  43718. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  43719. */
  43720. createIndexAttribute( /*attribute*/ ) { }
  43721. /**
  43722. * Creates the GPU buffer of a storage attribute.
  43723. *
  43724. * @abstract
  43725. * @param {BufferAttribute} attribute - The buffer attribute.
  43726. */
  43727. createStorageAttribute( /*attribute*/ ) { }
  43728. /**
  43729. * Updates the GPU buffer of a shader attribute.
  43730. *
  43731. * @abstract
  43732. * @param {BufferAttribute} attribute - The buffer attribute to update.
  43733. */
  43734. updateAttribute( /*attribute*/ ) { }
  43735. /**
  43736. * Destroys the GPU buffer of a shader attribute.
  43737. *
  43738. * @abstract
  43739. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  43740. */
  43741. destroyAttribute( /*attribute*/ ) { }
  43742. // canvas
  43743. /**
  43744. * Returns the backend's rendering context.
  43745. *
  43746. * @abstract
  43747. * @return {Object} The rendering context.
  43748. */
  43749. getContext() { }
  43750. /**
  43751. * Backends can use this method if they have to run
  43752. * logic when the renderer gets resized.
  43753. *
  43754. * @abstract
  43755. */
  43756. updateSize() { }
  43757. /**
  43758. * Updates the viewport with the values from the given render context.
  43759. *
  43760. * @abstract
  43761. * @param {RenderContext} renderContext - The render context.
  43762. */
  43763. updateViewport( /*renderContext*/ ) {}
  43764. // utils
  43765. /**
  43766. * Updates a unique identifier for the given render context that can be used
  43767. * to allocate resources like occlusion queries or timestamp queries.
  43768. *
  43769. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  43770. */
  43771. updateTimeStampUID( abstractRenderContext ) {
  43772. const contextData = this.get( abstractRenderContext );
  43773. const frame = this.renderer.info.frame;
  43774. let prefix;
  43775. if ( abstractRenderContext.isComputeNode === true ) {
  43776. prefix = 'c:' + this.renderer.info.compute.frameCalls;
  43777. } else {
  43778. prefix = 'r:' + this.renderer.info.render.frameCalls;
  43779. }
  43780. contextData.timestampUID = prefix + ':' + abstractRenderContext.id + ':f' + frame;
  43781. }
  43782. /**
  43783. * Returns a unique identifier for the given render context that can be used
  43784. * to allocate resources like occlusion queries or timestamp queries.
  43785. *
  43786. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  43787. * @return {string} The unique identifier.
  43788. */
  43789. getTimestampUID( abstractRenderContext ) {
  43790. return this.get( abstractRenderContext ).timestampUID;
  43791. }
  43792. getTimestampFrames( type ) {
  43793. const queryPool = this.timestampQueryPool[ type ];
  43794. return queryPool ? queryPool.getTimestampFrames() : [];
  43795. }
  43796. getTimestamp( uid ) {
  43797. const type = uid.startsWith( 'c:' ) ? TimestampQuery.COMPUTE : TimestampQuery.RENDER;
  43798. const queryPool = this.timestampQueryPool[ type ];
  43799. return queryPool.getTimestamp( uid );
  43800. }
  43801. /**
  43802. * Returns `true` if the given 3D object is fully occluded by other
  43803. * 3D objects in the scene. Backends must implement this method by using
  43804. * a Occlusion Query API.
  43805. *
  43806. * @abstract
  43807. * @param {RenderContext} renderContext - The render context.
  43808. * @param {Object3D} object - The 3D object to test.
  43809. * @return {boolean} Whether the 3D object is fully occluded or not.
  43810. */
  43811. isOccluded( /*renderContext, object*/ ) {}
  43812. /**
  43813. * Resolves the time stamp for the given render context and type.
  43814. *
  43815. * @async
  43816. * @abstract
  43817. * @param {string} [type='render'] - The type of the time stamp.
  43818. * @return {Promise<number>} A Promise that resolves with the time stamp.
  43819. */
  43820. async resolveTimestampsAsync( type = 'render' ) {
  43821. if ( ! this.trackTimestamp ) {
  43822. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  43823. return;
  43824. }
  43825. const queryPool = this.timestampQueryPool[ type ];
  43826. if ( ! queryPool ) {
  43827. return;
  43828. }
  43829. const duration = await queryPool.resolveQueriesAsync();
  43830. this.renderer.info[ type ].timestamp = duration;
  43831. return duration;
  43832. }
  43833. /**
  43834. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43835. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43836. *
  43837. * @async
  43838. * @abstract
  43839. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43840. */
  43841. async waitForGPU() {}
  43842. /**
  43843. * This method performs a readback operation by moving buffer data from
  43844. * a storage buffer attribute from the GPU to the CPU.
  43845. *
  43846. * @async
  43847. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43848. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43849. */
  43850. async getArrayBufferAsync( /* attribute */ ) {}
  43851. /**
  43852. * Checks if the given feature is supported by the backend.
  43853. *
  43854. * @async
  43855. * @abstract
  43856. * @param {string} name - The feature's name.
  43857. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  43858. */
  43859. async hasFeatureAsync( /*name*/ ) { }
  43860. /**
  43861. * Checks if the given feature is supported by the backend.
  43862. *
  43863. * @abstract
  43864. * @param {string} name - The feature's name.
  43865. * @return {boolean} Whether the feature is supported or not.
  43866. */
  43867. hasFeature( /*name*/ ) {}
  43868. /**
  43869. * Returns the maximum anisotropy texture filtering value.
  43870. *
  43871. * @abstract
  43872. * @return {number} The maximum anisotropy texture filtering value.
  43873. */
  43874. getMaxAnisotropy() {}
  43875. /**
  43876. * Returns the drawing buffer size.
  43877. *
  43878. * @return {Vector2} The drawing buffer size.
  43879. */
  43880. getDrawingBufferSize() {
  43881. _vector2 = _vector2 || new Vector2();
  43882. return this.renderer.getDrawingBufferSize( _vector2 );
  43883. }
  43884. /**
  43885. * Defines the scissor test.
  43886. *
  43887. * @abstract
  43888. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43889. */
  43890. setScissorTest( /*boolean*/ ) { }
  43891. /**
  43892. * Returns the clear color and alpha into a single
  43893. * color object.
  43894. *
  43895. * @return {Color4} The clear color.
  43896. */
  43897. getClearColor() {
  43898. const renderer = this.renderer;
  43899. _color4 = _color4 || new Color4();
  43900. renderer.getClearColor( _color4 );
  43901. _color4.getRGB( _color4 );
  43902. return _color4;
  43903. }
  43904. /**
  43905. * Returns the DOM element. If no DOM element exists, the backend
  43906. * creates a new one.
  43907. *
  43908. * @return {HTMLCanvasElement} The DOM element.
  43909. */
  43910. getDomElement() {
  43911. let domElement = this.domElement;
  43912. if ( domElement === null ) {
  43913. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  43914. // OffscreenCanvas does not have setAttribute, see #22811
  43915. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  43916. this.domElement = domElement;
  43917. }
  43918. return domElement;
  43919. }
  43920. /**
  43921. * Sets a dictionary for the given object into the
  43922. * internal data structure.
  43923. *
  43924. * @param {Object} object - The object.
  43925. * @param {Object} value - The dictionary to set.
  43926. */
  43927. set( object, value ) {
  43928. this.data.set( object, value );
  43929. }
  43930. /**
  43931. * Returns the dictionary for the given object.
  43932. *
  43933. * @param {Object} object - The object.
  43934. * @return {Object} The object's dictionary.
  43935. */
  43936. get( object ) {
  43937. let map = this.data.get( object );
  43938. if ( map === undefined ) {
  43939. map = {};
  43940. this.data.set( object, map );
  43941. }
  43942. return map;
  43943. }
  43944. /**
  43945. * Checks if the given object has a dictionary
  43946. * with data defined.
  43947. *
  43948. * @param {Object} object - The object.
  43949. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  43950. */
  43951. has( object ) {
  43952. return this.data.has( object );
  43953. }
  43954. /**
  43955. * Deletes an object from the internal data structure.
  43956. *
  43957. * @param {Object} object - The object to delete.
  43958. */
  43959. delete( object ) {
  43960. this.data.delete( object );
  43961. }
  43962. /**
  43963. * Frees internal resources.
  43964. *
  43965. * @abstract
  43966. */
  43967. dispose() { }
  43968. }
  43969. let _id$1 = 0;
  43970. /**
  43971. * This module is internally used in context of compute shaders.
  43972. * This type of shader is not natively supported in WebGL 2 and
  43973. * thus implemented via Transform Feedback. `DualAttributeData`
  43974. * manages the related data.
  43975. *
  43976. * @private
  43977. */
  43978. class DualAttributeData {
  43979. constructor( attributeData, dualBuffer ) {
  43980. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  43981. this.type = attributeData.type;
  43982. this.bufferType = attributeData.bufferType;
  43983. this.pbo = attributeData.pbo;
  43984. this.byteLength = attributeData.byteLength;
  43985. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  43986. this.version = attributeData.version;
  43987. this.isInteger = attributeData.isInteger;
  43988. this.activeBufferIndex = 0;
  43989. this.baseId = attributeData.id;
  43990. }
  43991. get id() {
  43992. return `${ this.baseId }|${ this.activeBufferIndex }`;
  43993. }
  43994. get bufferGPU() {
  43995. return this.buffers[ this.activeBufferIndex ];
  43996. }
  43997. get transformBuffer() {
  43998. return this.buffers[ this.activeBufferIndex ^ 1 ];
  43999. }
  44000. switchBuffers() {
  44001. this.activeBufferIndex ^= 1;
  44002. }
  44003. }
  44004. /**
  44005. * A WebGL 2 backend utility module for managing shader attributes.
  44006. *
  44007. * @private
  44008. */
  44009. class WebGLAttributeUtils {
  44010. /**
  44011. * Constructs a new utility object.
  44012. *
  44013. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44014. */
  44015. constructor( backend ) {
  44016. /**
  44017. * A reference to the WebGL 2 backend.
  44018. *
  44019. * @type {WebGLBackend}
  44020. */
  44021. this.backend = backend;
  44022. }
  44023. /**
  44024. * Creates the GPU buffer for the given buffer attribute.
  44025. *
  44026. * @param {BufferAttribute} attribute - The buffer attribute.
  44027. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44028. */
  44029. createAttribute( attribute, bufferType ) {
  44030. const backend = this.backend;
  44031. const { gl } = backend;
  44032. const array = attribute.array;
  44033. const usage = attribute.usage || gl.STATIC_DRAW;
  44034. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44035. const bufferData = backend.get( bufferAttribute );
  44036. let bufferGPU = bufferData.bufferGPU;
  44037. if ( bufferGPU === undefined ) {
  44038. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  44039. bufferData.bufferGPU = bufferGPU;
  44040. bufferData.bufferType = bufferType;
  44041. bufferData.version = bufferAttribute.version;
  44042. }
  44043. //attribute.onUploadCallback();
  44044. let type;
  44045. if ( array instanceof Float32Array ) {
  44046. type = gl.FLOAT;
  44047. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  44048. type = gl.HALF_FLOAT;
  44049. } else if ( array instanceof Uint16Array ) {
  44050. if ( attribute.isFloat16BufferAttribute ) {
  44051. type = gl.HALF_FLOAT;
  44052. } else {
  44053. type = gl.UNSIGNED_SHORT;
  44054. }
  44055. } else if ( array instanceof Int16Array ) {
  44056. type = gl.SHORT;
  44057. } else if ( array instanceof Uint32Array ) {
  44058. type = gl.UNSIGNED_INT;
  44059. } else if ( array instanceof Int32Array ) {
  44060. type = gl.INT;
  44061. } else if ( array instanceof Int8Array ) {
  44062. type = gl.BYTE;
  44063. } else if ( array instanceof Uint8Array ) {
  44064. type = gl.UNSIGNED_BYTE;
  44065. } else if ( array instanceof Uint8ClampedArray ) {
  44066. type = gl.UNSIGNED_BYTE;
  44067. } else {
  44068. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  44069. }
  44070. let attributeData = {
  44071. bufferGPU,
  44072. bufferType,
  44073. type,
  44074. byteLength: array.byteLength,
  44075. bytesPerElement: array.BYTES_PER_ELEMENT,
  44076. version: attribute.version,
  44077. pbo: attribute.pbo,
  44078. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  44079. id: _id$1 ++
  44080. };
  44081. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  44082. // create buffer for transform feedback use
  44083. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  44084. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  44085. }
  44086. backend.set( attribute, attributeData );
  44087. }
  44088. /**
  44089. * Updates the GPU buffer of the given buffer attribute.
  44090. *
  44091. * @param {BufferAttribute} attribute - The buffer attribute.
  44092. */
  44093. updateAttribute( attribute ) {
  44094. const backend = this.backend;
  44095. const { gl } = backend;
  44096. const array = attribute.array;
  44097. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44098. const bufferData = backend.get( bufferAttribute );
  44099. const bufferType = bufferData.bufferType;
  44100. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  44101. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  44102. if ( updateRanges.length === 0 ) {
  44103. // Not using update ranges
  44104. gl.bufferSubData( bufferType, 0, array );
  44105. } else {
  44106. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  44107. const range = updateRanges[ i ];
  44108. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  44109. array, range.start, range.count );
  44110. }
  44111. bufferAttribute.clearUpdateRanges();
  44112. }
  44113. gl.bindBuffer( bufferType, null );
  44114. bufferData.version = bufferAttribute.version;
  44115. }
  44116. /**
  44117. * Destroys the GPU buffer of the given buffer attribute.
  44118. *
  44119. * @param {BufferAttribute} attribute - The buffer attribute.
  44120. */
  44121. destroyAttribute( attribute ) {
  44122. const backend = this.backend;
  44123. const { gl } = backend;
  44124. if ( attribute.isInterleavedBufferAttribute ) {
  44125. backend.delete( attribute.data );
  44126. }
  44127. const attributeData = backend.get( attribute );
  44128. gl.deleteBuffer( attributeData.bufferGPU );
  44129. backend.delete( attribute );
  44130. }
  44131. /**
  44132. * This method performs a readback operation by moving buffer data from
  44133. * a storage buffer attribute from the GPU to the CPU.
  44134. *
  44135. * @async
  44136. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44137. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44138. */
  44139. async getArrayBufferAsync( attribute ) {
  44140. const backend = this.backend;
  44141. const { gl } = backend;
  44142. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  44143. const { bufferGPU } = backend.get( bufferAttribute );
  44144. const array = attribute.array;
  44145. const byteLength = array.byteLength;
  44146. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  44147. const writeBuffer = gl.createBuffer();
  44148. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44149. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  44150. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  44151. await backend.utils._clientWaitAsync();
  44152. const dstBuffer = new attribute.array.constructor( array.length );
  44153. // Ensure the buffer is bound before reading
  44154. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  44155. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  44156. gl.deleteBuffer( writeBuffer );
  44157. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  44158. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  44159. return dstBuffer.buffer;
  44160. }
  44161. /**
  44162. * Creates a WebGL buffer with the given data.
  44163. *
  44164. * @private
  44165. * @param {WebGL2RenderingContext} gl - The rendering context.
  44166. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  44167. * @param {TypedArray} array - The array of the buffer attribute.
  44168. * @param {GLenum} usage - The usage.
  44169. * @return {WebGLBuffer} The WebGL buffer.
  44170. */
  44171. _createBuffer( gl, bufferType, array, usage ) {
  44172. const bufferGPU = gl.createBuffer();
  44173. gl.bindBuffer( bufferType, bufferGPU );
  44174. gl.bufferData( bufferType, array, usage );
  44175. gl.bindBuffer( bufferType, null );
  44176. return bufferGPU;
  44177. }
  44178. }
  44179. let equationToGL, factorToGL;
  44180. /**
  44181. * A WebGL 2 backend utility module for managing the WebGL state.
  44182. *
  44183. * The major goal of this module is to reduce the number of state changes
  44184. * by caching the WEbGL state with a series of variables. In this way, the
  44185. * renderer only executes state change commands when necessary which
  44186. * improves the overall performance.
  44187. *
  44188. * @private
  44189. */
  44190. class WebGLState {
  44191. /**
  44192. * Constructs a new utility object.
  44193. *
  44194. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44195. */
  44196. constructor( backend ) {
  44197. /**
  44198. * A reference to the WebGL 2 backend.
  44199. *
  44200. * @type {WebGLBackend}
  44201. */
  44202. this.backend = backend;
  44203. /**
  44204. * A reference to the rendering context.
  44205. *
  44206. * @type {WebGL2RenderingContext}
  44207. */
  44208. this.gl = this.backend.gl;
  44209. // Below properties are intended to cache
  44210. // the WebGL state and are not explicitly
  44211. // documented for convenience reasons.
  44212. this.enabled = {};
  44213. this.currentFlipSided = null;
  44214. this.currentCullFace = null;
  44215. this.currentProgram = null;
  44216. this.currentBlendingEnabled = false;
  44217. this.currentBlending = null;
  44218. this.currentBlendSrc = null;
  44219. this.currentBlendDst = null;
  44220. this.currentBlendSrcAlpha = null;
  44221. this.currentBlendDstAlpha = null;
  44222. this.currentPremultipledAlpha = null;
  44223. this.currentPolygonOffsetFactor = null;
  44224. this.currentPolygonOffsetUnits = null;
  44225. this.currentColorMask = null;
  44226. this.currentDepthFunc = null;
  44227. this.currentDepthMask = null;
  44228. this.currentStencilFunc = null;
  44229. this.currentStencilRef = null;
  44230. this.currentStencilFuncMask = null;
  44231. this.currentStencilFail = null;
  44232. this.currentStencilZFail = null;
  44233. this.currentStencilZPass = null;
  44234. this.currentStencilMask = null;
  44235. this.currentLineWidth = null;
  44236. this.currentClippingPlanes = 0;
  44237. this.currentVAO = null;
  44238. this.currentIndex = null;
  44239. this.currentBoundFramebuffers = {};
  44240. this.currentDrawbuffers = new WeakMap();
  44241. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  44242. this.currentTextureSlot = null;
  44243. this.currentBoundTextures = {};
  44244. this.currentBoundBufferBases = {};
  44245. this._init();
  44246. }
  44247. /**
  44248. * Inits the state of the utility.
  44249. *
  44250. * @private
  44251. */
  44252. _init() {
  44253. const gl = this.gl;
  44254. // Store only WebGL constants here.
  44255. equationToGL = {
  44256. [ AddEquation ]: gl.FUNC_ADD,
  44257. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  44258. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  44259. };
  44260. factorToGL = {
  44261. [ ZeroFactor ]: gl.ZERO,
  44262. [ OneFactor ]: gl.ONE,
  44263. [ SrcColorFactor ]: gl.SRC_COLOR,
  44264. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  44265. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  44266. [ DstColorFactor ]: gl.DST_COLOR,
  44267. [ DstAlphaFactor ]: gl.DST_ALPHA,
  44268. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  44269. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  44270. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  44271. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  44272. };
  44273. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  44274. const viewportParam = gl.getParameter( gl.VIEWPORT );
  44275. this.currentScissor = new Vector4().fromArray( scissorParam );
  44276. this.currentViewport = new Vector4().fromArray( viewportParam );
  44277. this._tempVec4 = new Vector4();
  44278. }
  44279. /**
  44280. * Enables the given WebGL capability.
  44281. *
  44282. * This method caches the capability state so
  44283. * `gl.enable()` is only called when necessary.
  44284. *
  44285. * @param {GLenum} id - The capability to enable.
  44286. */
  44287. enable( id ) {
  44288. const { enabled } = this;
  44289. if ( enabled[ id ] !== true ) {
  44290. this.gl.enable( id );
  44291. enabled[ id ] = true;
  44292. }
  44293. }
  44294. /**
  44295. * Disables the given WebGL capability.
  44296. *
  44297. * This method caches the capability state so
  44298. * `gl.disable()` is only called when necessary.
  44299. *
  44300. * @param {GLenum} id - The capability to enable.
  44301. */
  44302. disable( id ) {
  44303. const { enabled } = this;
  44304. if ( enabled[ id ] !== false ) {
  44305. this.gl.disable( id );
  44306. enabled[ id ] = false;
  44307. }
  44308. }
  44309. /**
  44310. * Specifies whether polygons are front- or back-facing
  44311. * by setting the winding orientation.
  44312. *
  44313. * This method caches the state so `gl.frontFace()` is only
  44314. * called when necessary.
  44315. *
  44316. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  44317. */
  44318. setFlipSided( flipSided ) {
  44319. if ( this.currentFlipSided !== flipSided ) {
  44320. const { gl } = this;
  44321. if ( flipSided ) {
  44322. gl.frontFace( gl.CW );
  44323. } else {
  44324. gl.frontFace( gl.CCW );
  44325. }
  44326. this.currentFlipSided = flipSided;
  44327. }
  44328. }
  44329. /**
  44330. * Specifies whether or not front- and/or back-facing
  44331. * polygons can be culled.
  44332. *
  44333. * This method caches the state so `gl.cullFace()` is only
  44334. * called when necessary.
  44335. *
  44336. * @param {number} cullFace - Defines which polygons are candidates for culling.
  44337. */
  44338. setCullFace( cullFace ) {
  44339. const { gl } = this;
  44340. if ( cullFace !== CullFaceNone ) {
  44341. this.enable( gl.CULL_FACE );
  44342. if ( cullFace !== this.currentCullFace ) {
  44343. if ( cullFace === CullFaceBack ) {
  44344. gl.cullFace( gl.BACK );
  44345. } else if ( cullFace === CullFaceFront ) {
  44346. gl.cullFace( gl.FRONT );
  44347. } else {
  44348. gl.cullFace( gl.FRONT_AND_BACK );
  44349. }
  44350. }
  44351. } else {
  44352. this.disable( gl.CULL_FACE );
  44353. }
  44354. this.currentCullFace = cullFace;
  44355. }
  44356. /**
  44357. * Specifies the width of line primitives.
  44358. *
  44359. * This method caches the state so `gl.lineWidth()` is only
  44360. * called when necessary.
  44361. *
  44362. * @param {number} width - The line width.
  44363. */
  44364. setLineWidth( width ) {
  44365. const { currentLineWidth, gl } = this;
  44366. if ( width !== currentLineWidth ) {
  44367. gl.lineWidth( width );
  44368. this.currentLineWidth = width;
  44369. }
  44370. }
  44371. /**
  44372. * Defines the blending.
  44373. *
  44374. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  44375. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  44376. *
  44377. * @param {number} blending - The blending type.
  44378. * @param {number} blendEquation - The blending equation.
  44379. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  44380. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  44381. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  44382. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  44383. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  44384. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  44385. */
  44386. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  44387. const { gl } = this;
  44388. if ( blending === NoBlending ) {
  44389. if ( this.currentBlendingEnabled === true ) {
  44390. this.disable( gl.BLEND );
  44391. this.currentBlendingEnabled = false;
  44392. }
  44393. return;
  44394. }
  44395. if ( this.currentBlendingEnabled === false ) {
  44396. this.enable( gl.BLEND );
  44397. this.currentBlendingEnabled = true;
  44398. }
  44399. if ( blending !== CustomBlending ) {
  44400. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  44401. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  44402. gl.blendEquation( gl.FUNC_ADD );
  44403. this.currentBlendEquation = AddEquation;
  44404. this.currentBlendEquationAlpha = AddEquation;
  44405. }
  44406. if ( premultipliedAlpha ) {
  44407. switch ( blending ) {
  44408. case NormalBlending:
  44409. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44410. break;
  44411. case AdditiveBlending:
  44412. gl.blendFunc( gl.ONE, gl.ONE );
  44413. break;
  44414. case SubtractiveBlending:
  44415. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  44416. break;
  44417. case MultiplyBlending:
  44418. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  44419. break;
  44420. default:
  44421. error( 'WebGLState: Invalid blending: ', blending );
  44422. break;
  44423. }
  44424. } else {
  44425. switch ( blending ) {
  44426. case NormalBlending:
  44427. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  44428. break;
  44429. case AdditiveBlending:
  44430. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  44431. break;
  44432. case SubtractiveBlending:
  44433. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  44434. break;
  44435. case MultiplyBlending:
  44436. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  44437. break;
  44438. default:
  44439. error( 'WebGLState: Invalid blending: ', blending );
  44440. break;
  44441. }
  44442. }
  44443. this.currentBlendSrc = null;
  44444. this.currentBlendDst = null;
  44445. this.currentBlendSrcAlpha = null;
  44446. this.currentBlendDstAlpha = null;
  44447. this.currentBlending = blending;
  44448. this.currentPremultipledAlpha = premultipliedAlpha;
  44449. }
  44450. return;
  44451. }
  44452. // custom blending
  44453. blendEquationAlpha = blendEquationAlpha || blendEquation;
  44454. blendSrcAlpha = blendSrcAlpha || blendSrc;
  44455. blendDstAlpha = blendDstAlpha || blendDst;
  44456. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  44457. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  44458. this.currentBlendEquation = blendEquation;
  44459. this.currentBlendEquationAlpha = blendEquationAlpha;
  44460. }
  44461. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  44462. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  44463. this.currentBlendSrc = blendSrc;
  44464. this.currentBlendDst = blendDst;
  44465. this.currentBlendSrcAlpha = blendSrcAlpha;
  44466. this.currentBlendDstAlpha = blendDstAlpha;
  44467. }
  44468. this.currentBlending = blending;
  44469. this.currentPremultipledAlpha = false;
  44470. }
  44471. /**
  44472. * Specifies whether colors can be written when rendering
  44473. * into a framebuffer or not.
  44474. *
  44475. * This method caches the state so `gl.colorMask()` is only
  44476. * called when necessary.
  44477. *
  44478. * @param {boolean} colorMask - The color mask.
  44479. */
  44480. setColorMask( colorMask ) {
  44481. if ( this.currentColorMask !== colorMask ) {
  44482. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  44483. this.currentColorMask = colorMask;
  44484. }
  44485. }
  44486. /**
  44487. * Specifies whether the depth test is enabled or not.
  44488. *
  44489. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  44490. */
  44491. setDepthTest( depthTest ) {
  44492. const { gl } = this;
  44493. if ( depthTest ) {
  44494. this.enable( gl.DEPTH_TEST );
  44495. } else {
  44496. this.disable( gl.DEPTH_TEST );
  44497. }
  44498. }
  44499. /**
  44500. * Specifies whether depth values can be written when rendering
  44501. * into a framebuffer or not.
  44502. *
  44503. * This method caches the state so `gl.depthMask()` is only
  44504. * called when necessary.
  44505. *
  44506. * @param {boolean} depthMask - The depth mask.
  44507. */
  44508. setDepthMask( depthMask ) {
  44509. if ( this.currentDepthMask !== depthMask ) {
  44510. this.gl.depthMask( depthMask );
  44511. this.currentDepthMask = depthMask;
  44512. }
  44513. }
  44514. /**
  44515. * Specifies the depth compare function.
  44516. *
  44517. * This method caches the state so `gl.depthFunc()` is only
  44518. * called when necessary.
  44519. *
  44520. * @param {number} depthFunc - The depth compare function.
  44521. */
  44522. setDepthFunc( depthFunc ) {
  44523. if ( this.currentDepthFunc !== depthFunc ) {
  44524. const { gl } = this;
  44525. switch ( depthFunc ) {
  44526. case NeverDepth:
  44527. gl.depthFunc( gl.NEVER );
  44528. break;
  44529. case AlwaysDepth:
  44530. gl.depthFunc( gl.ALWAYS );
  44531. break;
  44532. case LessDepth:
  44533. gl.depthFunc( gl.LESS );
  44534. break;
  44535. case LessEqualDepth:
  44536. gl.depthFunc( gl.LEQUAL );
  44537. break;
  44538. case EqualDepth:
  44539. gl.depthFunc( gl.EQUAL );
  44540. break;
  44541. case GreaterEqualDepth:
  44542. gl.depthFunc( gl.GEQUAL );
  44543. break;
  44544. case GreaterDepth:
  44545. gl.depthFunc( gl.GREATER );
  44546. break;
  44547. case NotEqualDepth:
  44548. gl.depthFunc( gl.NOTEQUAL );
  44549. break;
  44550. default:
  44551. gl.depthFunc( gl.LEQUAL );
  44552. }
  44553. this.currentDepthFunc = depthFunc;
  44554. }
  44555. }
  44556. /**
  44557. * Specifies the scissor box.
  44558. *
  44559. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  44560. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  44561. * @param {number} width - The width of the viewport.
  44562. * @param {number} height - The height of the viewport.
  44563. *
  44564. */
  44565. scissor( x, y, width, height ) {
  44566. const scissor = this._tempVec4.set( x, y, width, height );
  44567. if ( this.currentScissor.equals( scissor ) === false ) {
  44568. const { gl } = this;
  44569. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  44570. this.currentScissor.copy( scissor );
  44571. }
  44572. }
  44573. /**
  44574. * Specifies the viewport.
  44575. *
  44576. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  44577. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  44578. * @param {number} width - The width of the viewport.
  44579. * @param {number} height - The height of the viewport.
  44580. *
  44581. */
  44582. viewport( x, y, width, height ) {
  44583. const viewport = this._tempVec4.set( x, y, width, height );
  44584. if ( this.currentViewport.equals( viewport ) === false ) {
  44585. const { gl } = this;
  44586. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  44587. this.currentViewport.copy( viewport );
  44588. }
  44589. }
  44590. /**
  44591. * Defines the scissor test.
  44592. *
  44593. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44594. */
  44595. setScissorTest( boolean ) {
  44596. const gl = this.gl;
  44597. if ( boolean ) {
  44598. gl.enable( gl.SCISSOR_TEST );
  44599. } else {
  44600. gl.disable( gl.SCISSOR_TEST );
  44601. }
  44602. }
  44603. /**
  44604. * Specifies whether the stencil test is enabled or not.
  44605. *
  44606. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  44607. */
  44608. setStencilTest( stencilTest ) {
  44609. const { gl } = this;
  44610. if ( stencilTest ) {
  44611. this.enable( gl.STENCIL_TEST );
  44612. } else {
  44613. this.disable( gl.STENCIL_TEST );
  44614. }
  44615. }
  44616. /**
  44617. * Specifies whether stencil values can be written when rendering
  44618. * into a framebuffer or not.
  44619. *
  44620. * This method caches the state so `gl.stencilMask()` is only
  44621. * called when necessary.
  44622. *
  44623. * @param {boolean} stencilMask - The stencil mask.
  44624. */
  44625. setStencilMask( stencilMask ) {
  44626. if ( this.currentStencilMask !== stencilMask ) {
  44627. this.gl.stencilMask( stencilMask );
  44628. this.currentStencilMask = stencilMask;
  44629. }
  44630. }
  44631. /**
  44632. * Specifies whether the stencil test functions.
  44633. *
  44634. * This method caches the state so `gl.stencilFunc()` is only
  44635. * called when necessary.
  44636. *
  44637. * @param {number} stencilFunc - The stencil compare function.
  44638. * @param {number} stencilRef - The reference value for the stencil test.
  44639. * @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.
  44640. */
  44641. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  44642. if ( this.currentStencilFunc !== stencilFunc ||
  44643. this.currentStencilRef !== stencilRef ||
  44644. this.currentStencilFuncMask !== stencilMask ) {
  44645. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  44646. this.currentStencilFunc = stencilFunc;
  44647. this.currentStencilRef = stencilRef;
  44648. this.currentStencilFuncMask = stencilMask;
  44649. }
  44650. }
  44651. /**
  44652. * Specifies whether the stencil test operation.
  44653. *
  44654. * This method caches the state so `gl.stencilOp()` is only
  44655. * called when necessary.
  44656. *
  44657. * @param {number} stencilFail - The function to use when the stencil test fails.
  44658. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  44659. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  44660. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  44661. */
  44662. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  44663. if ( this.currentStencilFail !== stencilFail ||
  44664. this.currentStencilZFail !== stencilZFail ||
  44665. this.currentStencilZPass !== stencilZPass ) {
  44666. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  44667. this.currentStencilFail = stencilFail;
  44668. this.currentStencilZFail = stencilZFail;
  44669. this.currentStencilZPass = stencilZPass;
  44670. }
  44671. }
  44672. /**
  44673. * Configures the WebGL state for the given material.
  44674. *
  44675. * @param {Material} material - The material to configure the state for.
  44676. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  44677. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  44678. */
  44679. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  44680. const { gl } = this;
  44681. material.side === DoubleSide
  44682. ? this.disable( gl.CULL_FACE )
  44683. : this.enable( gl.CULL_FACE );
  44684. let flipSided = ( material.side === BackSide );
  44685. if ( frontFaceCW ) flipSided = ! flipSided;
  44686. this.setFlipSided( flipSided );
  44687. ( material.blending === NormalBlending && material.transparent === false )
  44688. ? this.setBlending( NoBlending )
  44689. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  44690. this.setDepthFunc( material.depthFunc );
  44691. this.setDepthTest( material.depthTest );
  44692. this.setDepthMask( material.depthWrite );
  44693. this.setColorMask( material.colorWrite );
  44694. const stencilWrite = material.stencilWrite;
  44695. this.setStencilTest( stencilWrite );
  44696. if ( stencilWrite ) {
  44697. this.setStencilMask( material.stencilWriteMask );
  44698. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  44699. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  44700. }
  44701. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  44702. material.alphaToCoverage === true && this.backend.renderer.currentSamples > 0
  44703. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  44704. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  44705. if ( hardwareClippingPlanes > 0 ) {
  44706. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  44707. const CLIP_DISTANCE0_WEBGL = 0x3000;
  44708. for ( let i = 0; i < 8; i ++ ) {
  44709. if ( i < hardwareClippingPlanes ) {
  44710. this.enable( CLIP_DISTANCE0_WEBGL + i );
  44711. } else {
  44712. this.disable( CLIP_DISTANCE0_WEBGL + i );
  44713. }
  44714. }
  44715. }
  44716. }
  44717. }
  44718. /**
  44719. * Specifies the polygon offset.
  44720. *
  44721. * This method caches the state so `gl.polygonOffset()` is only
  44722. * called when necessary.
  44723. *
  44724. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  44725. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  44726. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  44727. */
  44728. setPolygonOffset( polygonOffset, factor, units ) {
  44729. const { gl } = this;
  44730. if ( polygonOffset ) {
  44731. this.enable( gl.POLYGON_OFFSET_FILL );
  44732. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  44733. gl.polygonOffset( factor, units );
  44734. this.currentPolygonOffsetFactor = factor;
  44735. this.currentPolygonOffsetUnits = units;
  44736. }
  44737. } else {
  44738. this.disable( gl.POLYGON_OFFSET_FILL );
  44739. }
  44740. }
  44741. /**
  44742. * Defines the usage of the given WebGL program.
  44743. *
  44744. * This method caches the state so `gl.useProgram()` is only
  44745. * called when necessary.
  44746. *
  44747. * @param {WebGLProgram} program - The WebGL program to use.
  44748. * @return {boolean} Whether a program change has been executed or not.
  44749. */
  44750. useProgram( program ) {
  44751. if ( this.currentProgram !== program ) {
  44752. this.gl.useProgram( program );
  44753. this.currentProgram = program;
  44754. return true;
  44755. }
  44756. return false;
  44757. }
  44758. /**
  44759. * Sets the vertex state by binding the given VAO and element buffer.
  44760. *
  44761. * @param {WebGLVertexArrayObject} vao - The VAO.
  44762. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  44763. * @return {boolean} Whether a vertex state has been changed or not.
  44764. */
  44765. setVertexState( vao, indexBuffer = null ) {
  44766. const gl = this.gl;
  44767. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  44768. gl.bindVertexArray( vao );
  44769. if ( indexBuffer !== null ) {
  44770. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  44771. }
  44772. this.currentVAO = vao;
  44773. this.currentIndex = indexBuffer;
  44774. return true;
  44775. }
  44776. return false;
  44777. }
  44778. /**
  44779. * Resets the vertex array state by resetting the VAO and element buffer.
  44780. */
  44781. resetVertexState() {
  44782. const gl = this.gl;
  44783. gl.bindVertexArray( null );
  44784. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  44785. this.currentVAO = null;
  44786. this.currentIndex = null;
  44787. }
  44788. // framebuffer
  44789. /**
  44790. * Binds the given framebuffer.
  44791. *
  44792. * This method caches the state so `gl.bindFramebuffer()` is only
  44793. * called when necessary.
  44794. *
  44795. * @param {number} target - The binding point (target).
  44796. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  44797. * @return {boolean} Whether a bind has been executed or not.
  44798. */
  44799. bindFramebuffer( target, framebuffer ) {
  44800. const { gl, currentBoundFramebuffers } = this;
  44801. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  44802. gl.bindFramebuffer( target, framebuffer );
  44803. currentBoundFramebuffers[ target ] = framebuffer;
  44804. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  44805. if ( target === gl.DRAW_FRAMEBUFFER ) {
  44806. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  44807. }
  44808. if ( target === gl.FRAMEBUFFER ) {
  44809. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  44810. }
  44811. return true;
  44812. }
  44813. return false;
  44814. }
  44815. /**
  44816. * Defines draw buffers to which fragment colors are written into.
  44817. * Configures the MRT setup of custom framebuffers.
  44818. *
  44819. * This method caches the state so `gl.drawBuffers()` is only
  44820. * called when necessary.
  44821. *
  44822. * @param {RenderContext} renderContext - The render context.
  44823. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  44824. */
  44825. drawBuffers( renderContext, framebuffer ) {
  44826. const { gl } = this;
  44827. let drawBuffers = [];
  44828. let needsUpdate = false;
  44829. if ( renderContext.textures !== null ) {
  44830. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  44831. if ( drawBuffers === undefined ) {
  44832. drawBuffers = [];
  44833. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  44834. }
  44835. const textures = renderContext.textures;
  44836. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  44837. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  44838. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  44839. }
  44840. drawBuffers.length = textures.length;
  44841. needsUpdate = true;
  44842. }
  44843. } else {
  44844. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  44845. drawBuffers[ 0 ] = gl.BACK;
  44846. needsUpdate = true;
  44847. }
  44848. }
  44849. if ( needsUpdate ) {
  44850. gl.drawBuffers( drawBuffers );
  44851. }
  44852. }
  44853. // texture
  44854. /**
  44855. * Makes the given texture unit active.
  44856. *
  44857. * This method caches the state so `gl.activeTexture()` is only
  44858. * called when necessary.
  44859. *
  44860. * @param {number} webglSlot - The texture unit to make active.
  44861. */
  44862. activeTexture( webglSlot ) {
  44863. const { gl, currentTextureSlot, maxTextures } = this;
  44864. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  44865. if ( currentTextureSlot !== webglSlot ) {
  44866. gl.activeTexture( webglSlot );
  44867. this.currentTextureSlot = webglSlot;
  44868. }
  44869. }
  44870. /**
  44871. * Binds the given WebGL texture to a target.
  44872. *
  44873. * This method caches the state so `gl.bindTexture()` is only
  44874. * called when necessary.
  44875. *
  44876. * @param {number} webglType - The binding point (target).
  44877. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  44878. * @param {number} webglSlot - The texture.
  44879. */
  44880. bindTexture( webglType, webglTexture, webglSlot ) {
  44881. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  44882. if ( webglSlot === undefined ) {
  44883. if ( currentTextureSlot === null ) {
  44884. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  44885. } else {
  44886. webglSlot = currentTextureSlot;
  44887. }
  44888. }
  44889. let boundTexture = currentBoundTextures[ webglSlot ];
  44890. if ( boundTexture === undefined ) {
  44891. boundTexture = { type: undefined, texture: undefined };
  44892. currentBoundTextures[ webglSlot ] = boundTexture;
  44893. }
  44894. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  44895. if ( currentTextureSlot !== webglSlot ) {
  44896. gl.activeTexture( webglSlot );
  44897. this.currentTextureSlot = webglSlot;
  44898. }
  44899. gl.bindTexture( webglType, webglTexture );
  44900. boundTexture.type = webglType;
  44901. boundTexture.texture = webglTexture;
  44902. }
  44903. }
  44904. /**
  44905. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  44906. *
  44907. * This method caches the state so `gl.bindBufferBase()` is only
  44908. * called when necessary.
  44909. *
  44910. * @param {number} target - The target for the bind operation.
  44911. * @param {number} index - The index of the target.
  44912. * @param {WebGLBuffer} buffer - The WebGL buffer.
  44913. * @return {boolean} Whether a bind has been executed or not.
  44914. */
  44915. bindBufferBase( target, index, buffer ) {
  44916. const { gl } = this;
  44917. const key = `${target}-${index}`;
  44918. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  44919. gl.bindBufferBase( target, index, buffer );
  44920. this.currentBoundBufferBases[ key ] = buffer;
  44921. return true;
  44922. }
  44923. return false;
  44924. }
  44925. /**
  44926. * Unbinds the current bound texture.
  44927. *
  44928. * This method caches the state so `gl.bindTexture()` is only
  44929. * called when necessary.
  44930. */
  44931. unbindTexture() {
  44932. const { gl, currentTextureSlot, currentBoundTextures } = this;
  44933. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  44934. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  44935. gl.bindTexture( boundTexture.type, null );
  44936. boundTexture.type = undefined;
  44937. boundTexture.texture = undefined;
  44938. }
  44939. }
  44940. }
  44941. /**
  44942. * A WebGL 2 backend utility module with common helpers.
  44943. *
  44944. * @private
  44945. */
  44946. class WebGLUtils {
  44947. /**
  44948. * Constructs a new utility object.
  44949. *
  44950. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44951. */
  44952. constructor( backend ) {
  44953. /**
  44954. * A reference to the WebGL 2 backend.
  44955. *
  44956. * @type {WebGLBackend}
  44957. */
  44958. this.backend = backend;
  44959. /**
  44960. * A reference to the rendering context.
  44961. *
  44962. * @type {WebGL2RenderingContext}
  44963. */
  44964. this.gl = this.backend.gl;
  44965. /**
  44966. * A reference to a backend module holding extension-related
  44967. * utility functions.
  44968. *
  44969. * @type {WebGLExtensions}
  44970. */
  44971. this.extensions = backend.extensions;
  44972. }
  44973. /**
  44974. * Converts the given three.js constant into a WebGL constant.
  44975. * The method currently supports the conversion of texture formats
  44976. * and types.
  44977. *
  44978. * @param {number} p - The three.js constant.
  44979. * @param {string} [colorSpace=NoColorSpace] - The color space.
  44980. * @return {?number} The corresponding WebGL constant.
  44981. */
  44982. convert( p, colorSpace = NoColorSpace ) {
  44983. const { gl, extensions } = this;
  44984. let extension;
  44985. const transfer = ColorManagement.getTransfer( colorSpace );
  44986. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  44987. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  44988. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  44989. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  44990. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  44991. if ( p === ByteType ) return gl.BYTE;
  44992. if ( p === ShortType ) return gl.SHORT;
  44993. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  44994. if ( p === IntType ) return gl.INT;
  44995. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  44996. if ( p === FloatType ) return gl.FLOAT;
  44997. if ( p === HalfFloatType ) {
  44998. return gl.HALF_FLOAT;
  44999. }
  45000. if ( p === AlphaFormat ) return gl.ALPHA;
  45001. if ( p === RGBFormat ) return gl.RGB;
  45002. if ( p === RGBAFormat ) return gl.RGBA;
  45003. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  45004. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  45005. // WebGL2 formats.
  45006. if ( p === RedFormat ) return gl.RED;
  45007. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  45008. if ( p === RGFormat ) return gl.RG;
  45009. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  45010. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  45011. // S3TC
  45012. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  45013. if ( transfer === SRGBTransfer ) {
  45014. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  45015. if ( extension !== null ) {
  45016. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  45017. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  45018. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  45019. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  45020. } else {
  45021. return null;
  45022. }
  45023. } else {
  45024. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  45025. if ( extension !== null ) {
  45026. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  45027. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45028. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45029. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45030. } else {
  45031. return null;
  45032. }
  45033. }
  45034. }
  45035. // PVRTC
  45036. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  45037. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  45038. if ( extension !== null ) {
  45039. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  45040. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  45041. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  45042. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  45043. } else {
  45044. return null;
  45045. }
  45046. }
  45047. // ETC
  45048. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  45049. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  45050. if ( extension !== null ) {
  45051. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  45052. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  45053. } else {
  45054. return null;
  45055. }
  45056. }
  45057. // ASTC
  45058. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  45059. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  45060. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  45061. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  45062. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  45063. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  45064. if ( extension !== null ) {
  45065. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  45066. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  45067. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  45068. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  45069. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  45070. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  45071. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  45072. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  45073. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  45074. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  45075. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  45076. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  45077. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  45078. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  45079. } else {
  45080. return null;
  45081. }
  45082. }
  45083. // BPTC
  45084. if ( p === RGBA_BPTC_Format ) {
  45085. extension = extensions.get( 'EXT_texture_compression_bptc' );
  45086. if ( extension !== null ) {
  45087. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  45088. } else {
  45089. return null;
  45090. }
  45091. }
  45092. // RGTC
  45093. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  45094. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  45095. if ( extension !== null ) {
  45096. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  45097. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  45098. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  45099. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  45100. } else {
  45101. return null;
  45102. }
  45103. }
  45104. //
  45105. if ( p === UnsignedInt248Type ) {
  45106. return gl.UNSIGNED_INT_24_8;
  45107. }
  45108. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  45109. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  45110. }
  45111. /**
  45112. * This method can be used to synchronize the CPU with the GPU by waiting until
  45113. * ongoing GPU commands have been completed.
  45114. *
  45115. * @private
  45116. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  45117. */
  45118. _clientWaitAsync() {
  45119. const { gl } = this;
  45120. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  45121. gl.flush();
  45122. return new Promise( ( resolve, reject ) => {
  45123. function test() {
  45124. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  45125. if ( res === gl.WAIT_FAILED ) {
  45126. gl.deleteSync( sync );
  45127. reject();
  45128. return;
  45129. }
  45130. if ( res === gl.TIMEOUT_EXPIRED ) {
  45131. requestAnimationFrame( test );
  45132. return;
  45133. }
  45134. gl.deleteSync( sync );
  45135. resolve();
  45136. }
  45137. test();
  45138. } );
  45139. }
  45140. }
  45141. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  45142. /**
  45143. * A WebGL 2 backend utility module for managing textures.
  45144. *
  45145. * @private
  45146. */
  45147. class WebGLTextureUtils {
  45148. /**
  45149. * Constructs a new utility object.
  45150. *
  45151. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45152. */
  45153. constructor( backend ) {
  45154. /**
  45155. * A reference to the WebGL 2 backend.
  45156. *
  45157. * @type {WebGLBackend}
  45158. */
  45159. this.backend = backend;
  45160. /**
  45161. * A reference to the rendering context.
  45162. *
  45163. * @type {WebGL2RenderingContext}
  45164. */
  45165. this.gl = backend.gl;
  45166. /**
  45167. * A reference to a backend module holding extension-related
  45168. * utility functions.
  45169. *
  45170. * @type {WebGLExtensions}
  45171. */
  45172. this.extensions = backend.extensions;
  45173. /**
  45174. * A dictionary for managing default textures. The key
  45175. * is the binding point (target), the value the WEbGL texture object.
  45176. *
  45177. * @type {Object<GLenum,WebGLTexture>}
  45178. */
  45179. this.defaultTextures = {};
  45180. /**
  45181. * A scratch framebuffer used for attaching the source texture in
  45182. * {@link copyTextureToTexture}.
  45183. *
  45184. * @private
  45185. * @type {?WebGLFramebuffer}
  45186. */
  45187. this._srcFramebuffer = null;
  45188. /**
  45189. * A scratch framebuffer used for attaching the destination texture in
  45190. * {@link copyTextureToTexture}.
  45191. *
  45192. * @private
  45193. * @type {?WebGLFramebuffer}
  45194. */
  45195. this._dstFramebuffer = null;
  45196. if ( initialized === false ) {
  45197. this._init();
  45198. initialized = true;
  45199. }
  45200. }
  45201. /**
  45202. * Inits the state of the utility.
  45203. *
  45204. * @private
  45205. */
  45206. _init() {
  45207. const gl = this.gl;
  45208. // Store only WebGL constants here.
  45209. wrappingToGL = {
  45210. [ RepeatWrapping ]: gl.REPEAT,
  45211. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  45212. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  45213. };
  45214. filterToGL = {
  45215. [ NearestFilter ]: gl.NEAREST,
  45216. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  45217. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  45218. [ LinearFilter ]: gl.LINEAR,
  45219. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  45220. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  45221. };
  45222. compareToGL = {
  45223. [ NeverCompare ]: gl.NEVER,
  45224. [ AlwaysCompare ]: gl.ALWAYS,
  45225. [ LessCompare ]: gl.LESS,
  45226. [ LessEqualCompare ]: gl.LEQUAL,
  45227. [ EqualCompare ]: gl.EQUAL,
  45228. [ GreaterEqualCompare ]: gl.GEQUAL,
  45229. [ GreaterCompare ]: gl.GREATER,
  45230. [ NotEqualCompare ]: gl.NOTEQUAL
  45231. };
  45232. }
  45233. /**
  45234. * Returns the native texture type for the given texture.
  45235. *
  45236. * @param {Texture} texture - The texture.
  45237. * @return {GLenum} The native texture type.
  45238. */
  45239. getGLTextureType( texture ) {
  45240. const { gl } = this;
  45241. let glTextureType;
  45242. if ( texture.isCubeTexture === true ) {
  45243. glTextureType = gl.TEXTURE_CUBE_MAP;
  45244. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45245. glTextureType = gl.TEXTURE_2D_ARRAY;
  45246. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  45247. glTextureType = gl.TEXTURE_3D;
  45248. } else {
  45249. glTextureType = gl.TEXTURE_2D;
  45250. }
  45251. return glTextureType;
  45252. }
  45253. /**
  45254. * Returns the native texture type for the given texture.
  45255. *
  45256. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  45257. * @param {GLenum} glFormat - The WebGL format.
  45258. * @param {GLenum} glType - The WebGL type.
  45259. * @param {string} colorSpace - The texture's color space.
  45260. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  45261. * @return {GLenum} The internal format.
  45262. */
  45263. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  45264. const { gl, extensions } = this;
  45265. if ( internalFormatName !== null ) {
  45266. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  45267. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  45268. }
  45269. let internalFormat = glFormat;
  45270. if ( glFormat === gl.RED ) {
  45271. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  45272. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  45273. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  45274. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  45275. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45276. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45277. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45278. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45279. }
  45280. if ( glFormat === gl.RED_INTEGER ) {
  45281. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  45282. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  45283. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  45284. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  45285. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  45286. if ( glType === gl.INT ) internalFormat = gl.R32I;
  45287. }
  45288. if ( glFormat === gl.RG ) {
  45289. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  45290. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  45291. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  45292. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  45293. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45294. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45295. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45296. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45297. }
  45298. if ( glFormat === gl.RG_INTEGER ) {
  45299. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  45300. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  45301. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  45302. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  45303. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  45304. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  45305. }
  45306. if ( glFormat === gl.RGB ) {
  45307. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45308. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  45309. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  45310. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  45311. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  45312. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45313. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45314. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45315. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45316. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  45317. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  45318. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45319. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  45320. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  45321. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  45322. }
  45323. if ( glFormat === gl.RGB_INTEGER ) {
  45324. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  45325. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  45326. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  45327. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  45328. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  45329. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  45330. }
  45331. if ( glFormat === gl.RGBA ) {
  45332. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  45333. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  45334. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  45335. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  45336. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  45337. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45338. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45339. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45340. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45341. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  45342. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  45343. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  45344. }
  45345. if ( glFormat === gl.RGBA_INTEGER ) {
  45346. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  45347. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  45348. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  45349. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  45350. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  45351. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  45352. }
  45353. if ( glFormat === gl.DEPTH_COMPONENT ) {
  45354. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  45355. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  45356. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  45357. }
  45358. if ( glFormat === gl.DEPTH_STENCIL ) {
  45359. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  45360. }
  45361. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  45362. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  45363. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  45364. extensions.get( 'EXT_color_buffer_float' );
  45365. }
  45366. return internalFormat;
  45367. }
  45368. /**
  45369. * Sets the texture parameters for the given texture.
  45370. *
  45371. * @param {GLenum} textureType - The texture type.
  45372. * @param {Texture} texture - The texture.
  45373. */
  45374. setTextureParameters( textureType, texture ) {
  45375. const { gl, extensions, backend } = this;
  45376. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  45377. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  45378. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  45379. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  45380. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  45381. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  45382. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  45383. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  45384. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  45385. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  45386. // WebGL 2 does not support wrapping for depth 2D array textures
  45387. if ( ! texture.isArrayTexture ) {
  45388. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  45389. }
  45390. }
  45391. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  45392. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  45393. // follow WebGPU backend mapping for texture filtering
  45394. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  45395. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  45396. if ( texture.compareFunction ) {
  45397. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  45398. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  45399. }
  45400. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  45401. if ( texture.magFilter === NearestFilter ) return;
  45402. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  45403. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  45404. if ( texture.anisotropy > 1 ) {
  45405. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  45406. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  45407. }
  45408. }
  45409. }
  45410. /**
  45411. * Creates a default texture for the given texture that can be used
  45412. * as a placeholder until the actual texture is ready for usage.
  45413. *
  45414. * @param {Texture} texture - The texture to create a default texture for.
  45415. */
  45416. createDefaultTexture( texture ) {
  45417. const { gl, backend, defaultTextures } = this;
  45418. const glTextureType = this.getGLTextureType( texture );
  45419. let textureGPU = defaultTextures[ glTextureType ];
  45420. if ( textureGPU === undefined ) {
  45421. textureGPU = gl.createTexture();
  45422. backend.state.bindTexture( glTextureType, textureGPU );
  45423. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  45424. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  45425. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  45426. defaultTextures[ glTextureType ] = textureGPU;
  45427. }
  45428. backend.set( texture, {
  45429. textureGPU,
  45430. glTextureType
  45431. } );
  45432. }
  45433. /**
  45434. * Defines a texture on the GPU for the given texture object.
  45435. *
  45436. * @param {Texture} texture - The texture.
  45437. * @param {Object} [options={}] - Optional configuration parameter.
  45438. * @return {undefined}
  45439. */
  45440. createTexture( texture, options ) {
  45441. const { gl, backend } = this;
  45442. const { levels, width, height, depth } = options;
  45443. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  45444. const glType = backend.utils.convert( texture.type );
  45445. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  45446. const textureGPU = gl.createTexture();
  45447. const glTextureType = this.getGLTextureType( texture );
  45448. backend.state.bindTexture( glTextureType, textureGPU );
  45449. this.setTextureParameters( glTextureType, texture );
  45450. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  45451. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  45452. } else if ( texture.isData3DTexture ) {
  45453. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  45454. } else if ( ! texture.isVideoTexture ) {
  45455. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  45456. }
  45457. backend.set( texture, {
  45458. textureGPU,
  45459. glTextureType,
  45460. glFormat,
  45461. glType,
  45462. glInternalFormat
  45463. } );
  45464. }
  45465. /**
  45466. * Uploads texture buffer data to the GPU memory.
  45467. *
  45468. * @param {WebGLBuffer} buffer - The buffer data.
  45469. * @param {Texture} texture - The texture,
  45470. */
  45471. copyBufferToTexture( buffer, texture ) {
  45472. const { gl, backend } = this;
  45473. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  45474. const { width, height } = texture.source.data;
  45475. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  45476. backend.state.bindTexture( glTextureType, textureGPU );
  45477. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  45478. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  45479. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  45480. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  45481. backend.state.unbindTexture();
  45482. // debug
  45483. // const framebuffer = gl.createFramebuffer();
  45484. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  45485. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  45486. // const readout = new Float32Array( width * height * 4 );
  45487. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  45488. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  45489. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  45490. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  45491. // log( readout );
  45492. }
  45493. /**
  45494. * Uploads the updated texture data to the GPU.
  45495. *
  45496. * @param {Texture} texture - The texture.
  45497. * @param {Object} [options={}] - Optional configuration parameter.
  45498. */
  45499. updateTexture( texture, options ) {
  45500. const { gl } = this;
  45501. const { width, height } = options;
  45502. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  45503. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  45504. return;
  45505. this.backend.state.bindTexture( glTextureType, textureGPU );
  45506. this.setTextureParameters( glTextureType, texture );
  45507. if ( texture.isCompressedTexture ) {
  45508. const mipmaps = texture.mipmaps;
  45509. const image = options.image;
  45510. for ( let i = 0; i < mipmaps.length; i ++ ) {
  45511. const mipmap = mipmaps[ i ];
  45512. if ( texture.isCompressedArrayTexture ) {
  45513. if ( texture.format !== gl.RGBA ) {
  45514. if ( glFormat !== null ) {
  45515. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  45516. } else {
  45517. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  45518. }
  45519. } else {
  45520. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  45521. }
  45522. } else {
  45523. if ( glFormat !== null ) {
  45524. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  45525. } else {
  45526. warn( 'Unsupported compressed texture format' );
  45527. }
  45528. }
  45529. }
  45530. } else if ( texture.isCubeTexture ) {
  45531. const images = options.images;
  45532. const mipmaps = texture.mipmaps;
  45533. for ( let i = 0; i < 6; i ++ ) {
  45534. const image = getImage( images[ i ] );
  45535. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  45536. for ( let j = 0; j < mipmaps.length; j ++ ) {
  45537. const mipmap = mipmaps[ j ];
  45538. const image = getImage( mipmap.images[ i ] );
  45539. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  45540. }
  45541. }
  45542. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  45543. const image = options.image;
  45544. if ( texture.layerUpdates.size > 0 ) {
  45545. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  45546. for ( const layerIndex of texture.layerUpdates ) {
  45547. const layerData = image.data.subarray(
  45548. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  45549. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  45550. );
  45551. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  45552. }
  45553. texture.clearLayerUpdates();
  45554. } else {
  45555. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  45556. }
  45557. } else if ( texture.isData3DTexture ) {
  45558. const image = options.image;
  45559. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  45560. } else if ( texture.isVideoTexture ) {
  45561. texture.update();
  45562. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  45563. } else {
  45564. const mipmaps = texture.mipmaps;
  45565. if ( mipmaps.length > 0 ) {
  45566. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  45567. const mipmap = mipmaps[ i ];
  45568. const image = getImage( mipmap );
  45569. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  45570. }
  45571. } else {
  45572. const image = getImage( options.image );
  45573. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  45574. }
  45575. }
  45576. }
  45577. /**
  45578. * Generates mipmaps for the given texture.
  45579. *
  45580. * @param {Texture} texture - The texture.
  45581. */
  45582. generateMipmaps( texture ) {
  45583. const { gl, backend } = this;
  45584. const { textureGPU, glTextureType } = backend.get( texture );
  45585. backend.state.bindTexture( glTextureType, textureGPU );
  45586. gl.generateMipmap( glTextureType );
  45587. }
  45588. /**
  45589. * Deallocates the render buffers of the given render target.
  45590. *
  45591. * @param {RenderTarget} renderTarget - The render target.
  45592. */
  45593. deallocateRenderBuffers( renderTarget ) {
  45594. const { gl, backend } = this;
  45595. // remove framebuffer reference
  45596. if ( renderTarget ) {
  45597. const renderContextData = backend.get( renderTarget );
  45598. renderContextData.renderBufferStorageSetup = undefined;
  45599. if ( renderContextData.framebuffers ) {
  45600. for ( const cacheKey in renderContextData.framebuffers ) {
  45601. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  45602. }
  45603. delete renderContextData.framebuffers;
  45604. }
  45605. if ( renderContextData.depthRenderbuffer ) {
  45606. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  45607. delete renderContextData.depthRenderbuffer;
  45608. }
  45609. if ( renderContextData.stencilRenderbuffer ) {
  45610. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  45611. delete renderContextData.stencilRenderbuffer;
  45612. }
  45613. if ( renderContextData.msaaFrameBuffer ) {
  45614. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  45615. delete renderContextData.msaaFrameBuffer;
  45616. }
  45617. if ( renderContextData.msaaRenderbuffers ) {
  45618. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  45619. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  45620. }
  45621. delete renderContextData.msaaRenderbuffers;
  45622. }
  45623. }
  45624. }
  45625. /**
  45626. * Destroys the GPU data for the given texture object.
  45627. *
  45628. * @param {Texture} texture - The texture.
  45629. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  45630. */
  45631. destroyTexture( texture, isDefaultTexture = false ) {
  45632. const { gl, backend } = this;
  45633. const { textureGPU, renderTarget } = backend.get( texture );
  45634. this.deallocateRenderBuffers( renderTarget );
  45635. if ( isDefaultTexture === false ) {
  45636. gl.deleteTexture( textureGPU );
  45637. }
  45638. backend.delete( texture );
  45639. }
  45640. /**
  45641. * Copies data of the given source texture to the given destination texture.
  45642. *
  45643. * @param {Texture} srcTexture - The source texture.
  45644. * @param {Texture} dstTexture - The destination texture.
  45645. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45646. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45647. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45648. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45649. */
  45650. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  45651. const { gl, backend } = this;
  45652. const { state } = this.backend;
  45653. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  45654. state.bindTexture( glTextureType, dstTextureGPU );
  45655. // gather the necessary dimensions to copy
  45656. let width, height, depth, minX, minY, minZ;
  45657. let dstX, dstY, dstZ;
  45658. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  45659. if ( srcRegion !== null ) {
  45660. width = srcRegion.max.x - srcRegion.min.x;
  45661. height = srcRegion.max.y - srcRegion.min.y;
  45662. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  45663. minX = srcRegion.min.x;
  45664. minY = srcRegion.min.y;
  45665. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  45666. } else {
  45667. const levelScale = Math.pow( 2, - srcLevel );
  45668. width = Math.floor( image.width * levelScale );
  45669. height = Math.floor( image.height * levelScale );
  45670. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  45671. depth = image.depth;
  45672. } else if ( srcTexture.isData3DTexture ) {
  45673. depth = Math.floor( image.depth * levelScale );
  45674. } else {
  45675. depth = 1;
  45676. }
  45677. minX = 0;
  45678. minY = 0;
  45679. minZ = 0;
  45680. }
  45681. if ( dstPosition !== null ) {
  45682. dstX = dstPosition.x;
  45683. dstY = dstPosition.y;
  45684. dstZ = dstPosition.z;
  45685. } else {
  45686. dstX = 0;
  45687. dstY = 0;
  45688. dstZ = 0;
  45689. }
  45690. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  45691. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  45692. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  45693. // used for copying data from cpu
  45694. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  45695. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  45696. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  45697. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  45698. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  45699. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  45700. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  45701. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  45702. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  45703. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  45704. // set up the src texture
  45705. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  45706. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  45707. if ( srcTexture.isDepthTexture ) {
  45708. const srcTextureData = backend.get( srcTexture );
  45709. const dstTextureData = backend.get( dstTexture );
  45710. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  45711. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  45712. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  45713. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  45714. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  45715. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  45716. for ( let i = 0; i < depth; i ++ ) {
  45717. // if the source or destination are a 3d target then a layer needs to be bound
  45718. if ( isSrc3D ) {
  45719. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  45720. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  45721. }
  45722. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  45723. }
  45724. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  45725. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  45726. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  45727. // get the appropriate frame buffers
  45728. const srcTextureData = backend.get( srcTexture );
  45729. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  45730. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  45731. // bind the frame buffer targets
  45732. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  45733. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  45734. for ( let i = 0; i < depth; i ++ ) {
  45735. // assign the correct layers and mip maps to the frame buffers
  45736. if ( isSrc3D ) {
  45737. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  45738. } else {
  45739. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  45740. }
  45741. if ( isDst3D ) {
  45742. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  45743. } else {
  45744. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  45745. }
  45746. // copy the data using the fastest function that can achieve the copy
  45747. if ( srcLevel !== 0 ) {
  45748. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  45749. } else if ( isDst3D ) {
  45750. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  45751. } else {
  45752. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  45753. }
  45754. }
  45755. // unbind read, draw buffers
  45756. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  45757. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  45758. } else {
  45759. if ( isDst3D ) {
  45760. // copy data into the 3d texture
  45761. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  45762. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  45763. } else if ( dstTexture.isCompressedArrayTexture ) {
  45764. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  45765. } else {
  45766. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  45767. }
  45768. } else {
  45769. // copy data into the 2d texture
  45770. if ( srcTexture.isDataTexture ) {
  45771. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  45772. } else if ( srcTexture.isCompressedTexture ) {
  45773. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  45774. } else {
  45775. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  45776. }
  45777. }
  45778. }
  45779. // reset values
  45780. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  45781. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  45782. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  45783. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  45784. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  45785. // Generate mipmaps only when copying level 0
  45786. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  45787. gl.generateMipmap( glTextureType );
  45788. }
  45789. state.unbindTexture();
  45790. }
  45791. /**
  45792. * Copies the current bound framebuffer to the given texture.
  45793. *
  45794. * @param {Texture} texture - The destination texture.
  45795. * @param {RenderContext} renderContext - The render context.
  45796. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45797. */
  45798. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45799. const { gl } = this;
  45800. const { state } = this.backend;
  45801. const { textureGPU } = this.backend.get( texture );
  45802. const { x, y, z: width, w: height } = rectangle;
  45803. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  45804. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  45805. if ( requireDrawFrameBuffer ) {
  45806. const partial = ( x !== 0 || y !== 0 );
  45807. let mask;
  45808. let attachment;
  45809. if ( texture.isDepthTexture === true ) {
  45810. mask = gl.DEPTH_BUFFER_BIT;
  45811. attachment = gl.DEPTH_ATTACHMENT;
  45812. if ( renderContext.stencil ) {
  45813. mask |= gl.STENCIL_BUFFER_BIT;
  45814. }
  45815. } else {
  45816. mask = gl.COLOR_BUFFER_BIT;
  45817. attachment = gl.COLOR_ATTACHMENT0;
  45818. }
  45819. if ( partial ) {
  45820. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  45821. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  45822. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  45823. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  45824. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  45825. const flippedY = srcHeight - y - height;
  45826. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  45827. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  45828. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  45829. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  45830. state.unbindTexture();
  45831. } else {
  45832. const fb = gl.createFramebuffer();
  45833. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  45834. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  45835. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  45836. gl.deleteFramebuffer( fb );
  45837. }
  45838. } else {
  45839. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  45840. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  45841. state.unbindTexture();
  45842. }
  45843. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  45844. this.backend._setFramebuffer( renderContext );
  45845. }
  45846. /**
  45847. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  45848. *
  45849. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  45850. * @param {RenderContext} renderContext - The render context.
  45851. * @param {number} samples - The MSAA sample count.
  45852. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  45853. */
  45854. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  45855. const { gl } = this;
  45856. const renderTarget = renderContext.renderTarget;
  45857. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  45858. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  45859. if ( depthBuffer && ! stencilBuffer ) {
  45860. let glInternalFormat = gl.DEPTH_COMPONENT24;
  45861. if ( useMultisampledRTT === true ) {
  45862. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  45863. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  45864. } else if ( samples > 0 ) {
  45865. if ( depthTexture && depthTexture.isDepthTexture ) {
  45866. if ( depthTexture.type === gl.FLOAT ) {
  45867. glInternalFormat = gl.DEPTH_COMPONENT32F;
  45868. }
  45869. }
  45870. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  45871. } else {
  45872. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  45873. }
  45874. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  45875. } else if ( depthBuffer && stencilBuffer ) {
  45876. if ( samples > 0 ) {
  45877. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  45878. } else {
  45879. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  45880. }
  45881. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  45882. }
  45883. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  45884. }
  45885. /**
  45886. * Returns texture data as a typed array.
  45887. *
  45888. * @async
  45889. * @param {Texture} texture - The texture to copy.
  45890. * @param {number} x - The x coordinate of the copy origin.
  45891. * @param {number} y - The y coordinate of the copy origin.
  45892. * @param {number} width - The width of the copy.
  45893. * @param {number} height - The height of the copy.
  45894. * @param {number} faceIndex - The face index.
  45895. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45896. */
  45897. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45898. const { backend, gl } = this;
  45899. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  45900. const fb = gl.createFramebuffer();
  45901. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  45902. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  45903. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  45904. const typedArrayType = this._getTypedArrayType( glType );
  45905. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  45906. const elementCount = width * height;
  45907. const byteLength = elementCount * bytesPerTexel;
  45908. const buffer = gl.createBuffer();
  45909. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  45910. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  45911. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  45912. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  45913. await backend.utils._clientWaitAsync();
  45914. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  45915. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  45916. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  45917. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  45918. gl.deleteFramebuffer( fb );
  45919. return dstBuffer;
  45920. }
  45921. /**
  45922. * Returns the corresponding typed array type for the given WebGL data type.
  45923. *
  45924. * @private
  45925. * @param {GLenum} glType - The WebGL data type.
  45926. * @return {TypedArray.constructor} The typed array type.
  45927. */
  45928. _getTypedArrayType( glType ) {
  45929. const { gl } = this;
  45930. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  45931. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  45932. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  45933. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  45934. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  45935. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  45936. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  45937. if ( glType === gl.FLOAT ) return Float32Array;
  45938. throw new Error( `Unsupported WebGL type: ${glType}` );
  45939. }
  45940. /**
  45941. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  45942. *
  45943. * @private
  45944. * @param {GLenum} glType - The WebGL data type.
  45945. * @param {GLenum} glFormat - The WebGL texture format.
  45946. * @return {number} The bytes-per-texel.
  45947. */
  45948. _getBytesPerTexel( glType, glFormat ) {
  45949. const { gl } = this;
  45950. let bytesPerComponent = 0;
  45951. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  45952. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  45953. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  45954. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  45955. glType === gl.UNSIGNED_SHORT ||
  45956. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  45957. if ( glType === gl.UNSIGNED_INT ||
  45958. glType === gl.FLOAT ) bytesPerComponent = 4;
  45959. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  45960. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  45961. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  45962. }
  45963. /**
  45964. * Frees the internal resources.
  45965. */
  45966. dispose() {
  45967. const { gl } = this;
  45968. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  45969. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  45970. }
  45971. }
  45972. function getImage( source ) {
  45973. if ( source.isDataTexture ) {
  45974. return source.image.data;
  45975. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  45976. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  45977. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  45978. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  45979. return source;
  45980. }
  45981. return source.data;
  45982. }
  45983. /**
  45984. * A WebGL 2 backend utility module for managing extensions.
  45985. *
  45986. * @private
  45987. */
  45988. class WebGLExtensions {
  45989. /**
  45990. * Constructs a new utility object.
  45991. *
  45992. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45993. */
  45994. constructor( backend ) {
  45995. /**
  45996. * A reference to the WebGL 2 backend.
  45997. *
  45998. * @type {WebGLBackend}
  45999. */
  46000. this.backend = backend;
  46001. /**
  46002. * A reference to the rendering context.
  46003. *
  46004. * @type {WebGL2RenderingContext}
  46005. */
  46006. this.gl = this.backend.gl;
  46007. /**
  46008. * A list with all the supported WebGL extensions.
  46009. *
  46010. * @type {Array<string>}
  46011. */
  46012. this.availableExtensions = this.gl.getSupportedExtensions();
  46013. /**
  46014. * A dictionary with requested WebGL extensions.
  46015. * The key is the name of the extension, the value
  46016. * the requested extension object.
  46017. *
  46018. * @type {Object<string,Object>}
  46019. */
  46020. this.extensions = {};
  46021. }
  46022. /**
  46023. * Returns the extension object for the given extension name.
  46024. *
  46025. * @param {string} name - The extension name.
  46026. * @return {Object} The extension object.
  46027. */
  46028. get( name ) {
  46029. let extension = this.extensions[ name ];
  46030. if ( extension === undefined ) {
  46031. extension = this.gl.getExtension( name );
  46032. this.extensions[ name ] = extension;
  46033. }
  46034. return extension;
  46035. }
  46036. /**
  46037. * Returns `true` if the requested extension is available.
  46038. *
  46039. * @param {string} name - The extension name.
  46040. * @return {boolean} Whether the given extension is available or not.
  46041. */
  46042. has( name ) {
  46043. return this.availableExtensions.includes( name );
  46044. }
  46045. }
  46046. /**
  46047. * A WebGL 2 backend utility module for managing the device's capabilities.
  46048. *
  46049. * @private
  46050. */
  46051. class WebGLCapabilities {
  46052. /**
  46053. * Constructs a new utility object.
  46054. *
  46055. * @param {WebGLBackend} backend - The WebGL 2 backend.
  46056. */
  46057. constructor( backend ) {
  46058. /**
  46059. * A reference to the WebGL 2 backend.
  46060. *
  46061. * @type {WebGLBackend}
  46062. */
  46063. this.backend = backend;
  46064. /**
  46065. * This value holds the cached max anisotropy value.
  46066. *
  46067. * @type {?number}
  46068. * @default null
  46069. */
  46070. this.maxAnisotropy = null;
  46071. }
  46072. /**
  46073. * Returns the maximum anisotropy texture filtering value. This value
  46074. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  46075. * WebGL extension.
  46076. *
  46077. * @return {number} The maximum anisotropy texture filtering value.
  46078. */
  46079. getMaxAnisotropy() {
  46080. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  46081. const gl = this.backend.gl;
  46082. const extensions = this.backend.extensions;
  46083. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  46084. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  46085. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  46086. } else {
  46087. this.maxAnisotropy = 0;
  46088. }
  46089. return this.maxAnisotropy;
  46090. }
  46091. }
  46092. const GLFeatureName = {
  46093. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  46094. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  46095. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  46096. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  46097. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46098. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  46099. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  46100. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  46101. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  46102. 'OVR_multiview2': 'OVR_multiview2'
  46103. };
  46104. class WebGLBufferRenderer {
  46105. constructor( backend ) {
  46106. this.gl = backend.gl;
  46107. this.extensions = backend.extensions;
  46108. this.info = backend.renderer.info;
  46109. this.mode = null;
  46110. this.index = 0;
  46111. this.type = null;
  46112. this.object = null;
  46113. }
  46114. render( start, count ) {
  46115. const { gl, mode, object, type, info, index } = this;
  46116. if ( index !== 0 ) {
  46117. gl.drawElements( mode, count, type, start );
  46118. } else {
  46119. gl.drawArrays( mode, start, count );
  46120. }
  46121. info.update( object, count, 1 );
  46122. }
  46123. renderInstances( start, count, primcount ) {
  46124. const { gl, mode, type, index, object, info } = this;
  46125. if ( primcount === 0 ) return;
  46126. if ( index !== 0 ) {
  46127. gl.drawElementsInstanced( mode, count, type, start, primcount );
  46128. } else {
  46129. gl.drawArraysInstanced( mode, start, count, primcount );
  46130. }
  46131. info.update( object, count, primcount );
  46132. }
  46133. renderMultiDraw( starts, counts, drawCount ) {
  46134. const { extensions, mode, object, info } = this;
  46135. if ( drawCount === 0 ) return;
  46136. const extension = extensions.get( 'WEBGL_multi_draw' );
  46137. if ( extension === null ) {
  46138. for ( let i = 0; i < drawCount; i ++ ) {
  46139. this.render( starts[ i ], counts[ i ] );
  46140. }
  46141. } else {
  46142. if ( this.index !== 0 ) {
  46143. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  46144. } else {
  46145. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  46146. }
  46147. let elementCount = 0;
  46148. for ( let i = 0; i < drawCount; i ++ ) {
  46149. elementCount += counts[ i ];
  46150. }
  46151. info.update( object, elementCount, 1 );
  46152. }
  46153. }
  46154. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  46155. const { extensions, mode, object, info } = this;
  46156. if ( drawCount === 0 ) return;
  46157. const extension = extensions.get( 'WEBGL_multi_draw' );
  46158. if ( extension === null ) {
  46159. for ( let i = 0; i < drawCount; i ++ ) {
  46160. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  46161. }
  46162. } else {
  46163. if ( this.index !== 0 ) {
  46164. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  46165. } else {
  46166. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  46167. }
  46168. let elementCount = 0;
  46169. for ( let i = 0; i < drawCount; i ++ ) {
  46170. elementCount += counts[ i ] * primcount[ i ];
  46171. }
  46172. info.update( object, elementCount, 1 );
  46173. }
  46174. }
  46175. //
  46176. }
  46177. /**
  46178. * Abstract base class of a timestamp query pool.
  46179. *
  46180. * @abstract
  46181. */
  46182. class TimestampQueryPool {
  46183. /**
  46184. * Creates a new timestamp query pool.
  46185. *
  46186. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  46187. */
  46188. constructor( maxQueries = 256 ) {
  46189. /**
  46190. * Whether to track timestamps or not.
  46191. *
  46192. * @type {boolean}
  46193. * @default true
  46194. */
  46195. this.trackTimestamp = true;
  46196. /**
  46197. * Maximum number of queries this pool can hold.
  46198. *
  46199. * @type {number}
  46200. * @default 256
  46201. */
  46202. this.maxQueries = maxQueries;
  46203. /**
  46204. * How many queries allocated so far.
  46205. *
  46206. * @type {number}
  46207. * @default 0
  46208. */
  46209. this.currentQueryIndex = 0;
  46210. /**
  46211. * Tracks offsets for different contexts.
  46212. *
  46213. * @type {Map<string, number>}
  46214. */
  46215. this.queryOffsets = new Map();
  46216. /**
  46217. * Whether the pool has been disposed or not.
  46218. *
  46219. * @type {boolean}
  46220. * @default false
  46221. */
  46222. this.isDisposed = false;
  46223. /**
  46224. * TODO
  46225. *
  46226. * @type {number}
  46227. * @default 0
  46228. */
  46229. this.lastValue = 0;
  46230. /**
  46231. * Stores all timestamp frames.
  46232. *
  46233. * @type {Array<number>}
  46234. */
  46235. this.frames = [];
  46236. /**
  46237. * TODO
  46238. *
  46239. * @type {boolean}
  46240. * @default false
  46241. */
  46242. this.pendingResolve = false;
  46243. /**
  46244. * Stores the latest timestamp for each render context.
  46245. *
  46246. * @type {Map<string, number>}
  46247. */
  46248. this.timestamps = new Map();
  46249. }
  46250. /**
  46251. * Returns all timestamp frames.
  46252. *
  46253. * @return {Array<number>} The timestamp frames.
  46254. */
  46255. getTimestampFrames() {
  46256. return this.frames;
  46257. }
  46258. /**
  46259. * Returns the timestamp for a given render context.
  46260. *
  46261. * @param {string} uid - A unique identifier for the render context.
  46262. * @return {?number} The timestamp, or undefined if not available.
  46263. */
  46264. getTimestamp( uid ) {
  46265. let timestamp = this.timestamps.get( uid );
  46266. if ( timestamp === undefined ) {
  46267. warn( `TimestampQueryPool: No timestamp available for uid ${ uid }.` );
  46268. timestamp = 0;
  46269. }
  46270. return timestamp;
  46271. }
  46272. /**
  46273. * Allocate queries for a specific uid.
  46274. *
  46275. * @abstract
  46276. * @param {string} uid - A unique identifier for the render context.
  46277. * @param {number} frameId - The current frame identifier.
  46278. * @returns {?number}
  46279. */
  46280. allocateQueriesForContext( /* uid, frameId */ ) {}
  46281. /**
  46282. * Resolve all timestamps and return data (or process them).
  46283. *
  46284. * @abstract
  46285. * @async
  46286. * @returns {Promise<number>|number} The resolved timestamp value.
  46287. */
  46288. async resolveQueriesAsync() {}
  46289. /**
  46290. * Dispose of the query pool.
  46291. *
  46292. * @abstract
  46293. */
  46294. dispose() {}
  46295. }
  46296. /**
  46297. * Manages a pool of WebGL timestamp queries for performance measurement.
  46298. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  46299. *
  46300. * @augments TimestampQueryPool
  46301. */
  46302. class WebGLTimestampQueryPool extends TimestampQueryPool {
  46303. /**
  46304. * Creates a new WebGL timestamp query pool.
  46305. *
  46306. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  46307. * @param {string} type - The type identifier for this query pool.
  46308. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  46309. */
  46310. constructor( gl, type, maxQueries = 2048 ) {
  46311. super( maxQueries );
  46312. this.gl = gl;
  46313. this.type = type;
  46314. // Check for timer query extensions
  46315. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  46316. gl.getExtension( 'EXT_disjoint_timer_query' );
  46317. if ( ! this.ext ) {
  46318. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  46319. this.trackTimestamp = false;
  46320. return;
  46321. }
  46322. // Create query objects
  46323. this.queries = [];
  46324. for ( let i = 0; i < this.maxQueries; i ++ ) {
  46325. this.queries.push( gl.createQuery() );
  46326. }
  46327. this.activeQuery = null;
  46328. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  46329. }
  46330. /**
  46331. * Allocates a pair of queries for a given render context.
  46332. *
  46333. * @param {string} uid - A unique identifier for the render context.
  46334. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  46335. */
  46336. allocateQueriesForContext( uid ) {
  46337. if ( ! this.trackTimestamp ) return null;
  46338. // Check if we have enough space for a new query pair
  46339. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  46340. 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() } ).` );
  46341. return null;
  46342. }
  46343. const baseOffset = this.currentQueryIndex;
  46344. this.currentQueryIndex += 2;
  46345. // Initialize query states
  46346. this.queryStates.set( baseOffset, 'inactive' );
  46347. this.queryOffsets.set( uid, baseOffset );
  46348. return baseOffset;
  46349. }
  46350. /**
  46351. * Begins a timestamp query for the specified render context.
  46352. *
  46353. * @param {string} uid - A unique identifier for the render context.
  46354. */
  46355. beginQuery( uid ) {
  46356. if ( ! this.trackTimestamp || this.isDisposed ) {
  46357. return;
  46358. }
  46359. const baseOffset = this.queryOffsets.get( uid );
  46360. if ( baseOffset == null ) {
  46361. return;
  46362. }
  46363. // Don't start a new query if there's an active one
  46364. if ( this.activeQuery !== null ) {
  46365. return;
  46366. }
  46367. const query = this.queries[ baseOffset ];
  46368. if ( ! query ) {
  46369. return;
  46370. }
  46371. try {
  46372. // Only begin if query is inactive
  46373. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  46374. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  46375. this.activeQuery = baseOffset;
  46376. this.queryStates.set( baseOffset, 'started' );
  46377. }
  46378. } catch ( error ) {
  46379. error( 'Error in beginQuery:', error );
  46380. this.activeQuery = null;
  46381. this.queryStates.set( baseOffset, 'inactive' );
  46382. }
  46383. }
  46384. /**
  46385. * Ends the active timestamp query for the specified render context.
  46386. *
  46387. * @param {string} uid - A unique identifier for the render context.
  46388. */
  46389. endQuery( uid ) {
  46390. if ( ! this.trackTimestamp || this.isDisposed ) {
  46391. return;
  46392. }
  46393. const baseOffset = this.queryOffsets.get( uid );
  46394. if ( baseOffset == null ) {
  46395. return;
  46396. }
  46397. // Only end if this is the active query
  46398. if ( this.activeQuery !== baseOffset ) {
  46399. return;
  46400. }
  46401. try {
  46402. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  46403. this.queryStates.set( baseOffset, 'ended' );
  46404. this.activeQuery = null;
  46405. } catch ( error ) {
  46406. error( 'Error in endQuery:', error );
  46407. // Reset state on error
  46408. this.queryStates.set( baseOffset, 'inactive' );
  46409. this.activeQuery = null;
  46410. }
  46411. }
  46412. /**
  46413. * Asynchronously resolves all completed queries and returns the total duration.
  46414. *
  46415. * @async
  46416. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  46417. */
  46418. async resolveQueriesAsync() {
  46419. if ( ! this.trackTimestamp || this.pendingResolve ) {
  46420. return this.lastValue;
  46421. }
  46422. this.pendingResolve = true;
  46423. try {
  46424. // Wait for all ended queries to complete
  46425. const resolvePromises = new Map();
  46426. for ( const [ uid, baseOffset ] of this.queryOffsets ) {
  46427. const state = this.queryStates.get( baseOffset );
  46428. if ( state === 'ended' ) {
  46429. const query = this.queries[ baseOffset ];
  46430. resolvePromises.set( uid, this.resolveQuery( query ) );
  46431. }
  46432. }
  46433. if ( resolvePromises.size === 0 ) {
  46434. return this.lastValue;
  46435. }
  46436. //
  46437. const framesDuration = {};
  46438. const frames = [];
  46439. for ( const [ uid, promise ] of resolvePromises ) {
  46440. const match = uid.match( /^(.*):f(\d+)$/ );
  46441. const frame = parseInt( match[ 2 ] );
  46442. if ( frames.includes( frame ) === false ) {
  46443. frames.push( frame );
  46444. }
  46445. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  46446. const duration = await promise;
  46447. this.timestamps.set( uid, duration );
  46448. framesDuration[ frame ] += duration;
  46449. }
  46450. // Return the total duration of the last frame
  46451. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  46452. // Store the last valid result
  46453. this.lastValue = totalDuration;
  46454. this.frames = frames;
  46455. // Reset states
  46456. this.currentQueryIndex = 0;
  46457. this.queryOffsets.clear();
  46458. this.queryStates.clear();
  46459. this.activeQuery = null;
  46460. return totalDuration;
  46461. } catch ( error ) {
  46462. error( 'Error resolving queries:', error );
  46463. return this.lastValue;
  46464. } finally {
  46465. this.pendingResolve = false;
  46466. }
  46467. }
  46468. /**
  46469. * Resolves a single query, checking for completion and disjoint operation.
  46470. *
  46471. * @async
  46472. * @param {WebGLQuery} query - The query object to resolve.
  46473. * @returns {Promise<number>} The elapsed time in milliseconds.
  46474. */
  46475. async resolveQuery( query ) {
  46476. return new Promise( ( resolve ) => {
  46477. if ( this.isDisposed ) {
  46478. resolve( this.lastValue );
  46479. return;
  46480. }
  46481. let timeoutId;
  46482. let isResolved = false;
  46483. const cleanup = () => {
  46484. if ( timeoutId ) {
  46485. clearTimeout( timeoutId );
  46486. timeoutId = null;
  46487. }
  46488. };
  46489. const finalizeResolution = ( value ) => {
  46490. if ( ! isResolved ) {
  46491. isResolved = true;
  46492. cleanup();
  46493. resolve( value );
  46494. }
  46495. };
  46496. const checkQuery = () => {
  46497. if ( this.isDisposed ) {
  46498. finalizeResolution( this.lastValue );
  46499. return;
  46500. }
  46501. try {
  46502. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  46503. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  46504. if ( disjoint ) {
  46505. finalizeResolution( this.lastValue );
  46506. return;
  46507. }
  46508. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  46509. if ( ! available ) {
  46510. timeoutId = setTimeout( checkQuery, 1 );
  46511. return;
  46512. }
  46513. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  46514. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  46515. } catch ( error ) {
  46516. error( 'Error checking query:', error );
  46517. resolve( this.lastValue );
  46518. }
  46519. };
  46520. checkQuery();
  46521. } );
  46522. }
  46523. /**
  46524. * Releases all resources held by this query pool.
  46525. * This includes deleting all query objects and clearing internal state.
  46526. */
  46527. dispose() {
  46528. if ( this.isDisposed ) {
  46529. return;
  46530. }
  46531. this.isDisposed = true;
  46532. if ( ! this.trackTimestamp ) return;
  46533. for ( const query of this.queries ) {
  46534. this.gl.deleteQuery( query );
  46535. }
  46536. this.queries = [];
  46537. this.queryStates.clear();
  46538. this.queryOffsets.clear();
  46539. this.lastValue = 0;
  46540. this.activeQuery = null;
  46541. }
  46542. }
  46543. /**
  46544. * A backend implementation targeting WebGL 2.
  46545. *
  46546. * @private
  46547. * @augments Backend
  46548. */
  46549. class WebGLBackend extends Backend {
  46550. /**
  46551. * WebGLBackend options.
  46552. *
  46553. * @typedef {Object} WebGLBackend~Options
  46554. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46555. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46556. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46557. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46558. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46559. * @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.
  46560. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46561. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  46562. */
  46563. /**
  46564. * Constructs a new WebGPU backend.
  46565. *
  46566. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  46567. */
  46568. constructor( parameters = {} ) {
  46569. super( parameters );
  46570. /**
  46571. * This flag can be used for type testing.
  46572. *
  46573. * @type {boolean}
  46574. * @readonly
  46575. * @default true
  46576. */
  46577. this.isWebGLBackend = true;
  46578. /**
  46579. * A reference to a backend module holding shader attribute-related
  46580. * utility functions.
  46581. *
  46582. * @type {?WebGLAttributeUtils}
  46583. * @default null
  46584. */
  46585. this.attributeUtils = null;
  46586. /**
  46587. * A reference to a backend module holding extension-related
  46588. * utility functions.
  46589. *
  46590. * @type {?WebGLExtensions}
  46591. * @default null
  46592. */
  46593. this.extensions = null;
  46594. /**
  46595. * A reference to a backend module holding capability-related
  46596. * utility functions.
  46597. *
  46598. * @type {?WebGLCapabilities}
  46599. * @default null
  46600. */
  46601. this.capabilities = null;
  46602. /**
  46603. * A reference to a backend module holding texture-related
  46604. * utility functions.
  46605. *
  46606. * @type {?WebGLTextureUtils}
  46607. * @default null
  46608. */
  46609. this.textureUtils = null;
  46610. /**
  46611. * A reference to a backend module holding renderer-related
  46612. * utility functions.
  46613. *
  46614. * @type {?WebGLBufferRenderer}
  46615. * @default null
  46616. */
  46617. this.bufferRenderer = null;
  46618. /**
  46619. * A reference to the rendering context.
  46620. *
  46621. * @type {?WebGL2RenderingContext}
  46622. * @default null
  46623. */
  46624. this.gl = null;
  46625. /**
  46626. * A reference to a backend module holding state-related
  46627. * utility functions.
  46628. *
  46629. * @type {?WebGLState}
  46630. * @default null
  46631. */
  46632. this.state = null;
  46633. /**
  46634. * A reference to a backend module holding common
  46635. * utility functions.
  46636. *
  46637. * @type {?WebGLUtils}
  46638. * @default null
  46639. */
  46640. this.utils = null;
  46641. /**
  46642. * Dictionary for caching VAOs.
  46643. *
  46644. * @type {Object<string,WebGLVertexArrayObject>}
  46645. */
  46646. this.vaoCache = {};
  46647. /**
  46648. * Dictionary for caching transform feedback objects.
  46649. *
  46650. * @type {Object<string,WebGLTransformFeedback>}
  46651. */
  46652. this.transformFeedbackCache = {};
  46653. /**
  46654. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  46655. * Only relevant when using compute shaders.
  46656. *
  46657. * @type {boolean}
  46658. * @default false
  46659. */
  46660. this.discard = false;
  46661. /**
  46662. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  46663. * device does not support the extension.
  46664. *
  46665. * @type {?EXTDisjointTimerQueryWebGL2}
  46666. * @default null
  46667. */
  46668. this.disjoint = null;
  46669. /**
  46670. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  46671. * device does not support the extension.
  46672. *
  46673. * @type {?KHRParallelShaderCompile}
  46674. * @default null
  46675. */
  46676. this.parallel = null;
  46677. /**
  46678. * A reference to the current render context.
  46679. *
  46680. * @private
  46681. * @type {RenderContext}
  46682. * @default null
  46683. */
  46684. this._currentContext = null;
  46685. /**
  46686. * A unique collection of bindings.
  46687. *
  46688. * @private
  46689. * @type {WeakSet<Array<BindGroup>>}
  46690. */
  46691. this._knownBindings = new WeakSet();
  46692. /**
  46693. * Whether the device supports framebuffers invalidation or not.
  46694. *
  46695. * @private
  46696. * @type {boolean}
  46697. */
  46698. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  46699. /**
  46700. * The target framebuffer when rendering with
  46701. * the WebXR device API.
  46702. *
  46703. * @private
  46704. * @type {?WebGLFramebuffer}
  46705. * @default null
  46706. */
  46707. this._xrFramebuffer = null;
  46708. }
  46709. /**
  46710. * Initializes the backend so it is ready for usage.
  46711. *
  46712. * @param {Renderer} renderer - The renderer.
  46713. */
  46714. init( renderer ) {
  46715. super.init( renderer );
  46716. //
  46717. const parameters = this.parameters;
  46718. const contextAttributes = {
  46719. antialias: renderer.currentSamples > 0,
  46720. alpha: true, // always true for performance reasons
  46721. depth: renderer.depth,
  46722. stencil: renderer.stencil
  46723. };
  46724. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  46725. function onContextLost( event ) {
  46726. event.preventDefault();
  46727. const contextLossInfo = {
  46728. api: 'WebGL',
  46729. message: event.statusMessage || 'Unknown reason',
  46730. reason: null,
  46731. originalEvent: event
  46732. };
  46733. renderer.onDeviceLost( contextLossInfo );
  46734. }
  46735. this._onContextLost = onContextLost;
  46736. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  46737. this.gl = glContext;
  46738. this.extensions = new WebGLExtensions( this );
  46739. this.capabilities = new WebGLCapabilities( this );
  46740. this.attributeUtils = new WebGLAttributeUtils( this );
  46741. this.textureUtils = new WebGLTextureUtils( this );
  46742. this.bufferRenderer = new WebGLBufferRenderer( this );
  46743. this.state = new WebGLState( this );
  46744. this.utils = new WebGLUtils( this );
  46745. this.extensions.get( 'EXT_color_buffer_float' );
  46746. this.extensions.get( 'WEBGL_clip_cull_distance' );
  46747. this.extensions.get( 'OES_texture_float_linear' );
  46748. this.extensions.get( 'EXT_color_buffer_half_float' );
  46749. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46750. this.extensions.get( 'WEBGL_render_shared_exponent' );
  46751. this.extensions.get( 'WEBGL_multi_draw' );
  46752. this.extensions.get( 'OVR_multiview2' );
  46753. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  46754. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  46755. }
  46756. /**
  46757. * The coordinate system of the backend.
  46758. *
  46759. * @type {number}
  46760. * @readonly
  46761. */
  46762. get coordinateSystem() {
  46763. return WebGLCoordinateSystem;
  46764. }
  46765. /**
  46766. * This method performs a readback operation by moving buffer data from
  46767. * a storage buffer attribute from the GPU to the CPU.
  46768. *
  46769. * @async
  46770. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46771. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46772. */
  46773. async getArrayBufferAsync( attribute ) {
  46774. return await this.attributeUtils.getArrayBufferAsync( attribute );
  46775. }
  46776. /**
  46777. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  46778. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  46779. *
  46780. * @async
  46781. * @return {Promise} A Promise that resolves when synchronization has been finished.
  46782. */
  46783. async waitForGPU() {
  46784. await this.utils._clientWaitAsync();
  46785. }
  46786. /**
  46787. * Ensures the backend is XR compatible.
  46788. *
  46789. * @async
  46790. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  46791. */
  46792. async makeXRCompatible() {
  46793. const attributes = this.gl.getContextAttributes();
  46794. if ( attributes.xrCompatible !== true ) {
  46795. await this.gl.makeXRCompatible();
  46796. }
  46797. }
  46798. /**
  46799. * Sets the XR rendering destination.
  46800. *
  46801. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  46802. */
  46803. setXRTarget( xrFramebuffer ) {
  46804. this._xrFramebuffer = xrFramebuffer;
  46805. }
  46806. /**
  46807. * Configures the given XR render target with external textures.
  46808. *
  46809. * This method is only relevant when using the WebXR Layers API.
  46810. *
  46811. * @param {XRRenderTarget} renderTarget - The XR render target.
  46812. * @param {WebGLTexture} colorTexture - A native color texture.
  46813. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  46814. */
  46815. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  46816. const gl = this.gl;
  46817. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  46818. if ( depthTexture !== null ) {
  46819. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  46820. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  46821. // The multisample_render_to_texture extension doesn't work properly if there
  46822. // are midframe flushes and an external depth texture.
  46823. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  46824. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  46825. }
  46826. renderTarget._autoAllocateDepthBuffer = false;
  46827. }
  46828. }
  46829. /**
  46830. * Inits a time stamp query for the given render context.
  46831. *
  46832. * @param {string} type - The type of the timestamp query.
  46833. * @param {string} uid - A unique identifier for the timestamp query.
  46834. */
  46835. initTimestampQuery( type, uid ) {
  46836. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  46837. if ( ! this.timestampQueryPool[ type ] ) {
  46838. // TODO: Variable maxQueries?
  46839. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  46840. }
  46841. const timestampQueryPool = this.timestampQueryPool[ type ];
  46842. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  46843. if ( baseOffset !== null ) {
  46844. timestampQueryPool.beginQuery( uid );
  46845. }
  46846. }
  46847. // timestamp utils
  46848. /**
  46849. * Prepares the timestamp buffer.
  46850. *
  46851. * @param {string} type - The type of the timestamp query.
  46852. * @param {string} uid - A unique identifier for the timestamp query.
  46853. */
  46854. prepareTimestampBuffer( type, uid ) {
  46855. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  46856. const timestampQueryPool = this.timestampQueryPool[ type ];
  46857. timestampQueryPool.endQuery( uid );
  46858. }
  46859. /**
  46860. * Returns the backend's rendering context.
  46861. *
  46862. * @return {WebGL2RenderingContext} The rendering context.
  46863. */
  46864. getContext() {
  46865. return this.gl;
  46866. }
  46867. /**
  46868. * This method is executed at the beginning of a render call and prepares
  46869. * the WebGL state for upcoming render calls
  46870. *
  46871. * @param {RenderContext} renderContext - The render context.
  46872. */
  46873. beginRender( renderContext ) {
  46874. const { state } = this;
  46875. const renderContextData = this.get( renderContext );
  46876. //
  46877. if ( renderContext.viewport ) {
  46878. this.updateViewport( renderContext );
  46879. } else {
  46880. const { width, height } = this.getDrawingBufferSize();
  46881. state.viewport( 0, 0, width, height );
  46882. }
  46883. if ( renderContext.scissor ) {
  46884. const { x, y, width, height } = renderContext.scissorValue;
  46885. state.scissor( x, renderContext.height - height - y, width, height );
  46886. }
  46887. //
  46888. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  46889. renderContextData.previousContext = this._currentContext;
  46890. this._currentContext = renderContext;
  46891. this._setFramebuffer( renderContext );
  46892. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  46893. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46894. if ( occlusionQueryCount > 0 ) {
  46895. // Get a reference to the array of objects with queries. The renderContextData property
  46896. // can be changed by another render pass before the async reading of all previous queries complete
  46897. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  46898. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  46899. renderContextData.lastOcclusionObject = null;
  46900. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  46901. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  46902. renderContextData.occlusionQueryIndex = 0;
  46903. }
  46904. }
  46905. /**
  46906. * This method is executed at the end of a render call and finalizes work
  46907. * after draw calls.
  46908. *
  46909. * @param {RenderContext} renderContext - The render context.
  46910. */
  46911. finishRender( renderContext ) {
  46912. const { gl, state } = this;
  46913. const renderContextData = this.get( renderContext );
  46914. const previousContext = renderContextData.previousContext;
  46915. state.resetVertexState();
  46916. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46917. if ( occlusionQueryCount > 0 ) {
  46918. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  46919. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  46920. }
  46921. this.resolveOccludedAsync( renderContext );
  46922. }
  46923. const textures = renderContext.textures;
  46924. if ( textures !== null ) {
  46925. for ( let i = 0; i < textures.length; i ++ ) {
  46926. const texture = textures[ i ];
  46927. if ( texture.generateMipmaps ) {
  46928. this.generateMipmaps( texture );
  46929. }
  46930. }
  46931. }
  46932. this._currentContext = previousContext;
  46933. this._resolveRenderTarget( renderContext );
  46934. if ( previousContext !== null ) {
  46935. this._setFramebuffer( previousContext );
  46936. if ( previousContext.viewport ) {
  46937. this.updateViewport( previousContext );
  46938. } else {
  46939. const { width, height } = this.getDrawingBufferSize();
  46940. state.viewport( 0, 0, width, height );
  46941. }
  46942. }
  46943. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  46944. }
  46945. /**
  46946. * This method processes the result of occlusion queries and writes it
  46947. * into render context data.
  46948. *
  46949. * @async
  46950. * @param {RenderContext} renderContext - The render context.
  46951. */
  46952. resolveOccludedAsync( renderContext ) {
  46953. const renderContextData = this.get( renderContext );
  46954. // handle occlusion query results
  46955. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  46956. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  46957. const occluded = new WeakSet();
  46958. const { gl } = this;
  46959. renderContextData.currentOcclusionQueryObjects = null;
  46960. renderContextData.currentOcclusionQueries = null;
  46961. const check = () => {
  46962. let completed = 0;
  46963. // check all queries and requeue as appropriate
  46964. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  46965. const query = currentOcclusionQueries[ i ];
  46966. if ( query === null ) continue;
  46967. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  46968. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  46969. currentOcclusionQueries[ i ] = null;
  46970. gl.deleteQuery( query );
  46971. completed ++;
  46972. }
  46973. }
  46974. if ( completed < currentOcclusionQueries.length ) {
  46975. requestAnimationFrame( check );
  46976. } else {
  46977. renderContextData.occluded = occluded;
  46978. }
  46979. };
  46980. check();
  46981. }
  46982. }
  46983. /**
  46984. * Returns `true` if the given 3D object is fully occluded by other
  46985. * 3D objects in the scene.
  46986. *
  46987. * @param {RenderContext} renderContext - The render context.
  46988. * @param {Object3D} object - The 3D object to test.
  46989. * @return {boolean} Whether the 3D object is fully occluded or not.
  46990. */
  46991. isOccluded( renderContext, object ) {
  46992. const renderContextData = this.get( renderContext );
  46993. return renderContextData.occluded && renderContextData.occluded.has( object );
  46994. }
  46995. /**
  46996. * Updates the viewport with the values from the given render context.
  46997. *
  46998. * @param {RenderContext} renderContext - The render context.
  46999. */
  47000. updateViewport( renderContext ) {
  47001. const { state } = this;
  47002. const { x, y, width, height } = renderContext.viewportValue;
  47003. state.viewport( x, renderContext.height - height - y, width, height );
  47004. }
  47005. /**
  47006. * Defines the scissor test.
  47007. *
  47008. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  47009. */
  47010. setScissorTest( boolean ) {
  47011. const state = this.state;
  47012. state.setScissorTest( boolean );
  47013. }
  47014. /**
  47015. * Returns the clear color and alpha into a single
  47016. * color object.
  47017. *
  47018. * @return {Color4} The clear color.
  47019. */
  47020. getClearColor() {
  47021. const clearColor = super.getClearColor();
  47022. // Since the canvas is always created with alpha: true,
  47023. // WebGL must always premultiply the clear color.
  47024. clearColor.r *= clearColor.a;
  47025. clearColor.g *= clearColor.a;
  47026. clearColor.b *= clearColor.a;
  47027. return clearColor;
  47028. }
  47029. /**
  47030. * Performs a clear operation.
  47031. *
  47032. * @param {boolean} color - Whether the color buffer should be cleared or not.
  47033. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  47034. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  47035. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  47036. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  47037. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  47038. * or not. Only relevant for explicit clears.
  47039. */
  47040. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  47041. const { gl, renderer } = this;
  47042. if ( descriptor === null ) {
  47043. const clearColor = this.getClearColor();
  47044. descriptor = {
  47045. textures: null,
  47046. clearColorValue: clearColor
  47047. };
  47048. }
  47049. //
  47050. let clear = 0;
  47051. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  47052. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  47053. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  47054. if ( clear !== 0 ) {
  47055. let clearColor;
  47056. if ( descriptor.clearColorValue ) {
  47057. clearColor = descriptor.clearColorValue;
  47058. } else {
  47059. clearColor = this.getClearColor();
  47060. }
  47061. const clearDepth = renderer.getClearDepth();
  47062. const clearStencil = renderer.getClearStencil();
  47063. if ( depth ) this.state.setDepthMask( true );
  47064. if ( descriptor.textures === null ) {
  47065. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  47066. gl.clear( clear );
  47067. } else {
  47068. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  47069. if ( color ) {
  47070. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  47071. if ( i === 0 ) {
  47072. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  47073. } else {
  47074. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  47075. }
  47076. }
  47077. }
  47078. if ( depth && stencil ) {
  47079. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  47080. } else if ( depth ) {
  47081. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  47082. } else if ( stencil ) {
  47083. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  47084. }
  47085. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  47086. }
  47087. }
  47088. }
  47089. /**
  47090. * This method is executed at the beginning of a compute call and
  47091. * prepares the state for upcoming compute tasks.
  47092. *
  47093. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47094. */
  47095. beginCompute( computeGroup ) {
  47096. const { state, gl } = this;
  47097. //
  47098. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  47099. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47100. }
  47101. /**
  47102. * Executes a compute command for the given compute node.
  47103. *
  47104. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47105. * @param {Node} computeNode - The compute node.
  47106. * @param {Array<BindGroup>} bindings - The bindings.
  47107. * @param {ComputePipeline} pipeline - The compute pipeline.
  47108. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  47109. */
  47110. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  47111. const { state, gl } = this;
  47112. if ( this.discard === false ) {
  47113. // required here to handle async behaviour of render.compute()
  47114. gl.enable( gl.RASTERIZER_DISCARD );
  47115. this.discard = true;
  47116. }
  47117. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  47118. const vaoKey = this._getVaoKey( attributes );
  47119. const vaoGPU = this.vaoCache[ vaoKey ];
  47120. if ( vaoGPU === undefined ) {
  47121. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  47122. } else {
  47123. state.setVertexState( vaoGPU );
  47124. }
  47125. state.useProgram( programGPU );
  47126. this._bindUniforms( bindings );
  47127. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  47128. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  47129. gl.beginTransformFeedback( gl.POINTS );
  47130. count = ( count !== null ) ? count : computeNode.count;
  47131. if ( Array.isArray( count ) ) {
  47132. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  47133. count = count[ 0 ];
  47134. }
  47135. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  47136. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  47137. } else {
  47138. gl.drawArrays( gl.POINTS, 0, count );
  47139. }
  47140. gl.endTransformFeedback();
  47141. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  47142. // switch active buffers
  47143. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47144. const dualAttributeData = transformBuffers[ i ];
  47145. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  47146. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  47147. }
  47148. dualAttributeData.switchBuffers();
  47149. }
  47150. }
  47151. /**
  47152. * This method is executed at the end of a compute call and
  47153. * finalizes work after compute tasks.
  47154. *
  47155. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47156. */
  47157. finishCompute( computeGroup ) {
  47158. const gl = this.gl;
  47159. this.discard = false;
  47160. gl.disable( gl.RASTERIZER_DISCARD );
  47161. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  47162. if ( this._currentContext ) {
  47163. this._setFramebuffer( this._currentContext );
  47164. }
  47165. }
  47166. /**
  47167. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  47168. *
  47169. * @param {RenderContext} renderContext - The render context.
  47170. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  47171. *
  47172. * @private
  47173. */
  47174. _isRenderCameraDepthArray( renderContext ) {
  47175. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  47176. }
  47177. /**
  47178. * Executes a draw command for the given render object.
  47179. *
  47180. * @param {RenderObject} renderObject - The render object to draw.
  47181. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47182. */
  47183. draw( renderObject/*, info*/ ) {
  47184. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  47185. const { programGPU } = this.get( pipeline );
  47186. const { gl, state } = this;
  47187. const contextData = this.get( context );
  47188. const drawParams = renderObject.getDrawParameters();
  47189. if ( drawParams === null ) return;
  47190. //
  47191. this._bindUniforms( renderObject.getBindings() );
  47192. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  47193. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  47194. state.useProgram( programGPU );
  47195. // vertex state
  47196. const attributes = renderObject.getAttributes();
  47197. const attributesData = this.get( attributes );
  47198. let vaoGPU = attributesData.vaoGPU;
  47199. if ( vaoGPU === undefined ) {
  47200. const vaoKey = this._getVaoKey( attributes );
  47201. vaoGPU = this.vaoCache[ vaoKey ];
  47202. if ( vaoGPU === undefined ) {
  47203. vaoGPU = this._createVao( attributes );
  47204. this.vaoCache[ vaoKey ] = vaoGPU;
  47205. attributesData.vaoGPU = vaoGPU;
  47206. }
  47207. }
  47208. const index = renderObject.getIndex();
  47209. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  47210. state.setVertexState( vaoGPU, indexGPU );
  47211. //
  47212. const lastObject = contextData.lastOcclusionObject;
  47213. if ( lastObject !== object && lastObject !== undefined ) {
  47214. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  47215. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  47216. contextData.occlusionQueryIndex ++;
  47217. }
  47218. if ( object.occlusionTest === true ) {
  47219. const query = gl.createQuery();
  47220. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  47221. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  47222. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  47223. }
  47224. contextData.lastOcclusionObject = object;
  47225. }
  47226. //
  47227. const renderer = this.bufferRenderer;
  47228. if ( object.isPoints ) renderer.mode = gl.POINTS;
  47229. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  47230. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  47231. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  47232. else {
  47233. if ( material.wireframe === true ) {
  47234. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  47235. renderer.mode = gl.LINES;
  47236. } else {
  47237. renderer.mode = gl.TRIANGLES;
  47238. }
  47239. }
  47240. //
  47241. const { vertexCount, instanceCount } = drawParams;
  47242. let { firstVertex } = drawParams;
  47243. renderer.object = object;
  47244. if ( index !== null ) {
  47245. firstVertex *= index.array.BYTES_PER_ELEMENT;
  47246. const indexData = this.get( index );
  47247. renderer.index = index.count;
  47248. renderer.type = indexData.type;
  47249. } else {
  47250. renderer.index = 0;
  47251. }
  47252. const draw = () => {
  47253. if ( object.isBatchedMesh ) {
  47254. if ( object._multiDrawInstances !== null ) {
  47255. // @deprecated, r174
  47256. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  47257. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  47258. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  47259. warnOnce( 'WebGLRenderer: WEBGL_multi_draw not supported.' );
  47260. } else {
  47261. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  47262. }
  47263. } else if ( instanceCount > 1 ) {
  47264. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  47265. } else {
  47266. renderer.render( firstVertex, vertexCount );
  47267. }
  47268. };
  47269. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  47270. const cameraData = this.get( renderObject.camera );
  47271. const cameras = renderObject.camera.cameras;
  47272. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  47273. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  47274. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  47275. const indexesGPU = [];
  47276. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47277. const bufferGPU = gl.createBuffer();
  47278. data[ 0 ] = i;
  47279. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47280. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  47281. indexesGPU.push( bufferGPU );
  47282. }
  47283. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  47284. }
  47285. const cameraIndexData = this.get( cameraIndex );
  47286. const pixelRatio = this.renderer.getPixelRatio();
  47287. const renderTarget = this._currentContext.renderTarget;
  47288. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  47289. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  47290. if ( isRenderCameraDepthArray ) {
  47291. // Clear the depth texture
  47292. const textureData = this.get( renderTarget.depthTexture );
  47293. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  47294. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  47295. const { stencilBuffer } = renderTarget;
  47296. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47297. this.renderer._activeCubeFace = i;
  47298. this._currentContext.activeCubeFace = i;
  47299. this._setFramebuffer( this._currentContext );
  47300. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  47301. }
  47302. this.renderer._activeCubeFace = prevActiveCubeFace;
  47303. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47304. }
  47305. }
  47306. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  47307. const subCamera = cameras[ i ];
  47308. if ( object.layers.test( subCamera.layers ) ) {
  47309. if ( isRenderCameraDepthArray ) {
  47310. // Update the active layer
  47311. this.renderer._activeCubeFace = i;
  47312. this._currentContext.activeCubeFace = i;
  47313. this._setFramebuffer( this._currentContext );
  47314. }
  47315. const vp = subCamera.viewport;
  47316. if ( vp !== undefined ) {
  47317. const x = vp.x * pixelRatio;
  47318. const y = vp.y * pixelRatio;
  47319. const width = vp.width * pixelRatio;
  47320. const height = vp.height * pixelRatio;
  47321. state.viewport(
  47322. Math.floor( x ),
  47323. Math.floor( renderObject.context.height - height - y ),
  47324. Math.floor( width ),
  47325. Math.floor( height )
  47326. );
  47327. }
  47328. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  47329. draw();
  47330. }
  47331. this._currentContext.activeCubeFace = prevActiveCubeFace;
  47332. this.renderer._activeCubeFace = prevActiveCubeFace;
  47333. }
  47334. } else {
  47335. draw();
  47336. }
  47337. }
  47338. /**
  47339. * Explain why always null is returned.
  47340. *
  47341. * @param {RenderObject} renderObject - The render object.
  47342. * @return {boolean} Whether the render pipeline requires an update or not.
  47343. */
  47344. needsRenderUpdate( /*renderObject*/ ) {
  47345. return false;
  47346. }
  47347. /**
  47348. * Explain why no cache key is computed.
  47349. *
  47350. * @param {RenderObject} renderObject - The render object.
  47351. * @return {string} The cache key.
  47352. */
  47353. getRenderCacheKey( /*renderObject*/ ) {
  47354. return '';
  47355. }
  47356. // textures
  47357. /**
  47358. * Creates a default texture for the given texture that can be used
  47359. * as a placeholder until the actual texture is ready for usage.
  47360. *
  47361. * @param {Texture} texture - The texture to create a default texture for.
  47362. */
  47363. createDefaultTexture( texture ) {
  47364. this.textureUtils.createDefaultTexture( texture );
  47365. }
  47366. /**
  47367. * Defines a texture on the GPU for the given texture object.
  47368. *
  47369. * @param {Texture} texture - The texture.
  47370. * @param {Object} [options={}] - Optional configuration parameter.
  47371. */
  47372. createTexture( texture, options ) {
  47373. this.textureUtils.createTexture( texture, options );
  47374. }
  47375. /**
  47376. * Uploads the updated texture data to the GPU.
  47377. *
  47378. * @param {Texture} texture - The texture.
  47379. * @param {Object} [options={}] - Optional configuration parameter.
  47380. */
  47381. updateTexture( texture, options ) {
  47382. this.textureUtils.updateTexture( texture, options );
  47383. }
  47384. /**
  47385. * Generates mipmaps for the given texture.
  47386. *
  47387. * @param {Texture} texture - The texture.
  47388. */
  47389. generateMipmaps( texture ) {
  47390. this.textureUtils.generateMipmaps( texture );
  47391. }
  47392. /**
  47393. * Destroys the GPU data for the given texture object.
  47394. *
  47395. * @param {Texture} texture - The texture.
  47396. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  47397. */
  47398. destroyTexture( texture, isDefaultTexture = false ) {
  47399. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  47400. }
  47401. /**
  47402. * Returns texture data as a typed array.
  47403. *
  47404. * @async
  47405. * @param {Texture} texture - The texture to copy.
  47406. * @param {number} x - The x coordinate of the copy origin.
  47407. * @param {number} y - The y coordinate of the copy origin.
  47408. * @param {number} width - The width of the copy.
  47409. * @param {number} height - The height of the copy.
  47410. * @param {number} faceIndex - The face index.
  47411. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47412. */
  47413. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47414. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47415. }
  47416. /**
  47417. * This method does nothing since WebGL 2 has no concept of samplers.
  47418. *
  47419. * @param {Texture} texture - The texture to update the sampler for.
  47420. * @return {string} The current sampler key.
  47421. */
  47422. updateSampler( /*texture*/ ) {
  47423. return '';
  47424. }
  47425. // node builder
  47426. /**
  47427. * Returns a node builder for the given render object.
  47428. *
  47429. * @param {RenderObject} object - The render object.
  47430. * @param {Renderer} renderer - The renderer.
  47431. * @return {GLSLNodeBuilder} The node builder.
  47432. */
  47433. createNodeBuilder( object, renderer ) {
  47434. return new GLSLNodeBuilder( object, renderer );
  47435. }
  47436. // program
  47437. /**
  47438. * Creates a shader program from the given programmable stage.
  47439. *
  47440. * @param {ProgrammableStage} program - The programmable stage.
  47441. */
  47442. createProgram( program ) {
  47443. const gl = this.gl;
  47444. const { stage, code } = program;
  47445. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  47446. gl.shaderSource( shader, code );
  47447. gl.compileShader( shader );
  47448. this.set( program, {
  47449. shaderGPU: shader
  47450. } );
  47451. }
  47452. /**
  47453. * Destroys the shader program of the given programmable stage.
  47454. *
  47455. * @param {ProgrammableStage} program - The programmable stage.
  47456. */
  47457. destroyProgram( program ) {
  47458. this.delete( program );
  47459. }
  47460. /**
  47461. * Creates a render pipeline for the given render object.
  47462. *
  47463. * @param {RenderObject} renderObject - The render object.
  47464. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47465. */
  47466. createRenderPipeline( renderObject, promises ) {
  47467. const gl = this.gl;
  47468. const pipeline = renderObject.pipeline;
  47469. // Program
  47470. const { fragmentProgram, vertexProgram } = pipeline;
  47471. const programGPU = gl.createProgram();
  47472. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  47473. const vertexShader = this.get( vertexProgram ).shaderGPU;
  47474. gl.attachShader( programGPU, fragmentShader );
  47475. gl.attachShader( programGPU, vertexShader );
  47476. gl.linkProgram( programGPU );
  47477. this.set( pipeline, {
  47478. programGPU,
  47479. fragmentShader,
  47480. vertexShader
  47481. } );
  47482. if ( promises !== null && this.parallel ) {
  47483. const p = new Promise( ( resolve /*, reject*/ ) => {
  47484. const parallel = this.parallel;
  47485. const checkStatus = () => {
  47486. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  47487. this._completeCompile( renderObject, pipeline );
  47488. resolve();
  47489. } else {
  47490. requestAnimationFrame( checkStatus );
  47491. }
  47492. };
  47493. checkStatus();
  47494. } );
  47495. promises.push( p );
  47496. return;
  47497. }
  47498. this._completeCompile( renderObject, pipeline );
  47499. }
  47500. /**
  47501. * Formats the source code of error messages.
  47502. *
  47503. * @private
  47504. * @param {string} string - The code.
  47505. * @param {number} errorLine - The error line.
  47506. * @return {string} The formatted code.
  47507. */
  47508. _handleSource( string, errorLine ) {
  47509. const lines = string.split( '\n' );
  47510. const lines2 = [];
  47511. const from = Math.max( errorLine - 6, 0 );
  47512. const to = Math.min( errorLine + 6, lines.length );
  47513. for ( let i = from; i < to; i ++ ) {
  47514. const line = i + 1;
  47515. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  47516. }
  47517. return lines2.join( '\n' );
  47518. }
  47519. /**
  47520. * Gets the shader compilation errors from the info log.
  47521. *
  47522. * @private
  47523. * @param {WebGL2RenderingContext} gl - The rendering context.
  47524. * @param {WebGLShader} shader - The WebGL shader object.
  47525. * @param {string} type - The shader type.
  47526. * @return {string} The shader errors.
  47527. */
  47528. _getShaderErrors( gl, shader, type ) {
  47529. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  47530. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  47531. const errors = shaderInfoLog.trim();
  47532. if ( status && errors === '' ) return '';
  47533. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  47534. if ( errorMatches ) {
  47535. const errorLine = parseInt( errorMatches[ 1 ] );
  47536. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  47537. } else {
  47538. return errors;
  47539. }
  47540. }
  47541. /**
  47542. * Logs shader compilation errors.
  47543. *
  47544. * @private
  47545. * @param {WebGLProgram} programGPU - The WebGL program.
  47546. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  47547. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  47548. */
  47549. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  47550. if ( this.renderer.debug.checkShaderErrors ) {
  47551. const gl = this.gl;
  47552. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  47553. const programLog = programInfoLog.trim();
  47554. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47555. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  47556. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  47557. } else {
  47558. // default error reporting
  47559. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  47560. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  47561. error(
  47562. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47563. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  47564. 'Program Info Log: ' + programLog + '\n' +
  47565. vertexErrors + '\n' +
  47566. fragmentErrors
  47567. );
  47568. }
  47569. } else if ( programLog !== '' ) {
  47570. warn( 'WebGLProgram: Program Info Log:', programLog );
  47571. }
  47572. }
  47573. }
  47574. /**
  47575. * Completes the shader program setup for the given render object.
  47576. *
  47577. * @private
  47578. * @param {RenderObject} renderObject - The render object.
  47579. * @param {RenderPipeline} pipeline - The render pipeline.
  47580. */
  47581. _completeCompile( renderObject, pipeline ) {
  47582. const { state, gl } = this;
  47583. const pipelineData = this.get( pipeline );
  47584. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  47585. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47586. this._logProgramError( programGPU, fragmentShader, vertexShader );
  47587. }
  47588. state.useProgram( programGPU );
  47589. // Bindings
  47590. const bindings = renderObject.getBindings();
  47591. this._setupBindings( bindings, programGPU );
  47592. //
  47593. this.set( pipeline, {
  47594. programGPU
  47595. } );
  47596. }
  47597. /**
  47598. * Creates a compute pipeline for the given compute node.
  47599. *
  47600. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47601. * @param {Array<BindGroup>} bindings - The bindings.
  47602. */
  47603. createComputePipeline( computePipeline, bindings ) {
  47604. const { state, gl } = this;
  47605. // Program
  47606. const fragmentProgram = {
  47607. stage: 'fragment',
  47608. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  47609. };
  47610. this.createProgram( fragmentProgram );
  47611. const { computeProgram } = computePipeline;
  47612. const programGPU = gl.createProgram();
  47613. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  47614. const vertexShader = this.get( computeProgram ).shaderGPU;
  47615. const transforms = computeProgram.transforms;
  47616. const transformVaryingNames = [];
  47617. const transformAttributeNodes = [];
  47618. for ( let i = 0; i < transforms.length; i ++ ) {
  47619. const transform = transforms[ i ];
  47620. transformVaryingNames.push( transform.varyingName );
  47621. transformAttributeNodes.push( transform.attributeNode );
  47622. }
  47623. gl.attachShader( programGPU, fragmentShader );
  47624. gl.attachShader( programGPU, vertexShader );
  47625. gl.transformFeedbackVaryings(
  47626. programGPU,
  47627. transformVaryingNames,
  47628. gl.SEPARATE_ATTRIBS
  47629. );
  47630. gl.linkProgram( programGPU );
  47631. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  47632. this._logProgramError( programGPU, fragmentShader, vertexShader );
  47633. }
  47634. state.useProgram( programGPU );
  47635. // Bindings
  47636. this._setupBindings( bindings, programGPU );
  47637. const attributeNodes = computeProgram.attributes;
  47638. const attributes = [];
  47639. const transformBuffers = [];
  47640. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  47641. const attribute = attributeNodes[ i ].node.attribute;
  47642. attributes.push( attribute );
  47643. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47644. }
  47645. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  47646. const attribute = transformAttributeNodes[ i ].attribute;
  47647. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47648. const attributeData = this.get( attribute );
  47649. transformBuffers.push( attributeData );
  47650. }
  47651. //
  47652. this.set( computePipeline, {
  47653. programGPU,
  47654. transformBuffers,
  47655. attributes
  47656. } );
  47657. }
  47658. /**
  47659. * Creates bindings from the given bind group definition.
  47660. *
  47661. * @param {BindGroup} bindGroup - The bind group.
  47662. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47663. * @param {number} cacheIndex - The cache index.
  47664. * @param {number} version - The version.
  47665. */
  47666. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  47667. if ( this._knownBindings.has( bindings ) === false ) {
  47668. this._knownBindings.add( bindings );
  47669. let uniformBuffers = 0;
  47670. let textures = 0;
  47671. for ( const bindGroup of bindings ) {
  47672. this.set( bindGroup, {
  47673. textures: textures,
  47674. uniformBuffers: uniformBuffers
  47675. } );
  47676. for ( const binding of bindGroup.bindings ) {
  47677. if ( binding.isUniformBuffer ) uniformBuffers ++;
  47678. if ( binding.isSampledTexture ) textures ++;
  47679. }
  47680. }
  47681. }
  47682. this.updateBindings( bindGroup, bindings );
  47683. }
  47684. /**
  47685. * Updates the given bind group definition.
  47686. *
  47687. * @param {BindGroup} bindGroup - The bind group.
  47688. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47689. * @param {number} cacheIndex - The cache index.
  47690. * @param {number} version - The version.
  47691. */
  47692. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  47693. const { gl } = this;
  47694. const bindGroupData = this.get( bindGroup );
  47695. let i = bindGroupData.uniformBuffers;
  47696. let t = bindGroupData.textures;
  47697. for ( const binding of bindGroup.bindings ) {
  47698. const map = this.get( binding );
  47699. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47700. const data = binding.buffer;
  47701. let { bufferGPU } = this.get( data );
  47702. if ( bufferGPU === undefined ) {
  47703. // create
  47704. bufferGPU = gl.createBuffer();
  47705. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47706. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  47707. this.set( data, { bufferGPU } );
  47708. } else {
  47709. // update
  47710. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47711. gl.bufferSubData( gl.UNIFORM_BUFFER, 0, data );
  47712. }
  47713. map.index = i ++;
  47714. map.bufferGPU = bufferGPU;
  47715. this.set( binding, map );
  47716. } else if ( binding.isSampledTexture ) {
  47717. const { textureGPU, glTextureType } = this.get( binding.texture );
  47718. map.index = t ++;
  47719. map.textureGPU = textureGPU;
  47720. map.glTextureType = glTextureType;
  47721. this.set( binding, map );
  47722. }
  47723. }
  47724. }
  47725. /**
  47726. * Updates a buffer binding.
  47727. *
  47728. * @param {Buffer} binding - The buffer binding to update.
  47729. */
  47730. updateBinding( binding ) {
  47731. const gl = this.gl;
  47732. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47733. const bindingData = this.get( binding );
  47734. const bufferGPU = bindingData.bufferGPU;
  47735. const data = binding.buffer;
  47736. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  47737. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  47738. }
  47739. }
  47740. // attributes
  47741. /**
  47742. * Creates the GPU buffer of an indexed shader attribute.
  47743. *
  47744. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  47745. */
  47746. createIndexAttribute( attribute ) {
  47747. const gl = this.gl;
  47748. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  47749. }
  47750. /**
  47751. * Creates the GPU buffer of a shader attribute.
  47752. *
  47753. * @param {BufferAttribute} attribute - The buffer attribute.
  47754. */
  47755. createAttribute( attribute ) {
  47756. if ( this.has( attribute ) ) return;
  47757. const gl = this.gl;
  47758. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47759. }
  47760. /**
  47761. * Creates the GPU buffer of a storage attribute.
  47762. *
  47763. * @param {BufferAttribute} attribute - The buffer attribute.
  47764. */
  47765. createStorageAttribute( attribute ) {
  47766. if ( this.has( attribute ) ) return;
  47767. const gl = this.gl;
  47768. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  47769. }
  47770. /**
  47771. * Updates the GPU buffer of a shader attribute.
  47772. *
  47773. * @param {BufferAttribute} attribute - The buffer attribute to update.
  47774. */
  47775. updateAttribute( attribute ) {
  47776. this.attributeUtils.updateAttribute( attribute );
  47777. }
  47778. /**
  47779. * Destroys the GPU buffer of a shader attribute.
  47780. *
  47781. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  47782. */
  47783. destroyAttribute( attribute ) {
  47784. this.attributeUtils.destroyAttribute( attribute );
  47785. }
  47786. /**
  47787. * Checks if the given feature is supported by the backend.
  47788. *
  47789. * @param {string} name - The feature's name.
  47790. * @return {boolean} Whether the feature is supported or not.
  47791. */
  47792. hasFeature( name ) {
  47793. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  47794. const extensions = this.extensions;
  47795. for ( let i = 0; i < keysMatching.length; i ++ ) {
  47796. if ( extensions.has( keysMatching[ i ] ) ) return true;
  47797. }
  47798. return false;
  47799. }
  47800. /**
  47801. * Returns the maximum anisotropy texture filtering value.
  47802. *
  47803. * @return {number} The maximum anisotropy texture filtering value.
  47804. */
  47805. getMaxAnisotropy() {
  47806. return this.capabilities.getMaxAnisotropy();
  47807. }
  47808. /**
  47809. * Copies data of the given source texture to the given destination texture.
  47810. *
  47811. * @param {Texture} srcTexture - The source texture.
  47812. * @param {Texture} dstTexture - The destination texture.
  47813. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  47814. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  47815. * @param {number} [srcLevel=0] - The source mip level to copy from.
  47816. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47817. */
  47818. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  47819. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  47820. }
  47821. /**
  47822. * Copies the current bound framebuffer to the given texture.
  47823. *
  47824. * @param {Texture} texture - The destination texture.
  47825. * @param {RenderContext} renderContext - The render context.
  47826. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47827. */
  47828. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47829. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  47830. }
  47831. /**
  47832. * Configures the active framebuffer from the given render context.
  47833. *
  47834. * @private
  47835. * @param {RenderContext} descriptor - The render context.
  47836. */
  47837. _setFramebuffer( descriptor ) {
  47838. const { gl, state } = this;
  47839. let currentFrameBuffer = null;
  47840. if ( descriptor.textures !== null ) {
  47841. const renderTarget = descriptor.renderTarget;
  47842. const renderTargetContextData = this.get( renderTarget );
  47843. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  47844. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  47845. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  47846. const isRenderTargetArray = renderTarget.depth > 1;
  47847. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  47848. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  47849. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  47850. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  47851. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47852. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  47853. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  47854. const cacheKey = getCacheKey( descriptor );
  47855. let fb;
  47856. if ( isCube ) {
  47857. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  47858. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  47859. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  47860. fb = this._xrFramebuffer;
  47861. } else {
  47862. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  47863. fb = renderTargetContextData.framebuffers[ cacheKey ];
  47864. }
  47865. if ( fb === undefined ) {
  47866. fb = gl.createFramebuffer();
  47867. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  47868. const textures = descriptor.textures;
  47869. const depthInvalidationArray = [];
  47870. if ( isCube ) {
  47871. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  47872. const { textureGPU } = this.get( textures[ 0 ] );
  47873. const cubeFace = this.renderer._activeCubeFace;
  47874. const mipLevel = this.renderer._activeMipmapLevel;
  47875. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  47876. } else {
  47877. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  47878. for ( let i = 0; i < textures.length; i ++ ) {
  47879. const texture = textures[ i ];
  47880. const textureData = this.get( texture );
  47881. textureData.renderTarget = descriptor.renderTarget;
  47882. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  47883. const attachment = gl.COLOR_ATTACHMENT0 + i;
  47884. if ( renderTarget.multiview ) {
  47885. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  47886. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  47887. const layer = this.renderer._activeCubeFace;
  47888. const mipLevel = this.renderer._activeMipmapLevel;
  47889. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  47890. } else {
  47891. if ( useMultisampledRTT ) {
  47892. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  47893. } else {
  47894. const mipLevel = this.renderer._activeMipmapLevel;
  47895. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  47896. }
  47897. }
  47898. }
  47899. }
  47900. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  47901. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  47902. const renderbuffer = gl.createRenderbuffer();
  47903. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  47904. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  47905. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  47906. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47907. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  47908. } else {
  47909. if ( descriptor.depthTexture !== null ) {
  47910. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  47911. const textureData = this.get( descriptor.depthTexture );
  47912. textureData.renderTarget = descriptor.renderTarget;
  47913. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  47914. if ( renderTarget.multiview ) {
  47915. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  47916. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  47917. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  47918. } else {
  47919. if ( descriptor.depthTexture.isArrayTexture ) {
  47920. const layer = this.renderer._activeCubeFace;
  47921. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  47922. } else {
  47923. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  47924. }
  47925. }
  47926. }
  47927. }
  47928. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  47929. } else {
  47930. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  47931. if ( isRenderCameraDepthArray ) {
  47932. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  47933. const layer = this.renderer._activeCubeFace;
  47934. const depthData = this.get( descriptor.depthTexture );
  47935. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  47936. gl.framebufferTextureLayer(
  47937. gl.FRAMEBUFFER,
  47938. depthStyle,
  47939. depthData.textureGPU,
  47940. 0,
  47941. layer
  47942. );
  47943. }
  47944. // rebind external XR textures
  47945. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  47946. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  47947. // rebind color
  47948. const textureData = this.get( descriptor.textures[ 0 ] );
  47949. if ( renderTarget.multiview ) {
  47950. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  47951. } else if ( useMultisampledRTT ) {
  47952. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  47953. } else {
  47954. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  47955. }
  47956. // rebind depth
  47957. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  47958. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  47959. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  47960. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47961. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  47962. } else {
  47963. const textureData = this.get( descriptor.depthTexture );
  47964. if ( renderTarget.multiview ) {
  47965. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  47966. } else if ( useMultisampledRTT ) {
  47967. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  47968. } else {
  47969. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  47970. }
  47971. }
  47972. }
  47973. }
  47974. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  47975. if ( msaaFb === undefined ) {
  47976. const invalidationArray = [];
  47977. msaaFb = gl.createFramebuffer();
  47978. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  47979. const msaaRenderbuffers = [];
  47980. const textures = descriptor.textures;
  47981. for ( let i = 0; i < textures.length; i ++ ) {
  47982. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  47983. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47984. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  47985. const texture = descriptor.textures[ i ];
  47986. const textureData = this.get( texture );
  47987. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  47988. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47989. }
  47990. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  47991. renderTargetContextData.msaaFrameBuffer = msaaFb;
  47992. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  47993. if ( depthBuffer && depthRenderbuffer === undefined ) {
  47994. depthRenderbuffer = gl.createRenderbuffer();
  47995. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  47996. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  47997. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  47998. invalidationArray.push( depthStyle );
  47999. }
  48000. renderTargetContextData.invalidationArray = invalidationArray;
  48001. }
  48002. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48003. } else {
  48004. currentFrameBuffer = fb;
  48005. }
  48006. state.drawBuffers( descriptor, fb );
  48007. }
  48008. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  48009. }
  48010. /**
  48011. * Computes the VAO key for the given index and attributes.
  48012. *
  48013. * @private
  48014. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48015. * @return {string} The VAO key.
  48016. */
  48017. _getVaoKey( attributes ) {
  48018. let key = '';
  48019. for ( let i = 0; i < attributes.length; i ++ ) {
  48020. const attributeData = this.get( attributes[ i ] );
  48021. key += ':' + attributeData.id;
  48022. }
  48023. return key;
  48024. }
  48025. /**
  48026. * Creates a VAO from the index and attributes.
  48027. *
  48028. * @private
  48029. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  48030. * @return {Object} The VAO data.
  48031. */
  48032. _createVao( attributes ) {
  48033. const { gl } = this;
  48034. const vaoGPU = gl.createVertexArray();
  48035. gl.bindVertexArray( vaoGPU );
  48036. for ( let i = 0; i < attributes.length; i ++ ) {
  48037. const attribute = attributes[ i ];
  48038. const attributeData = this.get( attribute );
  48039. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  48040. gl.enableVertexAttribArray( i );
  48041. let stride, offset;
  48042. if ( attribute.isInterleavedBufferAttribute === true ) {
  48043. stride = attribute.data.stride * attributeData.bytesPerElement;
  48044. offset = attribute.offset * attributeData.bytesPerElement;
  48045. } else {
  48046. stride = 0;
  48047. offset = 0;
  48048. }
  48049. if ( attributeData.isInteger ) {
  48050. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  48051. } else {
  48052. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  48053. }
  48054. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  48055. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  48056. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  48057. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  48058. }
  48059. }
  48060. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  48061. return vaoGPU;
  48062. }
  48063. /**
  48064. * Creates a transform feedback from the given transform buffers.
  48065. *
  48066. * @private
  48067. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  48068. * @return {WebGLTransformFeedback} The transform feedback.
  48069. */
  48070. _getTransformFeedback( transformBuffers ) {
  48071. let key = '';
  48072. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48073. key += ':' + transformBuffers[ i ].id;
  48074. }
  48075. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  48076. if ( transformFeedbackGPU !== undefined ) {
  48077. return transformFeedbackGPU;
  48078. }
  48079. const { gl } = this;
  48080. transformFeedbackGPU = gl.createTransformFeedback();
  48081. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  48082. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  48083. const attributeData = transformBuffers[ i ];
  48084. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  48085. }
  48086. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  48087. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  48088. return transformFeedbackGPU;
  48089. }
  48090. /**
  48091. * Setups the given bindings.
  48092. *
  48093. * @private
  48094. * @param {Array<BindGroup>} bindings - The bindings.
  48095. * @param {WebGLProgram} programGPU - The WebGL program.
  48096. */
  48097. _setupBindings( bindings, programGPU ) {
  48098. const gl = this.gl;
  48099. for ( const bindGroup of bindings ) {
  48100. for ( const binding of bindGroup.bindings ) {
  48101. const bindingData = this.get( binding );
  48102. const index = bindingData.index;
  48103. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48104. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  48105. gl.uniformBlockBinding( programGPU, location, index );
  48106. } else if ( binding.isSampledTexture ) {
  48107. const location = gl.getUniformLocation( programGPU, binding.name );
  48108. gl.uniform1i( location, index );
  48109. }
  48110. }
  48111. }
  48112. }
  48113. /**
  48114. * Binds the given uniforms.
  48115. *
  48116. * @private
  48117. * @param {Array<BindGroup>} bindings - The bindings.
  48118. */
  48119. _bindUniforms( bindings ) {
  48120. const { gl, state } = this;
  48121. for ( const bindGroup of bindings ) {
  48122. for ( const binding of bindGroup.bindings ) {
  48123. const bindingData = this.get( binding );
  48124. const index = bindingData.index;
  48125. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  48126. // TODO USE bindBufferRange to group multiple uniform buffers
  48127. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  48128. } else if ( binding.isSampledTexture ) {
  48129. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  48130. }
  48131. }
  48132. }
  48133. }
  48134. /**
  48135. * The method ensures multisampled render targets are resolved.
  48136. *
  48137. * @private
  48138. * @param {RenderContext} renderContext - The render context.
  48139. */
  48140. _resolveRenderTarget( renderContext ) {
  48141. const { gl, state } = this;
  48142. const renderTarget = renderContext.renderTarget;
  48143. if ( renderContext.textures !== null && renderTarget ) {
  48144. const renderTargetContextData = this.get( renderTarget );
  48145. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  48146. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48147. let mask = gl.COLOR_BUFFER_BIT;
  48148. if ( renderTarget.resolveDepthBuffer ) {
  48149. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  48150. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  48151. }
  48152. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  48153. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  48154. const textures = renderContext.textures;
  48155. const isMRT = textures.length > 1;
  48156. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  48157. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48158. if ( isMRT ) {
  48159. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  48160. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  48161. for ( let i = 0; i < textures.length; i ++ ) {
  48162. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  48163. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  48164. }
  48165. }
  48166. for ( let i = 0; i < textures.length; i ++ ) {
  48167. if ( isMRT ) {
  48168. // configure attachment for resolve
  48169. const { textureGPU } = this.get( textures[ i ] );
  48170. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48171. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  48172. }
  48173. if ( renderContext.scissor ) {
  48174. const { x, y, width, height } = renderContext.scissorValue;
  48175. const viewY = renderContext.height - height - y;
  48176. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  48177. } else {
  48178. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  48179. }
  48180. }
  48181. if ( isMRT ) {
  48182. // restore attachments
  48183. for ( let i = 0; i < textures.length; i ++ ) {
  48184. const { textureGPU } = this.get( textures[ i ] );
  48185. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  48186. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  48187. }
  48188. }
  48189. if ( this._supportsInvalidateFramebuffer === true ) {
  48190. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  48191. }
  48192. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  48193. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  48194. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  48195. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  48196. }
  48197. }
  48198. }
  48199. /**
  48200. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  48201. * should be used when MSAA is enabled.
  48202. *
  48203. * @private
  48204. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  48205. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  48206. */
  48207. _useMultisampledExtension( renderTarget ) {
  48208. if ( renderTarget.multiview === true ) {
  48209. return true;
  48210. }
  48211. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  48212. }
  48213. /**
  48214. * Frees internal resources.
  48215. */
  48216. dispose() {
  48217. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  48218. const extension = this.extensions.get( 'WEBGL_lose_context' );
  48219. if ( extension ) extension.loseContext();
  48220. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  48221. }
  48222. }
  48223. const GPUPrimitiveTopology = {
  48224. PointList: 'point-list',
  48225. LineList: 'line-list',
  48226. LineStrip: 'line-strip',
  48227. TriangleList: 'triangle-list',
  48228. TriangleStrip: 'triangle-strip',
  48229. };
  48230. const GPUCompareFunction = {
  48231. Never: 'never',
  48232. Less: 'less',
  48233. Equal: 'equal',
  48234. LessEqual: 'less-equal',
  48235. Greater: 'greater',
  48236. NotEqual: 'not-equal',
  48237. GreaterEqual: 'greater-equal',
  48238. Always: 'always'
  48239. };
  48240. const GPUStoreOp = {
  48241. Store: 'store'};
  48242. const GPULoadOp = {
  48243. Load: 'load',
  48244. Clear: 'clear'
  48245. };
  48246. const GPUFrontFace = {
  48247. CCW: 'ccw',
  48248. CW: 'cw'
  48249. };
  48250. const GPUCullMode = {
  48251. None: 'none',
  48252. Back: 'back'
  48253. };
  48254. const GPUIndexFormat = {
  48255. Uint16: 'uint16',
  48256. Uint32: 'uint32'
  48257. };
  48258. const GPUTextureFormat = {
  48259. // 8-bit formats
  48260. R8Unorm: 'r8unorm',
  48261. R8Snorm: 'r8snorm',
  48262. R8Uint: 'r8uint',
  48263. R8Sint: 'r8sint',
  48264. // 16-bit formats
  48265. R16Uint: 'r16uint',
  48266. R16Sint: 'r16sint',
  48267. R16Float: 'r16float',
  48268. RG8Unorm: 'rg8unorm',
  48269. RG8Snorm: 'rg8snorm',
  48270. RG8Uint: 'rg8uint',
  48271. RG8Sint: 'rg8sint',
  48272. // 32-bit formats
  48273. R32Uint: 'r32uint',
  48274. R32Sint: 'r32sint',
  48275. R32Float: 'r32float',
  48276. RG16Uint: 'rg16uint',
  48277. RG16Sint: 'rg16sint',
  48278. RG16Float: 'rg16float',
  48279. RGBA8Unorm: 'rgba8unorm',
  48280. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  48281. RGBA8Snorm: 'rgba8snorm',
  48282. RGBA8Uint: 'rgba8uint',
  48283. RGBA8Sint: 'rgba8sint',
  48284. BGRA8Unorm: 'bgra8unorm',
  48285. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  48286. // Packed 32-bit formats
  48287. RGB9E5UFloat: 'rgb9e5ufloat',
  48288. RGB10A2Unorm: 'rgb10a2unorm',
  48289. RG11B10UFloat: 'rg11b10ufloat',
  48290. // 64-bit formats
  48291. RG32Uint: 'rg32uint',
  48292. RG32Sint: 'rg32sint',
  48293. RG32Float: 'rg32float',
  48294. RGBA16Uint: 'rgba16uint',
  48295. RGBA16Sint: 'rgba16sint',
  48296. RGBA16Float: 'rgba16float',
  48297. // 128-bit formats
  48298. RGBA32Uint: 'rgba32uint',
  48299. RGBA32Sint: 'rgba32sint',
  48300. RGBA32Float: 'rgba32float',
  48301. Depth16Unorm: 'depth16unorm',
  48302. Depth24Plus: 'depth24plus',
  48303. Depth24PlusStencil8: 'depth24plus-stencil8',
  48304. Depth32Float: 'depth32float',
  48305. // 'depth32float-stencil8' extension
  48306. Depth32FloatStencil8: 'depth32float-stencil8',
  48307. // BC compressed formats usable if 'texture-compression-bc' is both
  48308. // supported by the device/user agent and enabled in requestDevice.
  48309. BC1RGBAUnorm: 'bc1-rgba-unorm',
  48310. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  48311. BC2RGBAUnorm: 'bc2-rgba-unorm',
  48312. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  48313. BC3RGBAUnorm: 'bc3-rgba-unorm',
  48314. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  48315. BC4RUnorm: 'bc4-r-unorm',
  48316. BC4RSnorm: 'bc4-r-snorm',
  48317. BC5RGUnorm: 'bc5-rg-unorm',
  48318. BC5RGSnorm: 'bc5-rg-snorm',
  48319. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  48320. BC6HRGBFloat: 'bc6h-rgb-float',
  48321. BC7RGBAUnorm: 'bc7-rgba-unorm',
  48322. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  48323. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  48324. // supported by the device/user agent and enabled in requestDevice.
  48325. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  48326. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  48327. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  48328. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  48329. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  48330. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  48331. EACR11Unorm: 'eac-r11unorm',
  48332. EACR11Snorm: 'eac-r11snorm',
  48333. EACRG11Unorm: 'eac-rg11unorm',
  48334. EACRG11Snorm: 'eac-rg11snorm',
  48335. // ASTC compressed formats usable if 'texture-compression-astc' is both
  48336. // supported by the device/user agent and enabled in requestDevice.
  48337. ASTC4x4Unorm: 'astc-4x4-unorm',
  48338. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  48339. ASTC5x4Unorm: 'astc-5x4-unorm',
  48340. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  48341. ASTC5x5Unorm: 'astc-5x5-unorm',
  48342. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  48343. ASTC6x5Unorm: 'astc-6x5-unorm',
  48344. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  48345. ASTC6x6Unorm: 'astc-6x6-unorm',
  48346. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  48347. ASTC8x5Unorm: 'astc-8x5-unorm',
  48348. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  48349. ASTC8x6Unorm: 'astc-8x6-unorm',
  48350. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  48351. ASTC8x8Unorm: 'astc-8x8-unorm',
  48352. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  48353. ASTC10x5Unorm: 'astc-10x5-unorm',
  48354. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  48355. ASTC10x6Unorm: 'astc-10x6-unorm',
  48356. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  48357. ASTC10x8Unorm: 'astc-10x8-unorm',
  48358. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  48359. ASTC10x10Unorm: 'astc-10x10-unorm',
  48360. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  48361. ASTC12x10Unorm: 'astc-12x10-unorm',
  48362. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  48363. ASTC12x12Unorm: 'astc-12x12-unorm',
  48364. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  48365. };
  48366. const GPUAddressMode = {
  48367. ClampToEdge: 'clamp-to-edge',
  48368. Repeat: 'repeat',
  48369. MirrorRepeat: 'mirror-repeat'
  48370. };
  48371. const GPUFilterMode = {
  48372. Linear: 'linear',
  48373. Nearest: 'nearest'
  48374. };
  48375. const GPUBlendFactor = {
  48376. Zero: 'zero',
  48377. One: 'one',
  48378. Src: 'src',
  48379. OneMinusSrc: 'one-minus-src',
  48380. SrcAlpha: 'src-alpha',
  48381. OneMinusSrcAlpha: 'one-minus-src-alpha',
  48382. Dst: 'dst',
  48383. OneMinusDst: 'one-minus-dst',
  48384. DstAlpha: 'dst-alpha',
  48385. OneMinusDstAlpha: 'one-minus-dst-alpha',
  48386. SrcAlphaSaturated: 'src-alpha-saturated',
  48387. Constant: 'constant',
  48388. OneMinusConstant: 'one-minus-constant'
  48389. };
  48390. const GPUBlendOperation = {
  48391. Add: 'add',
  48392. Subtract: 'subtract',
  48393. ReverseSubtract: 'reverse-subtract',
  48394. Min: 'min',
  48395. Max: 'max'
  48396. };
  48397. const GPUColorWriteFlags = {
  48398. None: 0,
  48399. All: 0xF
  48400. };
  48401. const GPUStencilOperation = {
  48402. Keep: 'keep',
  48403. Zero: 'zero',
  48404. Replace: 'replace',
  48405. Invert: 'invert',
  48406. IncrementClamp: 'increment-clamp',
  48407. DecrementClamp: 'decrement-clamp',
  48408. IncrementWrap: 'increment-wrap',
  48409. DecrementWrap: 'decrement-wrap'
  48410. };
  48411. const GPUBufferBindingType = {
  48412. Storage: 'storage',
  48413. ReadOnlyStorage: 'read-only-storage'
  48414. };
  48415. const GPUStorageTextureAccess = {
  48416. WriteOnly: 'write-only',
  48417. ReadOnly: 'read-only',
  48418. ReadWrite: 'read-write',
  48419. };
  48420. const GPUSamplerBindingType = {
  48421. NonFiltering: 'non-filtering',
  48422. Comparison: 'comparison'
  48423. };
  48424. const GPUTextureSampleType = {
  48425. Float: 'float',
  48426. UnfilterableFloat: 'unfilterable-float',
  48427. Depth: 'depth',
  48428. SInt: 'sint',
  48429. UInt: 'uint'
  48430. };
  48431. const GPUTextureDimension = {
  48432. TwoD: '2d',
  48433. ThreeD: '3d'
  48434. };
  48435. const GPUTextureViewDimension = {
  48436. TwoD: '2d',
  48437. TwoDArray: '2d-array',
  48438. Cube: 'cube',
  48439. ThreeD: '3d'
  48440. };
  48441. const GPUTextureAspect = {
  48442. All: 'all'};
  48443. const GPUInputStepMode = {
  48444. Vertex: 'vertex',
  48445. Instance: 'instance'
  48446. };
  48447. const GPUFeatureName = {
  48448. CoreFeaturesAndLimits: 'core-features-and-limits',
  48449. DepthClipControl: 'depth-clip-control',
  48450. Depth32FloatStencil8: 'depth32float-stencil8',
  48451. TextureCompressionBC: 'texture-compression-bc',
  48452. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  48453. TextureCompressionETC2: 'texture-compression-etc2',
  48454. TextureCompressionASTC: 'texture-compression-astc',
  48455. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  48456. TimestampQuery: 'timestamp-query',
  48457. IndirectFirstInstance: 'indirect-first-instance',
  48458. ShaderF16: 'shader-f16',
  48459. RG11B10UFloat: 'rg11b10ufloat-renderable',
  48460. BGRA8UNormStorage: 'bgra8unorm-storage',
  48461. Float32Filterable: 'float32-filterable',
  48462. Float32Blendable: 'float32-blendable',
  48463. ClipDistances: 'clip-distances',
  48464. DualSourceBlending: 'dual-source-blending',
  48465. Subgroups: 'subgroups',
  48466. TextureFormatsTier1: 'texture-formats-tier1',
  48467. TextureFormatsTier2: 'texture-formats-tier2'
  48468. };
  48469. /**
  48470. * A special form of sampler binding type.
  48471. * It's texture value is managed by a node object.
  48472. *
  48473. * @private
  48474. * @augments Sampler
  48475. */
  48476. class NodeSampler extends Sampler {
  48477. /**
  48478. * Constructs a new node-based sampler.
  48479. *
  48480. * @param {string} name - The samplers's name.
  48481. * @param {TextureNode} textureNode - The texture node.
  48482. * @param {UniformGroupNode} groupNode - The uniform group node.
  48483. */
  48484. constructor( name, textureNode, groupNode ) {
  48485. super( name, textureNode ? textureNode.value : null );
  48486. /**
  48487. * The texture node.
  48488. *
  48489. * @type {TextureNode}
  48490. */
  48491. this.textureNode = textureNode;
  48492. /**
  48493. * The uniform group node.
  48494. *
  48495. * @type {UniformGroupNode}
  48496. */
  48497. this.groupNode = groupNode;
  48498. }
  48499. /**
  48500. * Updates the texture value of this sampler.
  48501. *
  48502. * @return {boolean} Whether the sampler needs an update or not.
  48503. */
  48504. update() {
  48505. const { textureNode } = this;
  48506. if ( this.texture !== textureNode.value ) {
  48507. this.texture = textureNode.value;
  48508. return true;
  48509. }
  48510. return super.update();
  48511. }
  48512. }
  48513. /**
  48514. * Represents a storage buffer binding type.
  48515. *
  48516. * @private
  48517. * @augments Buffer
  48518. */
  48519. class StorageBuffer extends Buffer {
  48520. /**
  48521. * Constructs a new uniform buffer.
  48522. *
  48523. * @param {string} name - The buffer's name.
  48524. * @param {BufferAttribute} attribute - The buffer attribute.
  48525. */
  48526. constructor( name, attribute ) {
  48527. super( name, attribute ? attribute.array : null );
  48528. /**
  48529. * This flag can be used for type testing.
  48530. *
  48531. * @type {BufferAttribute}
  48532. */
  48533. this.attribute = attribute;
  48534. /**
  48535. * This flag can be used for type testing.
  48536. *
  48537. * @type {boolean}
  48538. * @readonly
  48539. * @default true
  48540. */
  48541. this.isStorageBuffer = true;
  48542. }
  48543. }
  48544. let _id = 0;
  48545. /**
  48546. * A special form of storage buffer binding type.
  48547. * It's buffer value is managed by a node object.
  48548. *
  48549. * @private
  48550. * @augments StorageBuffer
  48551. */
  48552. class NodeStorageBuffer extends StorageBuffer {
  48553. /**
  48554. * Constructs a new node-based storage buffer.
  48555. *
  48556. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  48557. * @param {UniformGroupNode} groupNode - The uniform group node.
  48558. */
  48559. constructor( nodeUniform, groupNode ) {
  48560. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  48561. /**
  48562. * The node uniform.
  48563. *
  48564. * @type {StorageBufferNode}
  48565. */
  48566. this.nodeUniform = nodeUniform;
  48567. /**
  48568. * The access type.
  48569. *
  48570. * @type {string}
  48571. */
  48572. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  48573. /**
  48574. * The uniform group node.
  48575. *
  48576. * @type {UniformGroupNode}
  48577. */
  48578. this.groupNode = groupNode;
  48579. }
  48580. /**
  48581. * The storage buffer.
  48582. *
  48583. * @type {BufferAttribute}
  48584. */
  48585. get buffer() {
  48586. return this.nodeUniform.value;
  48587. }
  48588. }
  48589. /**
  48590. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  48591. *
  48592. * @private
  48593. */
  48594. class WebGPUTexturePassUtils extends DataMap {
  48595. /**
  48596. * Constructs a new utility object.
  48597. *
  48598. * @param {GPUDevice} device - The WebGPU device.
  48599. */
  48600. constructor( device ) {
  48601. super();
  48602. /**
  48603. * The WebGPU device.
  48604. *
  48605. * @type {GPUDevice}
  48606. */
  48607. this.device = device;
  48608. const mipmapVertexSource = `
  48609. struct VarysStruct {
  48610. @builtin( position ) Position: vec4<f32>,
  48611. @location( 0 ) vTex : vec2<f32>
  48612. };
  48613. @vertex
  48614. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  48615. var Varys : VarysStruct;
  48616. var pos = array< vec2<f32>, 4 >(
  48617. vec2<f32>( -1.0, 1.0 ),
  48618. vec2<f32>( 1.0, 1.0 ),
  48619. vec2<f32>( -1.0, -1.0 ),
  48620. vec2<f32>( 1.0, -1.0 )
  48621. );
  48622. var tex = array< vec2<f32>, 4 >(
  48623. vec2<f32>( 0.0, 0.0 ),
  48624. vec2<f32>( 1.0, 0.0 ),
  48625. vec2<f32>( 0.0, 1.0 ),
  48626. vec2<f32>( 1.0, 1.0 )
  48627. );
  48628. Varys.vTex = tex[ vertexIndex ];
  48629. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  48630. return Varys;
  48631. }
  48632. `;
  48633. const mipmapFragmentSource = `
  48634. @group( 0 ) @binding( 0 )
  48635. var imgSampler : sampler;
  48636. @group( 0 ) @binding( 1 )
  48637. var img : texture_2d<f32>;
  48638. @fragment
  48639. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  48640. return textureSample( img, imgSampler, vTex );
  48641. }
  48642. `;
  48643. const flipYFragmentSource = `
  48644. @group( 0 ) @binding( 0 )
  48645. var imgSampler : sampler;
  48646. @group( 0 ) @binding( 1 )
  48647. var img : texture_2d<f32>;
  48648. @fragment
  48649. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  48650. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  48651. }
  48652. `;
  48653. /**
  48654. * The mipmap GPU sampler.
  48655. *
  48656. * @type {GPUSampler}
  48657. */
  48658. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  48659. /**
  48660. * The flipY GPU sampler.
  48661. *
  48662. * @type {GPUSampler}
  48663. */
  48664. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  48665. /**
  48666. * A cache for GPU render pipelines used for copy/transfer passes.
  48667. * Every texture format requires a unique pipeline.
  48668. *
  48669. * @type {Object<string,GPURenderPipeline>}
  48670. */
  48671. this.transferPipelines = {};
  48672. /**
  48673. * A cache for GPU render pipelines used for flipY passes.
  48674. * Every texture format requires a unique pipeline.
  48675. *
  48676. * @type {Object<string,GPURenderPipeline>}
  48677. */
  48678. this.flipYPipelines = {};
  48679. /**
  48680. * The mipmap vertex shader module.
  48681. *
  48682. * @type {GPUShaderModule}
  48683. */
  48684. this.mipmapVertexShaderModule = device.createShaderModule( {
  48685. label: 'mipmapVertex',
  48686. code: mipmapVertexSource
  48687. } );
  48688. /**
  48689. * The mipmap fragment shader module.
  48690. *
  48691. * @type {GPUShaderModule}
  48692. */
  48693. this.mipmapFragmentShaderModule = device.createShaderModule( {
  48694. label: 'mipmapFragment',
  48695. code: mipmapFragmentSource
  48696. } );
  48697. /**
  48698. * The flipY fragment shader module.
  48699. *
  48700. * @type {GPUShaderModule}
  48701. */
  48702. this.flipYFragmentShaderModule = device.createShaderModule( {
  48703. label: 'flipYFragment',
  48704. code: flipYFragmentSource
  48705. } );
  48706. }
  48707. /**
  48708. * Returns a render pipeline for the internal copy render pass. The pass
  48709. * requires a unique render pipeline for each texture format.
  48710. *
  48711. * @param {string} format - The GPU texture format
  48712. * @return {GPURenderPipeline} The GPU render pipeline.
  48713. */
  48714. getTransferPipeline( format ) {
  48715. let pipeline = this.transferPipelines[ format ];
  48716. if ( pipeline === undefined ) {
  48717. pipeline = this.device.createRenderPipeline( {
  48718. label: `mipmap-${ format }`,
  48719. vertex: {
  48720. module: this.mipmapVertexShaderModule,
  48721. entryPoint: 'main'
  48722. },
  48723. fragment: {
  48724. module: this.mipmapFragmentShaderModule,
  48725. entryPoint: 'main',
  48726. targets: [ { format } ]
  48727. },
  48728. primitive: {
  48729. topology: GPUPrimitiveTopology.TriangleStrip,
  48730. stripIndexFormat: GPUIndexFormat.Uint32
  48731. },
  48732. layout: 'auto'
  48733. } );
  48734. this.transferPipelines[ format ] = pipeline;
  48735. }
  48736. return pipeline;
  48737. }
  48738. /**
  48739. * Returns a render pipeline for the flipY render pass. The pass
  48740. * requires a unique render pipeline for each texture format.
  48741. *
  48742. * @param {string} format - The GPU texture format
  48743. * @return {GPURenderPipeline} The GPU render pipeline.
  48744. */
  48745. getFlipYPipeline( format ) {
  48746. let pipeline = this.flipYPipelines[ format ];
  48747. if ( pipeline === undefined ) {
  48748. pipeline = this.device.createRenderPipeline( {
  48749. label: `flipY-${ format }`,
  48750. vertex: {
  48751. module: this.mipmapVertexShaderModule,
  48752. entryPoint: 'main'
  48753. },
  48754. fragment: {
  48755. module: this.flipYFragmentShaderModule,
  48756. entryPoint: 'main',
  48757. targets: [ { format } ]
  48758. },
  48759. primitive: {
  48760. topology: GPUPrimitiveTopology.TriangleStrip,
  48761. stripIndexFormat: GPUIndexFormat.Uint32
  48762. },
  48763. layout: 'auto'
  48764. } );
  48765. this.flipYPipelines[ format ] = pipeline;
  48766. }
  48767. return pipeline;
  48768. }
  48769. /**
  48770. * Flip the contents of the given GPU texture along its vertical axis.
  48771. *
  48772. * @param {GPUTexture} textureGPU - The GPU texture object.
  48773. * @param {Object} textureGPUDescriptor - The texture descriptor.
  48774. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  48775. */
  48776. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  48777. const format = textureGPUDescriptor.format;
  48778. const { width, height } = textureGPUDescriptor.size;
  48779. const transferPipeline = this.getTransferPipeline( format );
  48780. const flipYPipeline = this.getFlipYPipeline( format );
  48781. const tempTexture = this.device.createTexture( {
  48782. size: { width, height, depthOrArrayLayers: 1 },
  48783. format,
  48784. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  48785. } );
  48786. const srcView = textureGPU.createView( {
  48787. baseMipLevel: 0,
  48788. mipLevelCount: 1,
  48789. dimension: GPUTextureViewDimension.TwoD,
  48790. baseArrayLayer
  48791. } );
  48792. const dstView = tempTexture.createView( {
  48793. baseMipLevel: 0,
  48794. mipLevelCount: 1,
  48795. dimension: GPUTextureViewDimension.TwoD,
  48796. baseArrayLayer: 0
  48797. } );
  48798. const commandEncoder = this.device.createCommandEncoder( {} );
  48799. const pass = ( pipeline, sourceView, destinationView ) => {
  48800. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  48801. const bindGroup = this.device.createBindGroup( {
  48802. layout: bindGroupLayout,
  48803. entries: [ {
  48804. binding: 0,
  48805. resource: this.flipYSampler
  48806. }, {
  48807. binding: 1,
  48808. resource: sourceView
  48809. } ]
  48810. } );
  48811. const passEncoder = commandEncoder.beginRenderPass( {
  48812. colorAttachments: [ {
  48813. view: destinationView,
  48814. loadOp: GPULoadOp.Clear,
  48815. storeOp: GPUStoreOp.Store,
  48816. clearValue: [ 0, 0, 0, 0 ]
  48817. } ]
  48818. } );
  48819. passEncoder.setPipeline( pipeline );
  48820. passEncoder.setBindGroup( 0, bindGroup );
  48821. passEncoder.draw( 4, 1, 0, 0 );
  48822. passEncoder.end();
  48823. };
  48824. pass( transferPipeline, srcView, dstView );
  48825. pass( flipYPipeline, dstView, srcView );
  48826. this.device.queue.submit( [ commandEncoder.finish() ] );
  48827. tempTexture.destroy();
  48828. }
  48829. /**
  48830. * Generates mipmaps for the given GPU texture.
  48831. *
  48832. * @param {GPUTexture} textureGPU - The GPU texture object.
  48833. * @param {Object} textureGPUDescriptor - The texture descriptor.
  48834. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  48835. */
  48836. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  48837. const textureData = this.get( textureGPU );
  48838. if ( textureData.useCount === undefined ) {
  48839. textureData.useCount = 0;
  48840. textureData.layers = [];
  48841. }
  48842. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  48843. const commandEncoder = this.device.createCommandEncoder( {} );
  48844. this._mipmapRunBundles( commandEncoder, passes );
  48845. this.device.queue.submit( [ commandEncoder.finish() ] );
  48846. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  48847. textureData.useCount ++;
  48848. }
  48849. /**
  48850. * Since multiple copy render passes are required to generate mipmaps, the passes
  48851. * are managed as render bundles to improve performance.
  48852. *
  48853. * @param {GPUTexture} textureGPU - The GPU texture object.
  48854. * @param {Object} textureGPUDescriptor - The texture descriptor.
  48855. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  48856. * @return {Array<Object>} An array of render bundles.
  48857. */
  48858. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  48859. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  48860. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  48861. let srcView = textureGPU.createView( {
  48862. baseMipLevel: 0,
  48863. mipLevelCount: 1,
  48864. dimension: GPUTextureViewDimension.TwoD,
  48865. baseArrayLayer
  48866. } );
  48867. const passes = [];
  48868. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  48869. const bindGroup = this.device.createBindGroup( {
  48870. layout: bindGroupLayout,
  48871. entries: [ {
  48872. binding: 0,
  48873. resource: this.mipmapSampler
  48874. }, {
  48875. binding: 1,
  48876. resource: srcView
  48877. } ]
  48878. } );
  48879. const dstView = textureGPU.createView( {
  48880. baseMipLevel: i,
  48881. mipLevelCount: 1,
  48882. dimension: GPUTextureViewDimension.TwoD,
  48883. baseArrayLayer
  48884. } );
  48885. const passDescriptor = {
  48886. colorAttachments: [ {
  48887. view: dstView,
  48888. loadOp: GPULoadOp.Clear,
  48889. storeOp: GPUStoreOp.Store,
  48890. clearValue: [ 0, 0, 0, 0 ]
  48891. } ]
  48892. };
  48893. const passEncoder = this.device.createRenderBundleEncoder( {
  48894. colorFormats: [ textureGPUDescriptor.format ]
  48895. } );
  48896. passEncoder.setPipeline( pipeline );
  48897. passEncoder.setBindGroup( 0, bindGroup );
  48898. passEncoder.draw( 4, 1, 0, 0 );
  48899. passes.push( {
  48900. renderBundles: [ passEncoder.finish() ],
  48901. passDescriptor
  48902. } );
  48903. srcView = dstView;
  48904. }
  48905. return passes;
  48906. }
  48907. /**
  48908. * Executes the render bundles.
  48909. *
  48910. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  48911. * @param {Array<Object>} passes - An array of render bundles.
  48912. */
  48913. _mipmapRunBundles( commandEncoder, passes ) {
  48914. const levels = passes.length;
  48915. for ( let i = 0; i < levels; i ++ ) {
  48916. const pass = passes[ i ];
  48917. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  48918. passEncoder.executeBundles( pass.renderBundles );
  48919. passEncoder.end();
  48920. }
  48921. }
  48922. }
  48923. const _compareToWebGPU = {
  48924. [ NeverCompare ]: 'never',
  48925. [ LessCompare ]: 'less',
  48926. [ EqualCompare ]: 'equal',
  48927. [ LessEqualCompare ]: 'less-equal',
  48928. [ GreaterCompare ]: 'greater',
  48929. [ GreaterEqualCompare ]: 'greater-equal',
  48930. [ AlwaysCompare ]: 'always',
  48931. [ NotEqualCompare ]: 'not-equal'
  48932. };
  48933. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  48934. /**
  48935. * A WebGPU backend utility module for managing textures.
  48936. *
  48937. * @private
  48938. */
  48939. class WebGPUTextureUtils {
  48940. /**
  48941. * Constructs a new utility object.
  48942. *
  48943. * @param {WebGPUBackend} backend - The WebGPU backend.
  48944. */
  48945. constructor( backend ) {
  48946. /**
  48947. * A reference to the WebGPU backend.
  48948. *
  48949. * @type {WebGPUBackend}
  48950. */
  48951. this.backend = backend;
  48952. /**
  48953. * A reference to the pass utils.
  48954. *
  48955. * @type {?WebGPUTexturePassUtils}
  48956. * @default null
  48957. */
  48958. this._passUtils = null;
  48959. /**
  48960. * A dictionary for managing default textures. The key
  48961. * is the texture format, the value the texture object.
  48962. *
  48963. * @type {Object<string,Texture>}
  48964. */
  48965. this.defaultTexture = {};
  48966. /**
  48967. * A dictionary for managing default cube textures. The key
  48968. * is the texture format, the value the texture object.
  48969. *
  48970. * @type {Object<string,CubeTexture>}
  48971. */
  48972. this.defaultCubeTexture = {};
  48973. /**
  48974. * A default video frame.
  48975. *
  48976. * @type {?VideoFrame}
  48977. * @default null
  48978. */
  48979. this.defaultVideoFrame = null;
  48980. /**
  48981. * A cache of shared texture samplers.
  48982. *
  48983. * @type {Map<string, Object>}
  48984. */
  48985. this._samplerCache = new Map();
  48986. }
  48987. /**
  48988. * Creates a GPU sampler for the given texture.
  48989. *
  48990. * @param {Texture} texture - The texture to create the sampler for.
  48991. * @return {string} The current sampler key.
  48992. */
  48993. updateSampler( texture ) {
  48994. const backend = this.backend;
  48995. const samplerKey = texture.minFilter + '-' + texture.magFilter + '-' +
  48996. texture.wrapS + '-' + texture.wrapT + '-' + ( texture.wrapR || '0' ) + '-' +
  48997. texture.anisotropy + '-' + ( texture.compareFunction || 0 );
  48998. let samplerData = this._samplerCache.get( samplerKey );
  48999. if ( samplerData === undefined ) {
  49000. const samplerDescriptorGPU = {
  49001. addressModeU: this._convertAddressMode( texture.wrapS ),
  49002. addressModeV: this._convertAddressMode( texture.wrapT ),
  49003. addressModeW: this._convertAddressMode( texture.wrapR ),
  49004. magFilter: this._convertFilterMode( texture.magFilter ),
  49005. minFilter: this._convertFilterMode( texture.minFilter ),
  49006. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  49007. maxAnisotropy: 1
  49008. };
  49009. // anisotropy can only be used when all filter modes are set to linear.
  49010. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  49011. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  49012. }
  49013. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  49014. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  49015. }
  49016. const sampler = backend.device.createSampler( samplerDescriptorGPU );
  49017. samplerData = { sampler, usedTimes: 0 };
  49018. this._samplerCache.set( samplerKey, samplerData );
  49019. }
  49020. const textureData = backend.get( texture );
  49021. if ( textureData.sampler !== samplerData.sampler ) {
  49022. // check if previous sampler is unused so it can be deleted
  49023. if ( textureData.sampler !== undefined ) {
  49024. const oldSamplerData = this._samplerCache.get( textureData.samplerKey );
  49025. oldSamplerData.usedTimes --;
  49026. if ( oldSamplerData.usedTimes === 0 ) {
  49027. this._samplerCache.delete( textureData.samplerKey );
  49028. }
  49029. }
  49030. // update to new sampler data
  49031. textureData.samplerKey = samplerKey;
  49032. textureData.sampler = samplerData.sampler;
  49033. samplerData.usedTimes ++;
  49034. }
  49035. return samplerKey;
  49036. }
  49037. /**
  49038. * Creates a default texture for the given texture that can be used
  49039. * as a placeholder until the actual texture is ready for usage.
  49040. *
  49041. * @param {Texture} texture - The texture to create a default texture for.
  49042. */
  49043. createDefaultTexture( texture ) {
  49044. let textureGPU;
  49045. const format = getFormat( texture );
  49046. if ( texture.isCubeTexture ) {
  49047. textureGPU = this._getDefaultCubeTextureGPU( format );
  49048. } else {
  49049. textureGPU = this._getDefaultTextureGPU( format );
  49050. }
  49051. this.backend.get( texture ).texture = textureGPU;
  49052. }
  49053. /**
  49054. * Defines a texture on the GPU for the given texture object.
  49055. *
  49056. * @param {Texture} texture - The texture.
  49057. * @param {Object} [options={}] - Optional configuration parameter.
  49058. */
  49059. createTexture( texture, options = {} ) {
  49060. const backend = this.backend;
  49061. const textureData = backend.get( texture );
  49062. if ( textureData.initialized ) {
  49063. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  49064. }
  49065. if ( texture.isExternalTexture ) {
  49066. textureData.texture = texture.sourceTexture;
  49067. textureData.initialized = true;
  49068. return;
  49069. }
  49070. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  49071. if ( options.levels === undefined ) options.levels = 1;
  49072. if ( options.depth === undefined ) options.depth = 1;
  49073. const { width, height, depth, levels } = options;
  49074. if ( texture.isFramebufferTexture ) {
  49075. if ( options.renderTarget ) {
  49076. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  49077. } else {
  49078. options.format = this.backend.utils.getPreferredCanvasFormat();
  49079. }
  49080. }
  49081. const dimension = this._getDimension( texture );
  49082. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  49083. textureData.format = format;
  49084. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  49085. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  49086. if ( texture.isStorageTexture === true ) {
  49087. usage |= GPUTextureUsage.STORAGE_BINDING;
  49088. }
  49089. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  49090. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  49091. }
  49092. const textureDescriptorGPU = {
  49093. label: texture.name,
  49094. size: {
  49095. width: width,
  49096. height: height,
  49097. depthOrArrayLayers: depth,
  49098. },
  49099. mipLevelCount: levels,
  49100. sampleCount: primarySamples,
  49101. dimension: dimension,
  49102. format: format,
  49103. usage: usage
  49104. };
  49105. // texture creation
  49106. if ( format === undefined ) {
  49107. warn( 'WebGPURenderer: Texture format not supported.' );
  49108. this.createDefaultTexture( texture );
  49109. return;
  49110. }
  49111. if ( texture.isCubeTexture ) {
  49112. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  49113. }
  49114. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  49115. if ( isMSAA ) {
  49116. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  49117. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  49118. msaaTextureDescriptorGPU.sampleCount = samples;
  49119. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  49120. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  49121. }
  49122. textureData.initialized = true;
  49123. textureData.textureDescriptorGPU = textureDescriptorGPU;
  49124. }
  49125. /**
  49126. * Destroys the GPU data for the given texture object.
  49127. *
  49128. * @param {Texture} texture - The texture.
  49129. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  49130. */
  49131. destroyTexture( texture, isDefaultTexture = false ) {
  49132. const backend = this.backend;
  49133. const textureData = backend.get( texture );
  49134. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  49135. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  49136. backend.delete( texture );
  49137. }
  49138. /**
  49139. * Generates mipmaps for the given texture.
  49140. *
  49141. * @param {Texture} texture - The texture.
  49142. */
  49143. generateMipmaps( texture ) {
  49144. const textureData = this.backend.get( texture );
  49145. if ( texture.isCubeTexture ) {
  49146. for ( let i = 0; i < 6; i ++ ) {
  49147. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  49148. }
  49149. } else {
  49150. const depth = texture.image.depth || 1;
  49151. for ( let i = 0; i < depth; i ++ ) {
  49152. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  49153. }
  49154. }
  49155. }
  49156. /**
  49157. * Returns the color buffer representing the color
  49158. * attachment of the default framebuffer.
  49159. *
  49160. * @return {GPUTexture} The color buffer.
  49161. */
  49162. getColorBuffer() {
  49163. const backend = this.backend;
  49164. const canvasTarget = backend.renderer.getCanvasTarget();
  49165. const { width, height } = backend.getDrawingBufferSize();
  49166. const samples = backend.renderer.currentSamples;
  49167. const colorTexture = canvasTarget.colorTexture;
  49168. const colorTextureData = backend.get( colorTexture );
  49169. if ( colorTexture.width === width && colorTexture.height === height && colorTexture.samples === samples ) {
  49170. return colorTextureData.texture;
  49171. }
  49172. // recreate
  49173. let colorBuffer = colorTextureData.texture;
  49174. if ( colorBuffer ) colorBuffer.destroy();
  49175. colorBuffer = backend.device.createTexture( {
  49176. label: 'colorBuffer',
  49177. size: {
  49178. width: width,
  49179. height: height,
  49180. depthOrArrayLayers: 1
  49181. },
  49182. sampleCount: backend.utils.getSampleCount( backend.renderer.currentSamples ),
  49183. format: backend.utils.getPreferredCanvasFormat(),
  49184. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  49185. } );
  49186. //
  49187. colorTexture.source.width = width;
  49188. colorTexture.source.height = height;
  49189. colorTexture.samples = samples;
  49190. colorTextureData.texture = colorBuffer;
  49191. return colorBuffer;
  49192. }
  49193. /**
  49194. * Returns the depth buffer representing the depth
  49195. * attachment of the default framebuffer.
  49196. *
  49197. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  49198. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  49199. * @return {GPUTexture} The depth buffer.
  49200. */
  49201. getDepthBuffer( depth = true, stencil = false ) {
  49202. const backend = this.backend;
  49203. const canvasTarget = backend.renderer.getCanvasTarget();
  49204. const { width, height } = backend.getDrawingBufferSize();
  49205. const samples = backend.renderer.currentSamples;
  49206. const depthTexture = canvasTarget.depthTexture;
  49207. if ( depthTexture.width === width &&
  49208. depthTexture.height === height &&
  49209. depthTexture.samples === samples &&
  49210. depthTexture.depth === depth &&
  49211. depthTexture.stencil === stencil ) {
  49212. return backend.get( depthTexture ).texture;
  49213. }
  49214. //
  49215. const depthTextureGPU = backend.get( depthTexture ).texture;
  49216. let format, type;
  49217. if ( stencil ) {
  49218. format = DepthStencilFormat;
  49219. type = UnsignedInt248Type;
  49220. } else if ( depth ) {
  49221. format = DepthFormat;
  49222. type = UnsignedIntType;
  49223. }
  49224. if ( depthTextureGPU !== undefined ) {
  49225. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type && depthTexture.samples === samples ) {
  49226. return depthTextureGPU;
  49227. }
  49228. this.destroyTexture( depthTexture );
  49229. }
  49230. // recreate
  49231. depthTexture.name = 'depthBuffer';
  49232. depthTexture.format = format;
  49233. depthTexture.type = type;
  49234. depthTexture.image.width = width;
  49235. depthTexture.image.height = height;
  49236. depthTexture.samples = samples;
  49237. this.createTexture( depthTexture, { width, height } );
  49238. return backend.get( depthTexture ).texture;
  49239. }
  49240. /**
  49241. * Uploads the updated texture data to the GPU.
  49242. *
  49243. * @param {Texture} texture - The texture.
  49244. * @param {Object} [options={}] - Optional configuration parameter.
  49245. */
  49246. updateTexture( texture, options ) {
  49247. const textureData = this.backend.get( texture );
  49248. const mipmaps = texture.mipmaps;
  49249. const { textureDescriptorGPU } = textureData;
  49250. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  49251. return;
  49252. // transfer texture data
  49253. if ( texture.isDataTexture ) {
  49254. if ( mipmaps.length > 0 ) {
  49255. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49256. const mipmap = mipmaps[ i ];
  49257. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  49258. }
  49259. } else {
  49260. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  49261. }
  49262. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  49263. for ( let i = 0; i < options.image.depth; i ++ ) {
  49264. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  49265. }
  49266. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  49267. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  49268. } else if ( texture.isCubeTexture ) {
  49269. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  49270. } else {
  49271. if ( mipmaps.length > 0 ) {
  49272. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49273. const mipmap = mipmaps[ i ];
  49274. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  49275. }
  49276. } else {
  49277. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  49278. }
  49279. }
  49280. //
  49281. textureData.version = texture.version;
  49282. }
  49283. /**
  49284. * Returns texture data as a typed array.
  49285. *
  49286. * @async
  49287. * @param {Texture} texture - The texture to copy.
  49288. * @param {number} x - The x coordinate of the copy origin.
  49289. * @param {number} y - The y coordinate of the copy origin.
  49290. * @param {number} width - The width of the copy.
  49291. * @param {number} height - The height of the copy.
  49292. * @param {number} faceIndex - The face index.
  49293. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49294. */
  49295. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49296. const device = this.backend.device;
  49297. const textureData = this.backend.get( texture );
  49298. const textureGPU = textureData.texture;
  49299. const format = textureData.textureDescriptorGPU.format;
  49300. const bytesPerTexel = this._getBytesPerTexel( format );
  49301. let bytesPerRow = width * bytesPerTexel;
  49302. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  49303. const readBuffer = device.createBuffer(
  49304. {
  49305. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  49306. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49307. }
  49308. );
  49309. const encoder = device.createCommandEncoder();
  49310. encoder.copyTextureToBuffer(
  49311. {
  49312. texture: textureGPU,
  49313. origin: { x, y, z: faceIndex },
  49314. },
  49315. {
  49316. buffer: readBuffer,
  49317. bytesPerRow: bytesPerRow
  49318. },
  49319. {
  49320. width: width,
  49321. height: height
  49322. }
  49323. );
  49324. const typedArrayType = this._getTypedArrayType( format );
  49325. device.queue.submit( [ encoder.finish() ] );
  49326. await readBuffer.mapAsync( GPUMapMode.READ );
  49327. const buffer = readBuffer.getMappedRange();
  49328. return new typedArrayType( buffer );
  49329. }
  49330. /**
  49331. * Frees all internal resources.
  49332. */
  49333. dispose() {
  49334. this._samplerCache.clear();
  49335. }
  49336. /**
  49337. * Returns the default GPU texture for the given format.
  49338. *
  49339. * @private
  49340. * @param {string} format - The GPU format.
  49341. * @return {GPUTexture} The GPU texture.
  49342. */
  49343. _getDefaultTextureGPU( format ) {
  49344. let defaultTexture = this.defaultTexture[ format ];
  49345. if ( defaultTexture === undefined ) {
  49346. const texture = new Texture();
  49347. texture.minFilter = NearestFilter;
  49348. texture.magFilter = NearestFilter;
  49349. this.createTexture( texture, { width: 1, height: 1, format } );
  49350. this.defaultTexture[ format ] = defaultTexture = texture;
  49351. }
  49352. return this.backend.get( defaultTexture ).texture;
  49353. }
  49354. /**
  49355. * Returns the default GPU cube texture for the given format.
  49356. *
  49357. * @private
  49358. * @param {string} format - The GPU format.
  49359. * @return {GPUTexture} The GPU texture.
  49360. */
  49361. _getDefaultCubeTextureGPU( format ) {
  49362. let defaultCubeTexture = this.defaultTexture[ format ];
  49363. if ( defaultCubeTexture === undefined ) {
  49364. const texture = new CubeTexture();
  49365. texture.minFilter = NearestFilter;
  49366. texture.magFilter = NearestFilter;
  49367. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  49368. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  49369. }
  49370. return this.backend.get( defaultCubeTexture ).texture;
  49371. }
  49372. /**
  49373. * Uploads cube texture image data to the GPU memory.
  49374. *
  49375. * @private
  49376. * @param {CubeTexture} texture - The cube texture.
  49377. * @param {GPUTexture} textureGPU - The GPU texture.
  49378. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49379. */
  49380. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  49381. const images = texture.images;
  49382. const mipmaps = texture.mipmaps;
  49383. for ( let i = 0; i < 6; i ++ ) {
  49384. const image = images[ i ];
  49385. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  49386. if ( image.isDataTexture ) {
  49387. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  49388. } else {
  49389. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  49390. }
  49391. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49392. const mipmap = mipmaps[ j ];
  49393. const image = mipmap.images[ i ];
  49394. if ( image.isDataTexture ) {
  49395. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  49396. } else {
  49397. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  49398. }
  49399. }
  49400. }
  49401. }
  49402. /**
  49403. * Uploads texture image data to the GPU memory.
  49404. *
  49405. * @private
  49406. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  49407. * @param {GPUTexture} textureGPU - The GPU texture.
  49408. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49409. * @param {number} originDepth - The origin depth.
  49410. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  49411. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  49412. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  49413. */
  49414. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  49415. const device = this.backend.device;
  49416. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  49417. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  49418. device.queue.copyExternalImageToTexture(
  49419. {
  49420. source: image,
  49421. flipY: flipY
  49422. }, {
  49423. texture: textureGPU,
  49424. mipLevel: mipLevel,
  49425. origin: { x: 0, y: 0, z: originDepth },
  49426. premultipliedAlpha: premultiplyAlpha
  49427. }, {
  49428. width: width,
  49429. height: height,
  49430. depthOrArrayLayers: 1
  49431. }
  49432. );
  49433. }
  49434. /**
  49435. * Returns the pass utils singleton.
  49436. *
  49437. * @private
  49438. * @return {WebGPUTexturePassUtils} The utils instance.
  49439. */
  49440. _getPassUtils() {
  49441. let passUtils = this._passUtils;
  49442. if ( passUtils === null ) {
  49443. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  49444. }
  49445. return passUtils;
  49446. }
  49447. /**
  49448. * Generates mipmaps for the given GPU texture.
  49449. *
  49450. * @private
  49451. * @param {GPUTexture} textureGPU - The GPU texture object.
  49452. * @param {Object} textureDescriptorGPU - The texture descriptor.
  49453. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  49454. */
  49455. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  49456. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  49457. }
  49458. /**
  49459. * Flip the contents of the given GPU texture along its vertical axis.
  49460. *
  49461. * @private
  49462. * @param {GPUTexture} textureGPU - The GPU texture object.
  49463. * @param {Object} textureDescriptorGPU - The texture descriptor.
  49464. * @param {number} [originDepth=0] - The origin depth.
  49465. */
  49466. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  49467. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  49468. }
  49469. /**
  49470. * Uploads texture buffer data to the GPU memory.
  49471. *
  49472. * @private
  49473. * @param {Object} image - An object defining the image buffer data.
  49474. * @param {GPUTexture} textureGPU - The GPU texture.
  49475. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49476. * @param {number} originDepth - The origin depth.
  49477. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  49478. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  49479. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  49480. */
  49481. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  49482. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  49483. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  49484. const device = this.backend.device;
  49485. const data = image.data;
  49486. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  49487. const bytesPerRow = image.width * bytesPerTexel;
  49488. device.queue.writeTexture(
  49489. {
  49490. texture: textureGPU,
  49491. mipLevel: mipLevel,
  49492. origin: { x: 0, y: 0, z: originDepth }
  49493. },
  49494. data,
  49495. {
  49496. offset: image.width * image.height * bytesPerTexel * depth,
  49497. bytesPerRow
  49498. },
  49499. {
  49500. width: image.width,
  49501. height: image.height,
  49502. depthOrArrayLayers: 1
  49503. } );
  49504. if ( flipY === true ) {
  49505. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  49506. }
  49507. }
  49508. /**
  49509. * Uploads compressed texture data to the GPU memory.
  49510. *
  49511. * @private
  49512. * @param {Array<Object>} mipmaps - An array with mipmap data.
  49513. * @param {GPUTexture} textureGPU - The GPU texture.
  49514. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  49515. */
  49516. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  49517. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  49518. const device = this.backend.device;
  49519. const blockData = this._getBlockData( textureDescriptorGPU.format );
  49520. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  49521. for ( let i = 0; i < mipmaps.length; i ++ ) {
  49522. const mipmap = mipmaps[ i ];
  49523. const width = mipmap.width;
  49524. const height = mipmap.height;
  49525. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  49526. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  49527. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  49528. for ( let j = 0; j < depth; j ++ ) {
  49529. device.queue.writeTexture(
  49530. {
  49531. texture: textureGPU,
  49532. mipLevel: i,
  49533. origin: { x: 0, y: 0, z: j }
  49534. },
  49535. mipmap.data,
  49536. {
  49537. offset: j * bytesPerImage,
  49538. bytesPerRow,
  49539. rowsPerImage: Math.ceil( height / blockData.height )
  49540. },
  49541. {
  49542. width: Math.ceil( width / blockData.width ) * blockData.width,
  49543. height: Math.ceil( height / blockData.height ) * blockData.height,
  49544. depthOrArrayLayers: 1
  49545. }
  49546. );
  49547. }
  49548. }
  49549. }
  49550. /**
  49551. * This method is only relevant for compressed texture formats. It returns a block
  49552. * data descriptor for the given GPU compressed texture format.
  49553. *
  49554. * @private
  49555. * @param {string} format - The GPU compressed texture format.
  49556. * @return {Object} The block data descriptor.
  49557. */
  49558. _getBlockData( format ) {
  49559. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  49560. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  49561. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  49562. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  49563. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  49564. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  49565. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  49566. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  49567. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  49568. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  49569. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  49570. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  49571. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  49572. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  49573. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  49574. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  49575. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  49576. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  49577. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  49578. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  49579. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  49580. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  49581. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  49582. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  49583. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  49584. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  49585. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  49586. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  49587. }
  49588. /**
  49589. * Converts the three.js uv wrapping constants to GPU address mode constants.
  49590. *
  49591. * @private
  49592. * @param {number} value - The three.js constant defining a uv wrapping mode.
  49593. * @return {string} The GPU address mode.
  49594. */
  49595. _convertAddressMode( value ) {
  49596. let addressMode = GPUAddressMode.ClampToEdge;
  49597. if ( value === RepeatWrapping ) {
  49598. addressMode = GPUAddressMode.Repeat;
  49599. } else if ( value === MirroredRepeatWrapping ) {
  49600. addressMode = GPUAddressMode.MirrorRepeat;
  49601. }
  49602. return addressMode;
  49603. }
  49604. /**
  49605. * Converts the three.js filter constants to GPU filter constants.
  49606. *
  49607. * @private
  49608. * @param {number} value - The three.js constant defining a filter mode.
  49609. * @return {string} The GPU filter mode.
  49610. */
  49611. _convertFilterMode( value ) {
  49612. let filterMode = GPUFilterMode.Linear;
  49613. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  49614. filterMode = GPUFilterMode.Nearest;
  49615. }
  49616. return filterMode;
  49617. }
  49618. /**
  49619. * Returns the bytes-per-texel value for the given GPU texture format.
  49620. *
  49621. * @private
  49622. * @param {string} format - The GPU texture format.
  49623. * @return {number} The bytes-per-texel.
  49624. */
  49625. _getBytesPerTexel( format ) {
  49626. // 8-bit formats
  49627. if ( format === GPUTextureFormat.R8Unorm ||
  49628. format === GPUTextureFormat.R8Snorm ||
  49629. format === GPUTextureFormat.R8Uint ||
  49630. format === GPUTextureFormat.R8Sint ) return 1;
  49631. // 16-bit formats
  49632. if ( format === GPUTextureFormat.R16Uint ||
  49633. format === GPUTextureFormat.R16Sint ||
  49634. format === GPUTextureFormat.R16Float ||
  49635. format === GPUTextureFormat.RG8Unorm ||
  49636. format === GPUTextureFormat.RG8Snorm ||
  49637. format === GPUTextureFormat.RG8Uint ||
  49638. format === GPUTextureFormat.RG8Sint ) return 2;
  49639. // 32-bit formats
  49640. if ( format === GPUTextureFormat.R32Uint ||
  49641. format === GPUTextureFormat.R32Sint ||
  49642. format === GPUTextureFormat.R32Float ||
  49643. format === GPUTextureFormat.RG16Uint ||
  49644. format === GPUTextureFormat.RG16Sint ||
  49645. format === GPUTextureFormat.RG16Float ||
  49646. format === GPUTextureFormat.RGBA8Unorm ||
  49647. format === GPUTextureFormat.RGBA8UnormSRGB ||
  49648. format === GPUTextureFormat.RGBA8Snorm ||
  49649. format === GPUTextureFormat.RGBA8Uint ||
  49650. format === GPUTextureFormat.RGBA8Sint ||
  49651. format === GPUTextureFormat.BGRA8Unorm ||
  49652. format === GPUTextureFormat.BGRA8UnormSRGB ||
  49653. // Packed 32-bit formats
  49654. format === GPUTextureFormat.RGB9E5UFloat ||
  49655. format === GPUTextureFormat.RGB10A2Unorm ||
  49656. format === GPUTextureFormat.RG11B10UFloat ||
  49657. format === GPUTextureFormat.Depth32Float ||
  49658. format === GPUTextureFormat.Depth24Plus ||
  49659. format === GPUTextureFormat.Depth24PlusStencil8 ||
  49660. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  49661. // 64-bit formats
  49662. if ( format === GPUTextureFormat.RG32Uint ||
  49663. format === GPUTextureFormat.RG32Sint ||
  49664. format === GPUTextureFormat.RG32Float ||
  49665. format === GPUTextureFormat.RGBA16Uint ||
  49666. format === GPUTextureFormat.RGBA16Sint ||
  49667. format === GPUTextureFormat.RGBA16Float ) return 8;
  49668. // 128-bit formats
  49669. if ( format === GPUTextureFormat.RGBA32Uint ||
  49670. format === GPUTextureFormat.RGBA32Sint ||
  49671. format === GPUTextureFormat.RGBA32Float ) return 16;
  49672. }
  49673. /**
  49674. * Returns the corresponding typed array type for the given GPU texture format.
  49675. *
  49676. * @private
  49677. * @param {string} format - The GPU texture format.
  49678. * @return {TypedArray.constructor} The typed array type.
  49679. */
  49680. _getTypedArrayType( format ) {
  49681. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  49682. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  49683. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  49684. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  49685. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  49686. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  49687. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  49688. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  49689. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  49690. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  49691. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  49692. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  49693. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  49694. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  49695. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  49696. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  49697. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  49698. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  49699. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  49700. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  49701. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  49702. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  49703. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  49704. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  49705. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  49706. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  49707. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  49708. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  49709. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  49710. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  49711. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  49712. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  49713. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  49714. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  49715. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  49716. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  49717. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  49718. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  49719. }
  49720. /**
  49721. * Returns the GPU dimensions for the given texture.
  49722. *
  49723. * @private
  49724. * @param {Texture} texture - The texture.
  49725. * @return {string} The GPU dimension.
  49726. */
  49727. _getDimension( texture ) {
  49728. let dimension;
  49729. if ( texture.is3DTexture || texture.isData3DTexture ) {
  49730. dimension = GPUTextureDimension.ThreeD;
  49731. } else {
  49732. dimension = GPUTextureDimension.TwoD;
  49733. }
  49734. return dimension;
  49735. }
  49736. }
  49737. /**
  49738. * Returns the GPU format for the given texture.
  49739. *
  49740. * @param {Texture} texture - The texture.
  49741. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  49742. * It is not necessary to apply the device for most formats.
  49743. * @return {string} The GPU format.
  49744. */
  49745. function getFormat( texture, device = null ) {
  49746. const format = texture.format;
  49747. const type = texture.type;
  49748. const colorSpace = texture.colorSpace;
  49749. const transfer = ColorManagement.getTransfer( colorSpace );
  49750. let formatGPU;
  49751. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  49752. switch ( format ) {
  49753. case RGB_S3TC_DXT1_Format:
  49754. case RGBA_S3TC_DXT1_Format:
  49755. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  49756. break;
  49757. case RGBA_S3TC_DXT3_Format:
  49758. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  49759. break;
  49760. case RGBA_S3TC_DXT5_Format:
  49761. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  49762. break;
  49763. case RED_RGTC1_Format:
  49764. formatGPU = GPUTextureFormat.BC4RUnorm;
  49765. break;
  49766. case SIGNED_RED_RGTC1_Format:
  49767. formatGPU = GPUTextureFormat.BC4RSnorm;
  49768. break;
  49769. case RED_GREEN_RGTC2_Format:
  49770. formatGPU = GPUTextureFormat.BC5RGUnorm;
  49771. break;
  49772. case SIGNED_RED_GREEN_RGTC2_Format:
  49773. formatGPU = GPUTextureFormat.BC5RGSnorm;
  49774. break;
  49775. case RGBA_BPTC_Format:
  49776. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  49777. break;
  49778. case RGB_ETC2_Format:
  49779. case RGB_ETC1_Format:
  49780. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  49781. break;
  49782. case RGBA_ETC2_EAC_Format:
  49783. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  49784. break;
  49785. case RGBA_ASTC_4x4_Format:
  49786. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  49787. break;
  49788. case RGBA_ASTC_5x4_Format:
  49789. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  49790. break;
  49791. case RGBA_ASTC_5x5_Format:
  49792. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  49793. break;
  49794. case RGBA_ASTC_6x5_Format:
  49795. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  49796. break;
  49797. case RGBA_ASTC_6x6_Format:
  49798. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  49799. break;
  49800. case RGBA_ASTC_8x5_Format:
  49801. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  49802. break;
  49803. case RGBA_ASTC_8x6_Format:
  49804. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  49805. break;
  49806. case RGBA_ASTC_8x8_Format:
  49807. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  49808. break;
  49809. case RGBA_ASTC_10x5_Format:
  49810. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  49811. break;
  49812. case RGBA_ASTC_10x6_Format:
  49813. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  49814. break;
  49815. case RGBA_ASTC_10x8_Format:
  49816. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  49817. break;
  49818. case RGBA_ASTC_10x10_Format:
  49819. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  49820. break;
  49821. case RGBA_ASTC_12x10_Format:
  49822. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  49823. break;
  49824. case RGBA_ASTC_12x12_Format:
  49825. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  49826. break;
  49827. case RGBAFormat:
  49828. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  49829. break;
  49830. default:
  49831. error( 'WebGPURenderer: Unsupported texture format.', format );
  49832. }
  49833. } else {
  49834. switch ( format ) {
  49835. case RGBAFormat:
  49836. switch ( type ) {
  49837. case ByteType:
  49838. formatGPU = GPUTextureFormat.RGBA8Snorm;
  49839. break;
  49840. case ShortType:
  49841. formatGPU = GPUTextureFormat.RGBA16Sint;
  49842. break;
  49843. case UnsignedShortType:
  49844. formatGPU = GPUTextureFormat.RGBA16Uint;
  49845. break;
  49846. case UnsignedIntType:
  49847. formatGPU = GPUTextureFormat.RGBA32Uint;
  49848. break;
  49849. case IntType:
  49850. formatGPU = GPUTextureFormat.RGBA32Sint;
  49851. break;
  49852. case UnsignedByteType:
  49853. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  49854. break;
  49855. case HalfFloatType:
  49856. formatGPU = GPUTextureFormat.RGBA16Float;
  49857. break;
  49858. case FloatType:
  49859. formatGPU = GPUTextureFormat.RGBA32Float;
  49860. break;
  49861. default:
  49862. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  49863. }
  49864. break;
  49865. case RGBFormat:
  49866. switch ( type ) {
  49867. case UnsignedInt5999Type:
  49868. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  49869. break;
  49870. case UnsignedInt101111Type:
  49871. formatGPU = GPUTextureFormat.RG11B10UFloat;
  49872. break;
  49873. default:
  49874. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  49875. }
  49876. break;
  49877. case RedFormat:
  49878. switch ( type ) {
  49879. case ByteType:
  49880. formatGPU = GPUTextureFormat.R8Snorm;
  49881. break;
  49882. case ShortType:
  49883. formatGPU = GPUTextureFormat.R16Sint;
  49884. break;
  49885. case UnsignedShortType:
  49886. formatGPU = GPUTextureFormat.R16Uint;
  49887. break;
  49888. case UnsignedIntType:
  49889. formatGPU = GPUTextureFormat.R32Uint;
  49890. break;
  49891. case IntType:
  49892. formatGPU = GPUTextureFormat.R32Sint;
  49893. break;
  49894. case UnsignedByteType:
  49895. formatGPU = GPUTextureFormat.R8Unorm;
  49896. break;
  49897. case HalfFloatType:
  49898. formatGPU = GPUTextureFormat.R16Float;
  49899. break;
  49900. case FloatType:
  49901. formatGPU = GPUTextureFormat.R32Float;
  49902. break;
  49903. default:
  49904. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  49905. }
  49906. break;
  49907. case RGFormat:
  49908. switch ( type ) {
  49909. case ByteType:
  49910. formatGPU = GPUTextureFormat.RG8Snorm;
  49911. break;
  49912. case ShortType:
  49913. formatGPU = GPUTextureFormat.RG16Sint;
  49914. break;
  49915. case UnsignedShortType:
  49916. formatGPU = GPUTextureFormat.RG16Uint;
  49917. break;
  49918. case UnsignedIntType:
  49919. formatGPU = GPUTextureFormat.RG32Uint;
  49920. break;
  49921. case IntType:
  49922. formatGPU = GPUTextureFormat.RG32Sint;
  49923. break;
  49924. case UnsignedByteType:
  49925. formatGPU = GPUTextureFormat.RG8Unorm;
  49926. break;
  49927. case HalfFloatType:
  49928. formatGPU = GPUTextureFormat.RG16Float;
  49929. break;
  49930. case FloatType:
  49931. formatGPU = GPUTextureFormat.RG32Float;
  49932. break;
  49933. default:
  49934. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  49935. }
  49936. break;
  49937. case DepthFormat:
  49938. switch ( type ) {
  49939. case UnsignedShortType:
  49940. formatGPU = GPUTextureFormat.Depth16Unorm;
  49941. break;
  49942. case UnsignedIntType:
  49943. formatGPU = GPUTextureFormat.Depth24Plus;
  49944. break;
  49945. case FloatType:
  49946. formatGPU = GPUTextureFormat.Depth32Float;
  49947. break;
  49948. default:
  49949. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  49950. }
  49951. break;
  49952. case DepthStencilFormat:
  49953. switch ( type ) {
  49954. case UnsignedInt248Type:
  49955. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  49956. break;
  49957. case FloatType:
  49958. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  49959. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  49960. }
  49961. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  49962. break;
  49963. default:
  49964. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  49965. }
  49966. break;
  49967. case RedIntegerFormat:
  49968. switch ( type ) {
  49969. case IntType:
  49970. formatGPU = GPUTextureFormat.R32Sint;
  49971. break;
  49972. case UnsignedIntType:
  49973. formatGPU = GPUTextureFormat.R32Uint;
  49974. break;
  49975. default:
  49976. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  49977. }
  49978. break;
  49979. case RGIntegerFormat:
  49980. switch ( type ) {
  49981. case IntType:
  49982. formatGPU = GPUTextureFormat.RG32Sint;
  49983. break;
  49984. case UnsignedIntType:
  49985. formatGPU = GPUTextureFormat.RG32Uint;
  49986. break;
  49987. default:
  49988. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  49989. }
  49990. break;
  49991. case RGBAIntegerFormat:
  49992. switch ( type ) {
  49993. case IntType:
  49994. formatGPU = GPUTextureFormat.RGBA32Sint;
  49995. break;
  49996. case UnsignedIntType:
  49997. formatGPU = GPUTextureFormat.RGBA32Uint;
  49998. break;
  49999. default:
  50000. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  50001. }
  50002. break;
  50003. default:
  50004. error( 'WebGPURenderer: Unsupported texture format.', format );
  50005. }
  50006. }
  50007. return formatGPU;
  50008. }
  50009. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  50010. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  50011. const wgslTypeLib$1 = {
  50012. 'f32': 'float',
  50013. 'i32': 'int',
  50014. 'u32': 'uint',
  50015. 'bool': 'bool',
  50016. 'vec2<f32>': 'vec2',
  50017. 'vec2<i32>': 'ivec2',
  50018. 'vec2<u32>': 'uvec2',
  50019. 'vec2<bool>': 'bvec2',
  50020. 'vec2f': 'vec2',
  50021. 'vec2i': 'ivec2',
  50022. 'vec2u': 'uvec2',
  50023. 'vec2b': 'bvec2',
  50024. 'vec3<f32>': 'vec3',
  50025. 'vec3<i32>': 'ivec3',
  50026. 'vec3<u32>': 'uvec3',
  50027. 'vec3<bool>': 'bvec3',
  50028. 'vec3f': 'vec3',
  50029. 'vec3i': 'ivec3',
  50030. 'vec3u': 'uvec3',
  50031. 'vec3b': 'bvec3',
  50032. 'vec4<f32>': 'vec4',
  50033. 'vec4<i32>': 'ivec4',
  50034. 'vec4<u32>': 'uvec4',
  50035. 'vec4<bool>': 'bvec4',
  50036. 'vec4f': 'vec4',
  50037. 'vec4i': 'ivec4',
  50038. 'vec4u': 'uvec4',
  50039. 'vec4b': 'bvec4',
  50040. 'mat2x2<f32>': 'mat2',
  50041. 'mat2x2f': 'mat2',
  50042. 'mat3x3<f32>': 'mat3',
  50043. 'mat3x3f': 'mat3',
  50044. 'mat4x4<f32>': 'mat4',
  50045. 'mat4x4f': 'mat4',
  50046. 'sampler': 'sampler',
  50047. 'texture_1d': 'texture',
  50048. 'texture_2d': 'texture',
  50049. 'texture_2d_array': 'texture',
  50050. 'texture_multisampled_2d': 'cubeTexture',
  50051. 'texture_depth_2d': 'depthTexture',
  50052. 'texture_depth_2d_array': 'depthTexture',
  50053. 'texture_depth_multisampled_2d': 'depthTexture',
  50054. 'texture_depth_cube': 'depthTexture',
  50055. 'texture_depth_cube_array': 'depthTexture',
  50056. 'texture_3d': 'texture3D',
  50057. 'texture_cube': 'cubeTexture',
  50058. 'texture_cube_array': 'cubeTexture',
  50059. 'texture_storage_1d': 'storageTexture',
  50060. 'texture_storage_2d': 'storageTexture',
  50061. 'texture_storage_2d_array': 'storageTexture',
  50062. 'texture_storage_3d': 'storageTexture'
  50063. };
  50064. const parse = ( source ) => {
  50065. source = source.trim();
  50066. const declaration = source.match( declarationRegexp );
  50067. if ( declaration !== null && declaration.length === 4 ) {
  50068. const inputsCode = declaration[ 2 ];
  50069. const propsMatches = [];
  50070. let match = null;
  50071. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  50072. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  50073. }
  50074. // Process matches to correctly pair names and types
  50075. const inputs = [];
  50076. for ( let i = 0; i < propsMatches.length; i ++ ) {
  50077. const { name, type } = propsMatches[ i ];
  50078. let resolvedType = type;
  50079. if ( resolvedType.startsWith( 'ptr' ) ) {
  50080. resolvedType = 'pointer';
  50081. } else {
  50082. if ( resolvedType.startsWith( 'texture' ) ) {
  50083. resolvedType = type.split( '<' )[ 0 ];
  50084. }
  50085. resolvedType = wgslTypeLib$1[ resolvedType ];
  50086. }
  50087. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  50088. }
  50089. const blockCode = source.substring( declaration[ 0 ].length );
  50090. const outputType = declaration[ 3 ] || 'void';
  50091. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  50092. const type = wgslTypeLib$1[ outputType ] || outputType;
  50093. return {
  50094. type,
  50095. inputs,
  50096. name,
  50097. inputsCode,
  50098. blockCode,
  50099. outputType
  50100. };
  50101. } else {
  50102. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  50103. }
  50104. };
  50105. /**
  50106. * This class represents a WSL node function.
  50107. *
  50108. * @augments NodeFunction
  50109. */
  50110. class WGSLNodeFunction extends NodeFunction {
  50111. /**
  50112. * Constructs a new WGSL node function.
  50113. *
  50114. * @param {string} source - The WGSL source.
  50115. */
  50116. constructor( source ) {
  50117. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  50118. super( type, inputs, name );
  50119. this.inputsCode = inputsCode;
  50120. this.blockCode = blockCode;
  50121. this.outputType = outputType;
  50122. }
  50123. /**
  50124. * This method returns the WGSL code of the node function.
  50125. *
  50126. * @param {string} [name=this.name] - The function's name.
  50127. * @return {string} The shader code.
  50128. */
  50129. getCode( name = this.name ) {
  50130. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  50131. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  50132. }
  50133. }
  50134. /**
  50135. * A WGSL node parser.
  50136. *
  50137. * @augments NodeParser
  50138. */
  50139. class WGSLNodeParser extends NodeParser {
  50140. /**
  50141. * The method parses the given WGSL code an returns a node function.
  50142. *
  50143. * @param {string} source - The WGSL code.
  50144. * @return {WGSLNodeFunction} A node function.
  50145. */
  50146. parseFunction( source ) {
  50147. return new WGSLNodeFunction( source );
  50148. }
  50149. }
  50150. // GPUShaderStage is not defined in browsers not supporting WebGPU
  50151. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  50152. const accessNames = {
  50153. [ NodeAccess.READ_ONLY ]: 'read',
  50154. [ NodeAccess.WRITE_ONLY ]: 'write',
  50155. [ NodeAccess.READ_WRITE ]: 'read_write'
  50156. };
  50157. const wrapNames = {
  50158. [ RepeatWrapping ]: 'repeat',
  50159. [ ClampToEdgeWrapping ]: 'clamp',
  50160. [ MirroredRepeatWrapping ]: 'mirror'
  50161. };
  50162. const gpuShaderStageLib = {
  50163. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  50164. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  50165. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  50166. };
  50167. const supports = {
  50168. instance: true,
  50169. swizzleAssign: false,
  50170. storageBuffer: true
  50171. };
  50172. const wgslFnOpLib = {
  50173. '^^': 'tsl_xor'
  50174. };
  50175. const wgslTypeLib = {
  50176. float: 'f32',
  50177. int: 'i32',
  50178. uint: 'u32',
  50179. bool: 'bool',
  50180. color: 'vec3<f32>',
  50181. vec2: 'vec2<f32>',
  50182. ivec2: 'vec2<i32>',
  50183. uvec2: 'vec2<u32>',
  50184. bvec2: 'vec2<bool>',
  50185. vec3: 'vec3<f32>',
  50186. ivec3: 'vec3<i32>',
  50187. uvec3: 'vec3<u32>',
  50188. bvec3: 'vec3<bool>',
  50189. vec4: 'vec4<f32>',
  50190. ivec4: 'vec4<i32>',
  50191. uvec4: 'vec4<u32>',
  50192. bvec4: 'vec4<bool>',
  50193. mat2: 'mat2x2<f32>',
  50194. mat3: 'mat3x3<f32>',
  50195. mat4: 'mat4x4<f32>'
  50196. };
  50197. const wgslCodeCache = {};
  50198. const wgslPolyfill = {
  50199. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  50200. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  50201. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  50202. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  50203. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  50204. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  50205. 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 ); }' ),
  50206. 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 ); }' ),
  50207. 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 ); }' ),
  50208. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  50209. 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 ); }' ),
  50210. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  50211. biquadraticTexture: new CodeNode( /* wgsl */`
  50212. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  50213. let res = vec2f( iRes );
  50214. let uvScaled = coord * res;
  50215. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  50216. // https://www.shadertoy.com/view/WtyXRy
  50217. let uv = uvWrapping - 0.5;
  50218. let iuv = floor( uv );
  50219. let f = fract( uv );
  50220. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  50221. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  50222. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  50223. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  50224. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  50225. }
  50226. ` )
  50227. };
  50228. const wgslMethods = {
  50229. dFdx: 'dpdx',
  50230. dFdy: '- dpdy',
  50231. mod_float: 'tsl_mod_float',
  50232. mod_vec2: 'tsl_mod_vec2',
  50233. mod_vec3: 'tsl_mod_vec3',
  50234. mod_vec4: 'tsl_mod_vec4',
  50235. equals_bool: 'tsl_equals_bool',
  50236. equals_bvec2: 'tsl_equals_bvec2',
  50237. equals_bvec3: 'tsl_equals_bvec3',
  50238. equals_bvec4: 'tsl_equals_bvec4',
  50239. inversesqrt: 'inverseSqrt',
  50240. bitcast: 'bitcast<f32>'
  50241. };
  50242. //
  50243. let diagnostics = '';
  50244. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  50245. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  50246. }
  50247. /**
  50248. * A node builder targeting WGSL.
  50249. *
  50250. * This module generates WGSL shader code from node materials and also
  50251. * generates the respective bindings and vertex buffer definitions. These
  50252. * data are later used by the renderer to create render and compute pipelines
  50253. * for render objects.
  50254. *
  50255. * @augments NodeBuilder
  50256. */
  50257. class WGSLNodeBuilder extends NodeBuilder {
  50258. /**
  50259. * Constructs a new WGSL node builder renderer.
  50260. *
  50261. * @param {Object3D} object - The 3D object.
  50262. * @param {Renderer} renderer - The renderer.
  50263. */
  50264. constructor( object, renderer ) {
  50265. super( object, renderer, new WGSLNodeParser() );
  50266. /**
  50267. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  50268. * another dictionary which manages UBOs per group ('render','frame','object').
  50269. *
  50270. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  50271. */
  50272. this.uniformGroups = {};
  50273. /**
  50274. * A dictionary that holds for each shader stage a Map of builtins.
  50275. *
  50276. * @type {Object<string,Map<string,Object>>}
  50277. */
  50278. this.builtins = {};
  50279. /**
  50280. * A dictionary that holds for each shader stage a Set of directives.
  50281. *
  50282. * @type {Object<string,Set<string>>}
  50283. */
  50284. this.directives = {};
  50285. /**
  50286. * A map for managing scope arrays. Only relevant for when using
  50287. * {@link WorkgroupInfoNode} in context of compute shaders.
  50288. *
  50289. * @type {Map<string,Object>}
  50290. */
  50291. this.scopedArrays = new Map();
  50292. }
  50293. /**
  50294. * Generates the WGSL snippet for sampled textures.
  50295. *
  50296. * @private
  50297. * @param {Texture} texture - The texture.
  50298. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50299. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50300. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50301. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50302. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50303. * @return {string} The WGSL snippet.
  50304. */
  50305. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50306. if ( shaderStage === 'fragment' ) {
  50307. if ( depthSnippet ) {
  50308. if ( offsetSnippet ) {
  50309. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  50310. }
  50311. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  50312. } else {
  50313. if ( offsetSnippet ) {
  50314. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  50315. }
  50316. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  50317. }
  50318. } else {
  50319. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  50320. }
  50321. }
  50322. /**
  50323. * Generates the WGSL snippet when sampling textures with explicit mip level.
  50324. *
  50325. * @private
  50326. * @param {Texture} texture - The texture.
  50327. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50328. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50329. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50330. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50331. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50332. * @return {string} The WGSL snippet.
  50333. */
  50334. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50335. if ( this.isUnfilterable( texture ) === false ) {
  50336. if ( offsetSnippet ) {
  50337. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  50338. }
  50339. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  50340. } else if ( this.isFilteredTexture( texture ) ) {
  50341. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  50342. } else {
  50343. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  50344. }
  50345. }
  50346. /**
  50347. * Generates a wrap function used in context of textures.
  50348. *
  50349. * @param {Texture} texture - The texture to generate the function for.
  50350. * @return {string} The name of the generated function.
  50351. */
  50352. generateWrapFunction( texture ) {
  50353. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  50354. let nodeCode = wgslCodeCache[ functionName ];
  50355. if ( nodeCode === undefined ) {
  50356. const includes = [];
  50357. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  50358. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  50359. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  50360. const addWrapSnippet = ( wrap, axis ) => {
  50361. if ( wrap === RepeatWrapping ) {
  50362. includes.push( wgslPolyfill.repeatWrapping_float );
  50363. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  50364. } else if ( wrap === ClampToEdgeWrapping ) {
  50365. includes.push( wgslPolyfill.clampWrapping_float );
  50366. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  50367. } else if ( wrap === MirroredRepeatWrapping ) {
  50368. includes.push( wgslPolyfill.mirrorWrapping_float );
  50369. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  50370. } else {
  50371. code += `\t\tcoord.${ axis }`;
  50372. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  50373. }
  50374. };
  50375. addWrapSnippet( texture.wrapS, 'x' );
  50376. code += ',\n';
  50377. addWrapSnippet( texture.wrapT, 'y' );
  50378. if ( texture.isData3DTexture ) {
  50379. code += ',\n';
  50380. addWrapSnippet( texture.wrapR, 'z' );
  50381. }
  50382. code += '\n\t);\n\n}\n';
  50383. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  50384. }
  50385. nodeCode.build( this );
  50386. return functionName;
  50387. }
  50388. /**
  50389. * Generates the array declaration string.
  50390. *
  50391. * @param {string} type - The type.
  50392. * @param {?number} [count] - The count.
  50393. * @return {string} The generated value as a shader string.
  50394. */
  50395. generateArrayDeclaration( type, count ) {
  50396. return `array< ${ this.getType( type ) }, ${ count } >`;
  50397. }
  50398. /**
  50399. * Generates a WGSL variable that holds the texture dimension of the given texture.
  50400. * It also returns information about the number of layers (elements) of an arrayed
  50401. * texture as well as the cube face count of cube textures.
  50402. *
  50403. * @param {Texture} texture - The texture to generate the function for.
  50404. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  50405. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50406. * @return {string} The name of the dimension variable.
  50407. */
  50408. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  50409. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  50410. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  50411. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  50412. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  50413. let textureDimensionsParams;
  50414. let dimensionType;
  50415. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  50416. const isMultisampled = primarySamples > 1;
  50417. if ( texture.isData3DTexture ) {
  50418. dimensionType = 'vec3<u32>';
  50419. } else {
  50420. // Regular 2D textures, depth textures, etc.
  50421. dimensionType = 'vec2<u32>';
  50422. }
  50423. // Build parameters string based on texture type and multisampling
  50424. if ( isMultisampled || texture.isStorageTexture ) {
  50425. textureDimensionsParams = textureProperty;
  50426. } else {
  50427. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  50428. }
  50429. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  50430. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  50431. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  50432. textureData.arrayLayerCount = new VarNode(
  50433. new ExpressionNode(
  50434. `textureNumLayers(${textureProperty})`,
  50435. 'u32'
  50436. )
  50437. );
  50438. }
  50439. // For cube textures, we know it's always 6 faces
  50440. if ( texture.isTextureCube ) {
  50441. textureData.cubeFaceCount = new VarNode(
  50442. new ExpressionNode( '6u', 'u32' )
  50443. );
  50444. }
  50445. }
  50446. return textureDimensionNode.build( this );
  50447. }
  50448. /**
  50449. * Generates the WGSL snippet for a manual filtered texture.
  50450. *
  50451. * @param {Texture} texture - The texture.
  50452. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50453. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50454. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50455. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50456. * @return {string} The WGSL snippet.
  50457. */
  50458. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  50459. this._include( 'biquadraticTexture' );
  50460. const wrapFunction = this.generateWrapFunction( texture );
  50461. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  50462. if ( offsetSnippet ) {
  50463. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  50464. }
  50465. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  50466. }
  50467. /**
  50468. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  50469. * Since it's a lookup, no sampling or filtering is applied.
  50470. *
  50471. * @param {Texture} texture - The texture.
  50472. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50473. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50474. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50475. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50476. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50477. * @return {string} The WGSL snippet.
  50478. */
  50479. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  50480. const wrapFunction = this.generateWrapFunction( texture );
  50481. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  50482. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  50483. if ( offsetSnippet ) {
  50484. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  50485. }
  50486. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  50487. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  50488. }
  50489. /**
  50490. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  50491. *
  50492. * @param {Texture} texture - The texture.
  50493. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50494. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50495. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50496. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50497. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50498. * @return {string} The WGSL snippet.
  50499. */
  50500. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50501. if ( levelSnippet === null ) levelSnippet = '0u';
  50502. if ( offsetSnippet ) {
  50503. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  50504. }
  50505. let snippet;
  50506. if ( depthSnippet ) {
  50507. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  50508. } else {
  50509. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  50510. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  50511. snippet += '.x';
  50512. }
  50513. }
  50514. return snippet;
  50515. }
  50516. /**
  50517. * Generates the WGSL snippet that writes a single texel to a texture.
  50518. *
  50519. * @param {Texture} texture - The texture.
  50520. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50521. * @param {string} uvIndexSnippet - 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} valueSnippet - A WGSL snippet that represent the new texel value.
  50524. * @return {string} The WGSL snippet.
  50525. */
  50526. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  50527. let snippet;
  50528. if ( depthSnippet ) {
  50529. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  50530. } else {
  50531. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  50532. }
  50533. return snippet;
  50534. }
  50535. /**
  50536. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  50537. *
  50538. * @param {Texture} texture - The texture.
  50539. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  50540. */
  50541. isSampleCompare( texture ) {
  50542. return texture.isDepthTexture === true && texture.compareFunction !== null;
  50543. }
  50544. /**
  50545. * Returns `true` if the given texture is unfilterable.
  50546. *
  50547. * @param {Texture} texture - The texture.
  50548. * @return {boolean} Whether the given texture is unfilterable or not.
  50549. */
  50550. isUnfilterable( texture ) {
  50551. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  50552. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  50553. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  50554. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  50555. }
  50556. /**
  50557. * Generates the WGSL snippet for sampling/loading the given texture.
  50558. *
  50559. * @param {Texture} texture - The texture.
  50560. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50561. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50562. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50563. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50564. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50565. * @return {string} The WGSL snippet.
  50566. */
  50567. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50568. let snippet = null;
  50569. if ( this.isUnfilterable( texture ) ) {
  50570. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  50571. } else {
  50572. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  50573. }
  50574. return snippet;
  50575. }
  50576. /**
  50577. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  50578. *
  50579. * @param {Texture} texture - The texture.
  50580. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50581. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50582. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  50583. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50584. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50585. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50586. * @return {string} The WGSL snippet.
  50587. */
  50588. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50589. if ( shaderStage === 'fragment' ) {
  50590. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  50591. if ( offsetSnippet ) {
  50592. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  50593. }
  50594. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  50595. } else {
  50596. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  50597. }
  50598. }
  50599. /**
  50600. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  50601. * against a reference value.
  50602. *
  50603. * @param {Texture} texture - The texture.
  50604. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50605. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50606. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  50607. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50608. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50609. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50610. * @return {string} The WGSL snippet.
  50611. */
  50612. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50613. if ( shaderStage === 'fragment' ) {
  50614. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  50615. if ( offsetSnippet ) {
  50616. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  50617. }
  50618. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  50619. }
  50620. if ( offsetSnippet ) {
  50621. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  50622. }
  50623. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  50624. } else {
  50625. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  50626. }
  50627. }
  50628. /**
  50629. * Generates the WGSL snippet when sampling textures with explicit mip level.
  50630. *
  50631. * @param {Texture} texture - The texture.
  50632. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50633. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50634. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  50635. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50636. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50637. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50638. * @return {string} The WGSL snippet.
  50639. */
  50640. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  50641. if ( this.isUnfilterable( texture ) === false ) {
  50642. if ( offsetSnippet ) {
  50643. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  50644. }
  50645. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  50646. } else if ( this.isFilteredTexture( texture ) ) {
  50647. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  50648. } else {
  50649. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  50650. }
  50651. }
  50652. /**
  50653. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  50654. *
  50655. * @param {Texture} texture - The texture.
  50656. * @param {string} textureProperty - The name of the texture uniform in the shader.
  50657. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  50658. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  50659. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  50660. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  50661. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50662. * @return {string} The WGSL snippet.
  50663. */
  50664. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  50665. if ( shaderStage === 'fragment' ) {
  50666. if ( offsetSnippet ) {
  50667. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  50668. }
  50669. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  50670. } else {
  50671. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  50672. }
  50673. }
  50674. /**
  50675. * Returns a WGSL snippet that represents the property name of the given node.
  50676. *
  50677. * @param {Node} node - The node.
  50678. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50679. * @return {string} The property name.
  50680. */
  50681. getPropertyName( node, shaderStage = this.shaderStage ) {
  50682. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  50683. if ( shaderStage === 'vertex' ) {
  50684. return `varyings.${ node.name }`;
  50685. }
  50686. } else if ( node.isNodeUniform === true ) {
  50687. const name = node.name;
  50688. const type = node.type;
  50689. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  50690. return name;
  50691. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  50692. if ( this.isCustomStruct( node ) ) {
  50693. return name;
  50694. }
  50695. return name + '.value';
  50696. } else {
  50697. return node.groupNode.name + '.' + name;
  50698. }
  50699. }
  50700. return super.getPropertyName( node );
  50701. }
  50702. /**
  50703. * Returns the output struct name.
  50704. *
  50705. * @return {string} The name of the output struct.
  50706. */
  50707. getOutputStructName() {
  50708. return 'output';
  50709. }
  50710. /**
  50711. * Returns the native shader operator name for a given generic name.
  50712. *
  50713. * @param {string} op - The operator name to resolve.
  50714. * @return {?string} The resolved operator name.
  50715. */
  50716. getFunctionOperator( op ) {
  50717. const fnOp = wgslFnOpLib[ op ];
  50718. if ( fnOp !== undefined ) {
  50719. this._include( fnOp );
  50720. return fnOp;
  50721. }
  50722. return null;
  50723. }
  50724. /**
  50725. * Returns the node access for the given node and shader stage.
  50726. *
  50727. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  50728. * @param {string} shaderStage - The shader stage.
  50729. * @return {string} The node access.
  50730. */
  50731. getNodeAccess( node, shaderStage ) {
  50732. if ( shaderStage !== 'compute' ) {
  50733. if ( node.isAtomic === true ) {
  50734. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  50735. return NodeAccess.READ_WRITE;
  50736. }
  50737. return NodeAccess.READ_ONLY;
  50738. }
  50739. return node.access;
  50740. }
  50741. /**
  50742. * Returns A WGSL snippet representing the storage access.
  50743. *
  50744. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  50745. * @param {string} shaderStage - The shader stage.
  50746. * @return {string} The WGSL snippet representing the storage access.
  50747. */
  50748. getStorageAccess( node, shaderStage ) {
  50749. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  50750. }
  50751. /**
  50752. * This method is one of the more important ones since it's responsible
  50753. * for generating a matching binding instance for the given uniform node.
  50754. *
  50755. * These bindings are later used in the renderer to create bind groups
  50756. * and layouts.
  50757. *
  50758. * @param {UniformNode} node - The uniform node.
  50759. * @param {string} type - The node data type.
  50760. * @param {string} shaderStage - The shader stage.
  50761. * @param {?string} [name=null] - An optional uniform name.
  50762. * @return {NodeUniform} The node uniform object.
  50763. */
  50764. getUniformFromNode( node, type, shaderStage, name = null ) {
  50765. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  50766. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  50767. if ( nodeData.uniformGPU === undefined ) {
  50768. let uniformGPU;
  50769. const group = node.groupNode;
  50770. const groupName = group.name;
  50771. const bindings = this.getBindGroupArray( groupName, shaderStage );
  50772. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  50773. let texture = null;
  50774. const access = this.getNodeAccess( node, shaderStage );
  50775. if ( type === 'texture' || type === 'storageTexture' ) {
  50776. if ( node.value.is3DTexture === true ) {
  50777. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  50778. } else {
  50779. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  50780. }
  50781. } else if ( type === 'cubeTexture' ) {
  50782. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  50783. } else if ( type === 'texture3D' ) {
  50784. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  50785. }
  50786. texture.store = node.isStorageTextureNode === true;
  50787. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  50788. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  50789. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  50790. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  50791. bindings.push( sampler, texture );
  50792. uniformGPU = [ sampler, texture ];
  50793. } else {
  50794. bindings.push( texture );
  50795. uniformGPU = [ texture ];
  50796. }
  50797. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  50798. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  50799. const buffer = new bufferClass( node, group );
  50800. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  50801. bindings.push( buffer );
  50802. uniformGPU = buffer;
  50803. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  50804. } else {
  50805. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  50806. let uniformsGroup = uniformsStage[ groupName ];
  50807. if ( uniformsGroup === undefined ) {
  50808. uniformsGroup = new NodeUniformsGroup( groupName, group );
  50809. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  50810. uniformsStage[ groupName ] = uniformsGroup;
  50811. bindings.push( uniformsGroup );
  50812. }
  50813. uniformGPU = this.getNodeUniform( uniformNode, type );
  50814. uniformsGroup.addUniform( uniformGPU );
  50815. }
  50816. nodeData.uniformGPU = uniformGPU;
  50817. }
  50818. return uniformNode;
  50819. }
  50820. /**
  50821. * This method should be used whenever builtins are required in nodes.
  50822. * The internal builtins data structure will make sure builtins are
  50823. * defined in the WGSL source.
  50824. *
  50825. * @param {string} name - The builtin name.
  50826. * @param {string} property - The property name.
  50827. * @param {string} type - The node data type.
  50828. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50829. * @return {string} The property name.
  50830. */
  50831. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  50832. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  50833. if ( map.has( name ) === false ) {
  50834. map.set( name, {
  50835. name,
  50836. property,
  50837. type
  50838. } );
  50839. }
  50840. return property;
  50841. }
  50842. /**
  50843. * Returns `true` if the given builtin is defined in the given shader stage.
  50844. *
  50845. * @param {string} name - The builtin name.
  50846. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  50847. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  50848. */
  50849. hasBuiltin( name, shaderStage = this.shaderStage ) {
  50850. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  50851. }
  50852. /**
  50853. * Returns the vertex index builtin.
  50854. *
  50855. * @return {string} The vertex index.
  50856. */
  50857. getVertexIndex() {
  50858. if ( this.shaderStage === 'vertex' ) {
  50859. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  50860. }
  50861. return 'vertexIndex';
  50862. }
  50863. /**
  50864. * Builds the given shader node.
  50865. *
  50866. * @param {ShaderNodeInternal} shaderNode - The shader node.
  50867. * @return {string} The WGSL function code.
  50868. */
  50869. buildFunctionCode( shaderNode ) {
  50870. const layout = shaderNode.layout;
  50871. const flowData = this.flowShaderNode( shaderNode );
  50872. const parameters = [];
  50873. for ( const input of layout.inputs ) {
  50874. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  50875. }
  50876. //
  50877. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  50878. ${ flowData.vars }
  50879. ${ flowData.code }
  50880. `;
  50881. if ( flowData.result ) {
  50882. code += `\treturn ${ flowData.result };\n`;
  50883. }
  50884. code += '\n}\n';
  50885. //
  50886. return code;
  50887. }
  50888. /**
  50889. * Contextually returns either the vertex stage instance index builtin
  50890. * or the linearized index of an compute invocation within a grid of workgroups.
  50891. *
  50892. * @return {string} The instance index.
  50893. */
  50894. getInstanceIndex() {
  50895. if ( this.shaderStage === 'vertex' ) {
  50896. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  50897. }
  50898. return 'instanceIndex';
  50899. }
  50900. /**
  50901. * Returns a builtin representing the index of a compute invocation within the scope of a workgroup load.
  50902. *
  50903. * @return {string} The invocation local index.
  50904. */
  50905. getInvocationLocalIndex() {
  50906. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  50907. }
  50908. /**
  50909. * Returns a builtin representing the size of a subgroup within the current shader.
  50910. *
  50911. * @return {string} The subgroup size.
  50912. */
  50913. getSubgroupSize() {
  50914. this.enableSubGroups();
  50915. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  50916. }
  50917. /**
  50918. * Returns a builtin representing the index of a compute invocation within the scope of a subgroup.
  50919. *
  50920. * @return {string} The invocation subgroup index.
  50921. */
  50922. getInvocationSubgroupIndex() {
  50923. this.enableSubGroups();
  50924. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  50925. }
  50926. /**
  50927. * Returns a builtin representing the index of a compute invocation's subgroup within its workgroup.
  50928. *
  50929. * @return {string} The subgroup index.
  50930. */
  50931. getSubgroupIndex() {
  50932. this.enableSubGroups();
  50933. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  50934. }
  50935. /**
  50936. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  50937. *
  50938. * @return {null} Null.
  50939. */
  50940. getDrawIndex() {
  50941. return null;
  50942. }
  50943. /**
  50944. * Returns the front facing builtin.
  50945. *
  50946. * @return {string} The front facing builtin.
  50947. */
  50948. getFrontFacing() {
  50949. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  50950. }
  50951. /**
  50952. * Returns the frag coord builtin.
  50953. *
  50954. * @return {string} The frag coord builtin.
  50955. */
  50956. getFragCoord() {
  50957. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  50958. }
  50959. /**
  50960. * Returns the frag depth builtin.
  50961. *
  50962. * @return {string} The frag depth builtin.
  50963. */
  50964. getFragDepth() {
  50965. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  50966. }
  50967. /**
  50968. * Returns the clip distances builtin.
  50969. *
  50970. * @return {string} The clip distances builtin.
  50971. */
  50972. getClipDistance() {
  50973. return 'varyings.hw_clip_distances';
  50974. }
  50975. /**
  50976. * Whether to flip texture data along its vertical axis or not.
  50977. *
  50978. * @return {boolean} Returns always `false` in context of WGSL.
  50979. */
  50980. isFlipY() {
  50981. return false;
  50982. }
  50983. /**
  50984. * Enables the given directive for the given shader stage.
  50985. *
  50986. * @param {string} name - The directive name.
  50987. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  50988. */
  50989. enableDirective( name, shaderStage = this.shaderStage ) {
  50990. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  50991. stage.add( name );
  50992. }
  50993. /**
  50994. * Returns the directives of the given shader stage as a WGSL string.
  50995. *
  50996. * @param {string} shaderStage - The shader stage.
  50997. * @return {string} A WGSL snippet that enables the directives of the given stage.
  50998. */
  50999. getDirectives( shaderStage ) {
  51000. const snippets = [];
  51001. const directives = this.directives[ shaderStage ];
  51002. if ( directives !== undefined ) {
  51003. for ( const directive of directives ) {
  51004. snippets.push( `enable ${directive};` );
  51005. }
  51006. }
  51007. return snippets.join( '\n' );
  51008. }
  51009. /**
  51010. * Enables the 'subgroups' directive.
  51011. */
  51012. enableSubGroups() {
  51013. this.enableDirective( 'subgroups' );
  51014. }
  51015. /**
  51016. * Enables the 'subgroups-f16' directive.
  51017. */
  51018. enableSubgroupsF16() {
  51019. this.enableDirective( 'subgroups-f16' );
  51020. }
  51021. /**
  51022. * Enables the 'clip_distances' directive.
  51023. */
  51024. enableClipDistances() {
  51025. this.enableDirective( 'clip_distances' );
  51026. }
  51027. /**
  51028. * Enables the 'f16' directive.
  51029. */
  51030. enableShaderF16() {
  51031. this.enableDirective( 'f16' );
  51032. }
  51033. /**
  51034. * Enables the 'dual_source_blending' directive.
  51035. */
  51036. enableDualSourceBlending() {
  51037. this.enableDirective( 'dual_source_blending' );
  51038. }
  51039. /**
  51040. * Enables hardware clipping.
  51041. *
  51042. * @param {string} planeCount - The clipping plane count.
  51043. */
  51044. enableHardwareClipping( planeCount ) {
  51045. this.enableClipDistances();
  51046. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  51047. }
  51048. /**
  51049. * Returns the builtins of the given shader stage as a WGSL string.
  51050. *
  51051. * @param {string} shaderStage - The shader stage.
  51052. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  51053. */
  51054. getBuiltins( shaderStage ) {
  51055. const snippets = [];
  51056. const builtins = this.builtins[ shaderStage ];
  51057. if ( builtins !== undefined ) {
  51058. for ( const { name, property, type } of builtins.values() ) {
  51059. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  51060. }
  51061. }
  51062. return snippets.join( ',\n\t' );
  51063. }
  51064. /**
  51065. * This method should be used when a new scoped buffer is used in context of
  51066. * compute shaders. It adds the array to the internal data structure which is
  51067. * later used to generate the respective WGSL.
  51068. *
  51069. * @param {string} name - The array name.
  51070. * @param {string} scope - The scope.
  51071. * @param {string} bufferType - The buffer type.
  51072. * @param {string} bufferCount - The buffer count.
  51073. * @return {string} The array name.
  51074. */
  51075. getScopedArray( name, scope, bufferType, bufferCount ) {
  51076. if ( this.scopedArrays.has( name ) === false ) {
  51077. this.scopedArrays.set( name, {
  51078. name,
  51079. scope,
  51080. bufferType,
  51081. bufferCount
  51082. } );
  51083. }
  51084. return name;
  51085. }
  51086. /**
  51087. * Returns the scoped arrays of the given shader stage as a WGSL string.
  51088. *
  51089. * @param {string} shaderStage - The shader stage.
  51090. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  51091. * Returns `undefined` when used in the vertex or fragment stage.
  51092. */
  51093. getScopedArrays( shaderStage ) {
  51094. if ( shaderStage !== 'compute' ) {
  51095. return;
  51096. }
  51097. const snippets = [];
  51098. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  51099. const type = this.getType( bufferType );
  51100. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  51101. }
  51102. return snippets.join( '\n' );
  51103. }
  51104. /**
  51105. * Returns the shader attributes of the given shader stage as a WGSL string.
  51106. *
  51107. * @param {string} shaderStage - The shader stage.
  51108. * @return {string} The WGSL snippet that defines the shader attributes.
  51109. */
  51110. getAttributes( shaderStage ) {
  51111. const snippets = [];
  51112. if ( shaderStage === 'compute' ) {
  51113. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  51114. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  51115. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  51116. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  51117. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  51118. this.enableDirective( 'subgroups', shaderStage );
  51119. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  51120. }
  51121. }
  51122. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  51123. const builtins = this.getBuiltins( 'attribute' );
  51124. if ( builtins ) snippets.push( builtins );
  51125. const attributes = this.getAttributesArray();
  51126. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  51127. const attribute = attributes[ index ];
  51128. const name = attribute.name;
  51129. const type = this.getType( attribute.type );
  51130. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  51131. }
  51132. }
  51133. return snippets.join( ',\n\t' );
  51134. }
  51135. /**
  51136. * Returns the members of the given struct type node as a WGSL string.
  51137. *
  51138. * @param {StructTypeNode} struct - The struct type node.
  51139. * @return {string} The WGSL snippet that defines the struct members.
  51140. */
  51141. getStructMembers( struct ) {
  51142. const snippets = [];
  51143. for ( const member of struct.members ) {
  51144. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  51145. let type = this.getType( member.type );
  51146. if ( member.atomic ) {
  51147. type = 'atomic< ' + type + ' >';
  51148. }
  51149. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  51150. }
  51151. if ( struct.output ) {
  51152. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  51153. }
  51154. return snippets.join( ',\n' );
  51155. }
  51156. /**
  51157. * Returns the structs of the given shader stage as a WGSL string.
  51158. *
  51159. * @param {string} shaderStage - The shader stage.
  51160. * @return {string} The WGSL snippet that defines the structs.
  51161. */
  51162. getStructs( shaderStage ) {
  51163. let result = '';
  51164. const structs = this.structs[ shaderStage ];
  51165. if ( structs.length > 0 ) {
  51166. const snippets = [];
  51167. for ( const struct of structs ) {
  51168. let snippet = `struct ${ struct.name } {\n`;
  51169. snippet += this.getStructMembers( struct );
  51170. snippet += '\n};';
  51171. snippets.push( snippet );
  51172. }
  51173. result = '\n' + snippets.join( '\n\n' ) + '\n';
  51174. }
  51175. return result;
  51176. }
  51177. /**
  51178. * Returns a WGSL string representing a variable.
  51179. *
  51180. * @param {string} type - The variable's type.
  51181. * @param {string} name - The variable's name.
  51182. * @param {?number} [count=null] - The array length.
  51183. * @return {string} The WGSL snippet that defines a variable.
  51184. */
  51185. getVar( type, name, count = null ) {
  51186. let snippet = `var ${ name } : `;
  51187. if ( count !== null ) {
  51188. snippet += this.generateArrayDeclaration( type, count );
  51189. } else {
  51190. snippet += this.getType( type );
  51191. }
  51192. return snippet;
  51193. }
  51194. /**
  51195. * Returns the variables of the given shader stage as a WGSL string.
  51196. *
  51197. * @param {string} shaderStage - The shader stage.
  51198. * @return {string} The WGSL snippet that defines the variables.
  51199. */
  51200. getVars( shaderStage ) {
  51201. const snippets = [];
  51202. const vars = this.vars[ shaderStage ];
  51203. if ( vars !== undefined ) {
  51204. for ( const variable of vars ) {
  51205. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  51206. }
  51207. }
  51208. return `\n${ snippets.join( '\n' ) }\n`;
  51209. }
  51210. /**
  51211. * Returns the varyings of the given shader stage as a WGSL string.
  51212. *
  51213. * @param {string} shaderStage - The shader stage.
  51214. * @return {string} The WGSL snippet that defines the varyings.
  51215. */
  51216. getVaryings( shaderStage ) {
  51217. const snippets = [];
  51218. if ( shaderStage === 'vertex' ) {
  51219. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  51220. }
  51221. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  51222. const varyings = this.varyings;
  51223. const vars = this.vars[ shaderStage ];
  51224. for ( let index = 0; index < varyings.length; index ++ ) {
  51225. const varying = varyings[ index ];
  51226. if ( varying.needsInterpolation ) {
  51227. let attributesSnippet = `@location( ${index} )`;
  51228. if ( varying.interpolationType ) {
  51229. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  51230. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  51231. // Otherwise, optimize interpolation when sensible
  51232. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  51233. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  51234. }
  51235. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  51236. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  51237. vars.push( varying );
  51238. }
  51239. }
  51240. }
  51241. const builtins = this.getBuiltins( shaderStage );
  51242. if ( builtins ) snippets.push( builtins );
  51243. const code = snippets.join( ',\n\t' );
  51244. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  51245. }
  51246. isCustomStruct( nodeUniform ) {
  51247. const attribute = nodeUniform.value;
  51248. const bufferNode = nodeUniform.node;
  51249. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  51250. const isStructArray =
  51251. ( bufferNode.value && bufferNode.value.array ) &&
  51252. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  51253. return isAttributeStructType && ! isStructArray;
  51254. }
  51255. /**
  51256. * Returns the uniforms of the given shader stage as a WGSL string.
  51257. *
  51258. * @param {string} shaderStage - The shader stage.
  51259. * @return {string} The WGSL snippet that defines the uniforms.
  51260. */
  51261. getUniforms( shaderStage ) {
  51262. const uniforms = this.uniforms[ shaderStage ];
  51263. const bindingSnippets = [];
  51264. const bufferSnippets = [];
  51265. const structSnippets = [];
  51266. const uniformGroups = {};
  51267. for ( const uniform of uniforms ) {
  51268. const groupName = uniform.groupNode.name;
  51269. const uniformIndexes = this.bindingsIndexes[ groupName ];
  51270. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  51271. const texture = uniform.node.value;
  51272. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  51273. if ( this.isSampleCompare( texture ) ) {
  51274. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  51275. } else {
  51276. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  51277. }
  51278. }
  51279. let textureType;
  51280. let multisampled = '';
  51281. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  51282. if ( primarySamples > 1 ) {
  51283. multisampled = '_multisampled';
  51284. }
  51285. if ( texture.isCubeTexture === true ) {
  51286. textureType = 'texture_cube<f32>';
  51287. } else if ( texture.isDepthTexture === true ) {
  51288. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  51289. textureType = `texture${ multisampled }_2d<f32>`;
  51290. } else {
  51291. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  51292. }
  51293. } else if ( uniform.node.isStorageTextureNode === true ) {
  51294. const format = getFormat( texture );
  51295. const access = this.getStorageAccess( uniform.node, shaderStage );
  51296. const is3D = uniform.node.value.is3DTexture;
  51297. const isArrayTexture = uniform.node.value.isArrayTexture;
  51298. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  51299. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  51300. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  51301. textureType = 'texture_2d_array<f32>';
  51302. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  51303. textureType = 'texture_3d<f32>';
  51304. } else {
  51305. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  51306. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  51307. }
  51308. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  51309. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  51310. const bufferNode = uniform.node;
  51311. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  51312. const bufferCount = bufferNode.bufferCount;
  51313. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  51314. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  51315. if ( this.isCustomStruct( uniform ) ) {
  51316. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  51317. } else {
  51318. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  51319. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  51320. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  51321. }
  51322. } else {
  51323. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  51324. const groupName = uniform.groupNode.name;
  51325. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  51326. index: uniformIndexes.binding ++,
  51327. id: uniformIndexes.group,
  51328. snippets: []
  51329. } );
  51330. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  51331. }
  51332. }
  51333. for ( const name in uniformGroups ) {
  51334. const group = uniformGroups[ name ];
  51335. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  51336. }
  51337. let code = bindingSnippets.join( '\n' );
  51338. code += bufferSnippets.join( '\n' );
  51339. code += structSnippets.join( '\n' );
  51340. return code;
  51341. }
  51342. /**
  51343. * Controls the code build of the shader stages.
  51344. */
  51345. buildCode() {
  51346. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  51347. this.sortBindingGroups();
  51348. for ( const shaderStage in shadersData ) {
  51349. this.shaderStage = shaderStage;
  51350. const stageData = shadersData[ shaderStage ];
  51351. stageData.uniforms = this.getUniforms( shaderStage );
  51352. stageData.attributes = this.getAttributes( shaderStage );
  51353. stageData.varyings = this.getVaryings( shaderStage );
  51354. stageData.structs = this.getStructs( shaderStage );
  51355. stageData.vars = this.getVars( shaderStage );
  51356. stageData.codes = this.getCodes( shaderStage );
  51357. stageData.directives = this.getDirectives( shaderStage );
  51358. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  51359. //
  51360. let flow = '// code\n\n';
  51361. flow += this.flowCode[ shaderStage ];
  51362. const flowNodes = this.flowNodes[ shaderStage ];
  51363. const mainNode = flowNodes[ flowNodes.length - 1 ];
  51364. const outputNode = mainNode.outputNode;
  51365. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  51366. for ( const node of flowNodes ) {
  51367. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  51368. const slotName = node.name;
  51369. if ( slotName ) {
  51370. if ( flow.length > 0 ) flow += '\n';
  51371. flow += `\t// flow -> ${ slotName }\n`;
  51372. }
  51373. flow += `${ flowSlotData.code }\n\t`;
  51374. if ( node === mainNode && shaderStage !== 'compute' ) {
  51375. flow += '// result\n\n\t';
  51376. if ( shaderStage === 'vertex' ) {
  51377. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  51378. } else if ( shaderStage === 'fragment' ) {
  51379. if ( isOutputStruct ) {
  51380. stageData.returnType = outputNode.getNodeType( this );
  51381. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  51382. flow += `return ${ flowSlotData.result };`;
  51383. } else {
  51384. let structSnippet = '\t@location(0) color: vec4<f32>';
  51385. const builtins = this.getBuiltins( 'output' );
  51386. if ( builtins ) structSnippet += ',\n\t' + builtins;
  51387. stageData.returnType = 'OutputStruct';
  51388. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  51389. stageData.structs += '\nvar<private> output : OutputStruct;';
  51390. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  51391. }
  51392. }
  51393. }
  51394. }
  51395. stageData.flow = flow;
  51396. }
  51397. this.shaderStage = null;
  51398. if ( this.material !== null ) {
  51399. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  51400. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  51401. } else {
  51402. // Early strictly validated in computeNode
  51403. const workgroupSize = this.object.workgroupSize;
  51404. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  51405. }
  51406. }
  51407. /**
  51408. * Returns the native shader method name for a given generic name.
  51409. *
  51410. * @param {string} method - The method name to resolve.
  51411. * @param {?string} [output=null] - An optional output.
  51412. * @return {string} The resolved WGSL method name.
  51413. */
  51414. getMethod( method, output = null ) {
  51415. let wgslMethod;
  51416. if ( output !== null ) {
  51417. wgslMethod = this._getWGSLMethod( method + '_' + output );
  51418. }
  51419. if ( wgslMethod === undefined ) {
  51420. wgslMethod = this._getWGSLMethod( method );
  51421. }
  51422. return wgslMethod || method;
  51423. }
  51424. /**
  51425. * Returns the bitcast method name for a given input and outputType.
  51426. *
  51427. * @param {string} type - The output type to bitcast to.
  51428. * @return {string} The resolved WGSL bitcast invocation.
  51429. */
  51430. getBitcastMethod( type ) {
  51431. const dataType = this.getType( type );
  51432. return `bitcast<${ dataType }>`;
  51433. }
  51434. /**
  51435. * Returns the native snippet for a ternary operation.
  51436. *
  51437. * @param {string} condSnippet - The condition determining which expression gets resolved.
  51438. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  51439. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  51440. * @return {string} The resolved method name.
  51441. */
  51442. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  51443. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  51444. }
  51445. /**
  51446. * Returns the WGSL type of the given node data type.
  51447. *
  51448. * @param {string} type - The node data type.
  51449. * @return {string} The WGSL type.
  51450. */
  51451. getType( type ) {
  51452. return wgslTypeLib[ type ] || type;
  51453. }
  51454. /**
  51455. * Whether the requested feature is available or not.
  51456. *
  51457. * @param {string} name - The requested feature.
  51458. * @return {boolean} Whether the requested feature is supported or not.
  51459. */
  51460. isAvailable( name ) {
  51461. let result = supports[ name ];
  51462. if ( result === undefined ) {
  51463. if ( name === 'float32Filterable' ) {
  51464. result = this.renderer.hasFeature( 'float32-filterable' );
  51465. } else if ( name === 'clipDistance' ) {
  51466. result = this.renderer.hasFeature( 'clip-distances' );
  51467. }
  51468. supports[ name ] = result;
  51469. }
  51470. return result;
  51471. }
  51472. /**
  51473. * Returns the native shader method name for a given generic name.
  51474. *
  51475. * @private
  51476. * @param {string} method - The method name to resolve.
  51477. * @return {string} The resolved WGSL method name.
  51478. */
  51479. _getWGSLMethod( method ) {
  51480. if ( wgslPolyfill[ method ] !== undefined ) {
  51481. this._include( method );
  51482. }
  51483. return wgslMethods[ method ];
  51484. }
  51485. /**
  51486. * Includes the given method name into the current
  51487. * function node.
  51488. *
  51489. * @private
  51490. * @param {string} name - The method name to include.
  51491. * @return {CodeNode} The respective code node.
  51492. */
  51493. _include( name ) {
  51494. const codeNode = wgslPolyfill[ name ];
  51495. codeNode.build( this );
  51496. if ( this.currentFunctionNode !== null ) {
  51497. this.currentFunctionNode.includes.push( codeNode );
  51498. }
  51499. return codeNode;
  51500. }
  51501. /**
  51502. * Returns a WGSL vertex shader based on the given shader data.
  51503. *
  51504. * @private
  51505. * @param {Object} shaderData - The shader data.
  51506. * @return {string} The vertex shader.
  51507. */
  51508. _getWGSLVertexCode( shaderData ) {
  51509. return `${ this.getSignature() }
  51510. // directives
  51511. ${shaderData.directives}
  51512. // structs
  51513. ${shaderData.structs}
  51514. // uniforms
  51515. ${shaderData.uniforms}
  51516. // varyings
  51517. ${shaderData.varyings}
  51518. var<private> varyings : VaryingsStruct;
  51519. // codes
  51520. ${shaderData.codes}
  51521. @vertex
  51522. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  51523. // vars
  51524. ${shaderData.vars}
  51525. // flow
  51526. ${shaderData.flow}
  51527. return varyings;
  51528. }
  51529. `;
  51530. }
  51531. /**
  51532. * Returns a WGSL fragment shader based on the given shader data.
  51533. *
  51534. * @private
  51535. * @param {Object} shaderData - The shader data.
  51536. * @return {string} The vertex shader.
  51537. */
  51538. _getWGSLFragmentCode( shaderData ) {
  51539. return `${ this.getSignature() }
  51540. // global
  51541. ${ diagnostics }
  51542. // structs
  51543. ${shaderData.structs}
  51544. // uniforms
  51545. ${shaderData.uniforms}
  51546. // codes
  51547. ${shaderData.codes}
  51548. @fragment
  51549. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  51550. // vars
  51551. ${shaderData.vars}
  51552. // flow
  51553. ${shaderData.flow}
  51554. }
  51555. `;
  51556. }
  51557. /**
  51558. * Returns a WGSL compute shader based on the given shader data.
  51559. *
  51560. * @private
  51561. * @param {Object} shaderData - The shader data.
  51562. * @param {string} workgroupSize - The workgroup size.
  51563. * @return {string} The vertex shader.
  51564. */
  51565. _getWGSLComputeCode( shaderData, workgroupSize ) {
  51566. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  51567. return `${ this.getSignature() }
  51568. // directives
  51569. ${ shaderData.directives }
  51570. // system
  51571. var<private> instanceIndex : u32;
  51572. // locals
  51573. ${ shaderData.scopedArrays }
  51574. // structs
  51575. ${ shaderData.structs }
  51576. // uniforms
  51577. ${ shaderData.uniforms }
  51578. // codes
  51579. ${ shaderData.codes }
  51580. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  51581. fn main( ${ shaderData.attributes } ) {
  51582. // system
  51583. instanceIndex = globalId.x
  51584. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  51585. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  51586. // vars
  51587. ${ shaderData.vars }
  51588. // flow
  51589. ${ shaderData.flow }
  51590. }
  51591. `;
  51592. }
  51593. /**
  51594. * Returns a WGSL struct based on the given name and variables.
  51595. *
  51596. * @private
  51597. * @param {string} name - The struct name.
  51598. * @param {string} vars - The struct variables.
  51599. * @return {string} The WGSL snippet representing a struct.
  51600. */
  51601. _getWGSLStruct( name, vars ) {
  51602. return `
  51603. struct ${name} {
  51604. ${vars}
  51605. };`;
  51606. }
  51607. /**
  51608. * Returns a WGSL struct binding.
  51609. *
  51610. * @private
  51611. * @param {string} name - The struct name.
  51612. * @param {string} vars - The struct variables.
  51613. * @param {string} access - The access.
  51614. * @param {number} [binding=0] - The binding index.
  51615. * @param {number} [group=0] - The group index.
  51616. * @return {string} The WGSL snippet representing a struct binding.
  51617. */
  51618. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  51619. const structName = name + 'Struct';
  51620. const structSnippet = this._getWGSLStruct( structName, vars );
  51621. return `${structSnippet}
  51622. @binding( ${ binding } ) @group( ${ group } )
  51623. var<${access}> ${ name } : ${ structName };`;
  51624. }
  51625. }
  51626. /**
  51627. * A WebGPU backend utility module with common helpers.
  51628. *
  51629. * @private
  51630. */
  51631. class WebGPUUtils {
  51632. /**
  51633. * Constructs a new utility object.
  51634. *
  51635. * @param {WebGPUBackend} backend - The WebGPU backend.
  51636. */
  51637. constructor( backend ) {
  51638. /**
  51639. * A reference to the WebGPU backend.
  51640. *
  51641. * @type {WebGPUBackend}
  51642. */
  51643. this.backend = backend;
  51644. }
  51645. /**
  51646. * Returns the depth/stencil GPU format for the given render context.
  51647. *
  51648. * @param {RenderContext} renderContext - The render context.
  51649. * @return {string} The depth/stencil GPU texture format.
  51650. */
  51651. getCurrentDepthStencilFormat( renderContext ) {
  51652. let format;
  51653. if ( renderContext.depthTexture !== null ) {
  51654. format = this.getTextureFormatGPU( renderContext.depthTexture );
  51655. } else if ( renderContext.depth && renderContext.stencil ) {
  51656. format = GPUTextureFormat.Depth24PlusStencil8;
  51657. } else if ( renderContext.depth ) {
  51658. format = GPUTextureFormat.Depth24Plus;
  51659. }
  51660. return format;
  51661. }
  51662. /**
  51663. * Returns the GPU format for the given texture.
  51664. *
  51665. * @param {Texture} texture - The texture.
  51666. * @return {string} The GPU texture format.
  51667. */
  51668. getTextureFormatGPU( texture ) {
  51669. return this.backend.get( texture ).format;
  51670. }
  51671. /**
  51672. * Returns an object that defines the multi-sampling state of the given texture.
  51673. *
  51674. * @param {Texture} texture - The texture.
  51675. * @return {Object} The multi-sampling state.
  51676. */
  51677. getTextureSampleData( texture ) {
  51678. let samples;
  51679. if ( texture.isFramebufferTexture ) {
  51680. samples = 1;
  51681. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  51682. const renderer = this.backend.renderer;
  51683. const renderTarget = renderer.getRenderTarget();
  51684. samples = renderTarget ? renderTarget.samples : renderer.currentSamples;
  51685. } else if ( texture.renderTarget ) {
  51686. samples = texture.renderTarget.samples;
  51687. }
  51688. samples = samples || 1;
  51689. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  51690. const primarySamples = isMSAA ? 1 : samples;
  51691. return { samples, primarySamples, isMSAA };
  51692. }
  51693. /**
  51694. * Returns the default color attachment's GPU format of the current render context.
  51695. *
  51696. * @param {RenderContext} renderContext - The render context.
  51697. * @return {string} The GPU texture format of the default color attachment.
  51698. */
  51699. getCurrentColorFormat( renderContext ) {
  51700. let format;
  51701. if ( renderContext.textures !== null ) {
  51702. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  51703. } else {
  51704. format = this.getPreferredCanvasFormat(); // default context format
  51705. }
  51706. return format;
  51707. }
  51708. /**
  51709. * Returns the GPU formats of all color attachments of the current render context.
  51710. *
  51711. * @param {RenderContext} renderContext - The render context.
  51712. * @return {Array<string>} The GPU texture formats of all color attachments.
  51713. */
  51714. getCurrentColorFormats( renderContext ) {
  51715. if ( renderContext.textures !== null ) {
  51716. return renderContext.textures.map( t => this.getTextureFormatGPU( t ) );
  51717. } else {
  51718. return [ this.getPreferredCanvasFormat() ]; // default context format
  51719. }
  51720. }
  51721. /**
  51722. * Returns the output color space of the current render context.
  51723. *
  51724. * @param {RenderContext} renderContext - The render context.
  51725. * @return {string} The output color space.
  51726. */
  51727. getCurrentColorSpace( renderContext ) {
  51728. if ( renderContext.textures !== null ) {
  51729. return renderContext.textures[ 0 ].colorSpace;
  51730. }
  51731. return this.backend.renderer.outputColorSpace;
  51732. }
  51733. /**
  51734. * Returns GPU primitive topology for the given object and material.
  51735. *
  51736. * @param {Object3D} object - The 3D object.
  51737. * @param {Material} material - The material.
  51738. * @return {string} The GPU primitive topology.
  51739. */
  51740. getPrimitiveTopology( object, material ) {
  51741. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  51742. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  51743. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  51744. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  51745. }
  51746. /**
  51747. * Returns a modified sample count from the given sample count value.
  51748. *
  51749. * That is required since WebGPU only supports either 1 or 4.
  51750. *
  51751. * @param {number} sampleCount - The input sample count.
  51752. * @return {number} The (potentially updated) output sample count.
  51753. */
  51754. getSampleCount( sampleCount ) {
  51755. return sampleCount >= 4 ? 4 : 1;
  51756. }
  51757. /**
  51758. * Returns the sample count of the given render context.
  51759. *
  51760. * @param {RenderContext} renderContext - The render context.
  51761. * @return {number} The sample count.
  51762. */
  51763. getSampleCountRenderContext( renderContext ) {
  51764. if ( renderContext.textures !== null ) {
  51765. return this.getSampleCount( renderContext.sampleCount );
  51766. }
  51767. return this.getSampleCount( this.backend.renderer.currentSamples );
  51768. }
  51769. /**
  51770. * Returns the preferred canvas format.
  51771. *
  51772. * There is a separate method for this so it's possible to
  51773. * honor edge cases for specific devices.
  51774. *
  51775. * @return {string} The GPU texture format of the canvas.
  51776. */
  51777. getPreferredCanvasFormat() {
  51778. const outputType = this.backend.parameters.outputType;
  51779. if ( outputType === undefined ) {
  51780. return navigator.gpu.getPreferredCanvasFormat();
  51781. } else if ( outputType === UnsignedByteType ) {
  51782. return GPUTextureFormat.BGRA8Unorm;
  51783. } else if ( outputType === HalfFloatType ) {
  51784. return GPUTextureFormat.RGBA16Float;
  51785. } else {
  51786. throw new Error( 'Unsupported outputType' );
  51787. }
  51788. }
  51789. }
  51790. const typedArraysToVertexFormatPrefix = new Map( [
  51791. [ Int8Array, [ 'sint8', 'snorm8' ]],
  51792. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  51793. [ Int16Array, [ 'sint16', 'snorm16' ]],
  51794. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  51795. [ Int32Array, [ 'sint32', 'snorm32' ]],
  51796. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  51797. [ Float32Array, [ 'float32', ]],
  51798. ] );
  51799. if ( typeof Float16Array !== 'undefined' ) {
  51800. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  51801. }
  51802. const typedAttributeToVertexFormatPrefix = new Map( [
  51803. [ Float16BufferAttribute, [ 'float16', ]],
  51804. ] );
  51805. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  51806. [ Int32Array, 'sint32' ],
  51807. [ Int16Array, 'sint32' ], // patch for INT16
  51808. [ Uint32Array, 'uint32' ],
  51809. [ Uint16Array, 'uint32' ], // patch for UINT16
  51810. [ Float32Array, 'float32' ]
  51811. ] );
  51812. /**
  51813. * A WebGPU backend utility module for managing shader attributes.
  51814. *
  51815. * @private
  51816. */
  51817. class WebGPUAttributeUtils {
  51818. /**
  51819. * Constructs a new utility object.
  51820. *
  51821. * @param {WebGPUBackend} backend - The WebGPU backend.
  51822. */
  51823. constructor( backend ) {
  51824. /**
  51825. * A reference to the WebGPU backend.
  51826. *
  51827. * @type {WebGPUBackend}
  51828. */
  51829. this.backend = backend;
  51830. }
  51831. /**
  51832. * Creates the GPU buffer for the given buffer attribute.
  51833. *
  51834. * @param {BufferAttribute} attribute - The buffer attribute.
  51835. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  51836. */
  51837. createAttribute( attribute, usage ) {
  51838. const bufferAttribute = this._getBufferAttribute( attribute );
  51839. const backend = this.backend;
  51840. const bufferData = backend.get( bufferAttribute );
  51841. let buffer = bufferData.buffer;
  51842. if ( buffer === undefined ) {
  51843. const device = backend.device;
  51844. let array = bufferAttribute.array;
  51845. // patch for INT16 and UINT16
  51846. if ( attribute.normalized === false ) {
  51847. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  51848. array = new Int32Array( array );
  51849. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  51850. array = new Uint32Array( array );
  51851. if ( usage & GPUBufferUsage.INDEX ) {
  51852. for ( let i = 0; i < array.length; i ++ ) {
  51853. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  51854. }
  51855. }
  51856. }
  51857. }
  51858. bufferAttribute.array = array;
  51859. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  51860. array = new array.constructor( bufferAttribute.count * 4 );
  51861. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  51862. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  51863. }
  51864. // Update BufferAttribute
  51865. bufferAttribute.itemSize = 4;
  51866. bufferAttribute.array = array;
  51867. bufferData._force3to4BytesAlignment = true;
  51868. }
  51869. // ensure 4 byte alignment
  51870. const byteLength = array.byteLength;
  51871. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  51872. buffer = device.createBuffer( {
  51873. label: bufferAttribute.name,
  51874. size: size,
  51875. usage: usage,
  51876. mappedAtCreation: true
  51877. } );
  51878. new array.constructor( buffer.getMappedRange() ).set( array );
  51879. buffer.unmap();
  51880. bufferData.buffer = buffer;
  51881. }
  51882. }
  51883. /**
  51884. * Updates the GPU buffer of the given buffer attribute.
  51885. *
  51886. * @param {BufferAttribute} attribute - The buffer attribute.
  51887. */
  51888. updateAttribute( attribute ) {
  51889. const bufferAttribute = this._getBufferAttribute( attribute );
  51890. const backend = this.backend;
  51891. const device = backend.device;
  51892. const bufferData = backend.get( bufferAttribute );
  51893. const buffer = backend.get( bufferAttribute ).buffer;
  51894. let array = bufferAttribute.array;
  51895. // if storage buffer ensure 4 byte alignment
  51896. if ( bufferData._force3to4BytesAlignment === true ) {
  51897. array = new array.constructor( bufferAttribute.count * 4 );
  51898. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  51899. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  51900. }
  51901. bufferAttribute.array = array;
  51902. }
  51903. const isTypedArray = this._isTypedArray( array );
  51904. const updateRanges = bufferAttribute.updateRanges;
  51905. if ( updateRanges.length === 0 ) {
  51906. // Not using update ranges
  51907. device.queue.writeBuffer(
  51908. buffer,
  51909. 0,
  51910. array,
  51911. 0
  51912. );
  51913. } else {
  51914. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  51915. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  51916. const range = updateRanges[ i ];
  51917. let dataOffset, size;
  51918. if ( bufferData._force3to4BytesAlignment === true ) {
  51919. const vertexStart = Math.floor( range.start / 3 );
  51920. const vertexCount = Math.ceil( range.count / 3 );
  51921. dataOffset = vertexStart * 4 * byteOffsetFactor;
  51922. size = vertexCount * 4 * byteOffsetFactor;
  51923. } else {
  51924. dataOffset = range.start * byteOffsetFactor;
  51925. size = range.count * byteOffsetFactor;
  51926. }
  51927. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  51928. device.queue.writeBuffer(
  51929. buffer,
  51930. bufferOffset,
  51931. array,
  51932. dataOffset,
  51933. size
  51934. );
  51935. }
  51936. bufferAttribute.clearUpdateRanges();
  51937. }
  51938. }
  51939. /**
  51940. * This method creates the vertex buffer layout data which are
  51941. * require when creating a render pipeline for the given render object.
  51942. *
  51943. * @param {RenderObject} renderObject - The render object.
  51944. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  51945. */
  51946. createShaderVertexBuffers( renderObject ) {
  51947. const attributes = renderObject.getAttributes();
  51948. const vertexBuffers = new Map();
  51949. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  51950. const geometryAttribute = attributes[ slot ];
  51951. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  51952. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  51953. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  51954. if ( vertexBufferLayout === undefined ) {
  51955. let arrayStride, stepMode;
  51956. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  51957. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  51958. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  51959. } else {
  51960. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  51961. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  51962. }
  51963. // patch for INT16 and UINT16
  51964. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  51965. arrayStride = 4;
  51966. }
  51967. vertexBufferLayout = {
  51968. arrayStride,
  51969. attributes: [],
  51970. stepMode
  51971. };
  51972. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  51973. }
  51974. const format = this._getVertexFormat( geometryAttribute );
  51975. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  51976. vertexBufferLayout.attributes.push( {
  51977. shaderLocation: slot,
  51978. offset,
  51979. format
  51980. } );
  51981. }
  51982. return Array.from( vertexBuffers.values() );
  51983. }
  51984. /**
  51985. * Destroys the GPU buffer of the given buffer attribute.
  51986. *
  51987. * @param {BufferAttribute} attribute - The buffer attribute.
  51988. */
  51989. destroyAttribute( attribute ) {
  51990. const backend = this.backend;
  51991. const data = backend.get( this._getBufferAttribute( attribute ) );
  51992. data.buffer.destroy();
  51993. backend.delete( attribute );
  51994. }
  51995. /**
  51996. * This method performs a readback operation by moving buffer data from
  51997. * a storage buffer attribute from the GPU to the CPU.
  51998. *
  51999. * @async
  52000. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  52001. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  52002. */
  52003. async getArrayBufferAsync( attribute ) {
  52004. const backend = this.backend;
  52005. const device = backend.device;
  52006. const data = backend.get( this._getBufferAttribute( attribute ) );
  52007. const bufferGPU = data.buffer;
  52008. const size = bufferGPU.size;
  52009. const readBufferGPU = device.createBuffer( {
  52010. label: `${ attribute.name }_readback`,
  52011. size,
  52012. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52013. } );
  52014. const cmdEncoder = device.createCommandEncoder( {
  52015. label: `readback_encoder_${ attribute.name }`
  52016. } );
  52017. cmdEncoder.copyBufferToBuffer(
  52018. bufferGPU,
  52019. 0,
  52020. readBufferGPU,
  52021. 0,
  52022. size
  52023. );
  52024. const gpuCommands = cmdEncoder.finish();
  52025. device.queue.submit( [ gpuCommands ] );
  52026. await readBufferGPU.mapAsync( GPUMapMode.READ );
  52027. const arrayBuffer = readBufferGPU.getMappedRange();
  52028. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  52029. readBufferGPU.unmap();
  52030. return dstBuffer.buffer;
  52031. }
  52032. /**
  52033. * Returns the vertex format of the given buffer attribute.
  52034. *
  52035. * @private
  52036. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  52037. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  52038. */
  52039. _getVertexFormat( geometryAttribute ) {
  52040. const { itemSize, normalized } = geometryAttribute;
  52041. const ArrayType = geometryAttribute.array.constructor;
  52042. const AttributeType = geometryAttribute.constructor;
  52043. let format;
  52044. if ( itemSize === 1 ) {
  52045. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  52046. } else {
  52047. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  52048. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  52049. if ( prefix ) {
  52050. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  52051. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  52052. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  52053. if ( paddedItemSize % 1 ) {
  52054. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  52055. }
  52056. format = `${prefix}x${paddedItemSize}`;
  52057. }
  52058. }
  52059. if ( ! format ) {
  52060. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  52061. }
  52062. return format;
  52063. }
  52064. /**
  52065. * Returns `true` if the given array is a typed array.
  52066. *
  52067. * @private
  52068. * @param {any} array - The array.
  52069. * @return {boolean} Whether the given array is a typed array or not.
  52070. */
  52071. _isTypedArray( array ) {
  52072. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  52073. }
  52074. /**
  52075. * Utility method for handling interleaved buffer attributes correctly.
  52076. * To process them, their `InterleavedBuffer` is returned.
  52077. *
  52078. * @private
  52079. * @param {BufferAttribute} attribute - The attribute.
  52080. * @return {BufferAttribute|InterleavedBuffer}
  52081. */
  52082. _getBufferAttribute( attribute ) {
  52083. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  52084. return attribute;
  52085. }
  52086. }
  52087. /**
  52088. * A WebGPU backend utility module for managing bindings.
  52089. *
  52090. * When reading the documentation it's helpful to keep in mind that
  52091. * all class definitions starting with 'GPU*' are modules from the
  52092. * WebGPU API. So for example `BindGroup` is a class from the engine
  52093. * whereas `GPUBindGroup` is a class from WebGPU.
  52094. *
  52095. * @private
  52096. */
  52097. class WebGPUBindingUtils {
  52098. /**
  52099. * Constructs a new utility object.
  52100. *
  52101. * @param {WebGPUBackend} backend - The WebGPU backend.
  52102. */
  52103. constructor( backend ) {
  52104. /**
  52105. * A reference to the WebGPU backend.
  52106. *
  52107. * @type {WebGPUBackend}
  52108. */
  52109. this.backend = backend;
  52110. /**
  52111. * A cache for managing bind group layouts.
  52112. *
  52113. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  52114. */
  52115. this.bindGroupLayoutCache = new WeakMap();
  52116. }
  52117. /**
  52118. * Creates a GPU bind group layout for the given bind group.
  52119. *
  52120. * @param {BindGroup} bindGroup - The bind group.
  52121. * @return {GPUBindGroupLayout} The GPU bind group layout.
  52122. */
  52123. createBindingsLayout( bindGroup ) {
  52124. const backend = this.backend;
  52125. const device = backend.device;
  52126. const entries = [];
  52127. let index = 0;
  52128. for ( const binding of bindGroup.bindings ) {
  52129. const bindingGPU = {
  52130. binding: index ++,
  52131. visibility: binding.visibility
  52132. };
  52133. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  52134. const buffer = {}; // GPUBufferBindingLayout
  52135. if ( binding.isStorageBuffer ) {
  52136. if ( binding.visibility & 4 ) {
  52137. // compute
  52138. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  52139. buffer.type = GPUBufferBindingType.Storage;
  52140. } else {
  52141. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52142. }
  52143. } else {
  52144. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  52145. }
  52146. }
  52147. bindingGPU.buffer = buffer;
  52148. } else if ( binding.isSampledTexture && binding.store ) {
  52149. const storageTexture = {}; // GPUStorageTextureBindingLayout
  52150. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  52151. const access = binding.access;
  52152. if ( access === NodeAccess.READ_WRITE ) {
  52153. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  52154. } else if ( access === NodeAccess.WRITE_ONLY ) {
  52155. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  52156. } else {
  52157. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  52158. }
  52159. if ( binding.texture.isArrayTexture ) {
  52160. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52161. } else if ( binding.texture.is3DTexture ) {
  52162. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  52163. }
  52164. bindingGPU.storageTexture = storageTexture;
  52165. } else if ( binding.isSampledTexture ) {
  52166. const texture = {}; // GPUTextureBindingLayout
  52167. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  52168. if ( primarySamples > 1 ) {
  52169. texture.multisampled = true;
  52170. if ( ! binding.texture.isDepthTexture ) {
  52171. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52172. }
  52173. }
  52174. if ( binding.texture.isDepthTexture ) {
  52175. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  52176. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52177. } else {
  52178. texture.sampleType = GPUTextureSampleType.Depth;
  52179. }
  52180. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  52181. const type = binding.texture.type;
  52182. if ( type === IntType ) {
  52183. texture.sampleType = GPUTextureSampleType.SInt;
  52184. } else if ( type === UnsignedIntType ) {
  52185. texture.sampleType = GPUTextureSampleType.UInt;
  52186. } else if ( type === FloatType ) {
  52187. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  52188. texture.sampleType = GPUTextureSampleType.Float;
  52189. } else {
  52190. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  52191. }
  52192. }
  52193. }
  52194. if ( binding.isSampledCubeTexture ) {
  52195. texture.viewDimension = GPUTextureViewDimension.Cube;
  52196. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52197. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  52198. } else if ( binding.isSampledTexture3D ) {
  52199. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  52200. }
  52201. bindingGPU.texture = texture;
  52202. } else if ( binding.isSampler ) {
  52203. const sampler = {}; // GPUSamplerBindingLayout
  52204. if ( binding.texture.isDepthTexture ) {
  52205. if ( binding.texture.compareFunction !== null ) {
  52206. sampler.type = GPUSamplerBindingType.Comparison;
  52207. } else if ( backend.compatibilityMode ) {
  52208. sampler.type = GPUSamplerBindingType.NonFiltering;
  52209. }
  52210. }
  52211. bindingGPU.sampler = sampler;
  52212. } else {
  52213. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  52214. }
  52215. entries.push( bindingGPU );
  52216. }
  52217. return device.createBindGroupLayout( { entries } );
  52218. }
  52219. /**
  52220. * Creates bindings from the given bind group definition.
  52221. *
  52222. * @param {BindGroup} bindGroup - The bind group.
  52223. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52224. * @param {number} cacheIndex - The cache index.
  52225. * @param {number} version - The version.
  52226. */
  52227. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  52228. const { backend, bindGroupLayoutCache } = this;
  52229. const bindingsData = backend.get( bindGroup );
  52230. // setup (static) binding layout and (dynamic) binding group
  52231. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  52232. if ( bindLayoutGPU === undefined ) {
  52233. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  52234. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  52235. }
  52236. let bindGroupGPU;
  52237. if ( cacheIndex > 0 ) {
  52238. if ( bindingsData.groups === undefined ) {
  52239. bindingsData.groups = [];
  52240. bindingsData.versions = [];
  52241. }
  52242. if ( bindingsData.versions[ cacheIndex ] === version ) {
  52243. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  52244. }
  52245. }
  52246. if ( bindGroupGPU === undefined ) {
  52247. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  52248. if ( cacheIndex > 0 ) {
  52249. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  52250. bindingsData.versions[ cacheIndex ] = version;
  52251. }
  52252. }
  52253. bindingsData.group = bindGroupGPU;
  52254. bindingsData.layout = bindLayoutGPU;
  52255. }
  52256. /**
  52257. * Updates a buffer binding.
  52258. *
  52259. * @param {Buffer} binding - The buffer binding to update.
  52260. */
  52261. updateBinding( binding ) {
  52262. const backend = this.backend;
  52263. const device = backend.device;
  52264. const buffer = binding.buffer;
  52265. const bufferGPU = backend.get( binding ).buffer;
  52266. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  52267. }
  52268. /**
  52269. * Creates a GPU bind group for the camera index.
  52270. *
  52271. * @param {Uint32Array} data - The index data.
  52272. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  52273. * @return {GPUBindGroup} The GPU bind group.
  52274. */
  52275. createBindGroupIndex( data, layout ) {
  52276. const backend = this.backend;
  52277. const device = backend.device;
  52278. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52279. const index = data[ 0 ];
  52280. const buffer = device.createBuffer( {
  52281. label: 'bindingCameraIndex_' + index,
  52282. size: 16, // uint(4) * 4
  52283. usage: usage
  52284. } );
  52285. device.queue.writeBuffer( buffer, 0, data, 0 );
  52286. const entries = [ { binding: 0, resource: { buffer } } ];
  52287. return device.createBindGroup( {
  52288. label: 'bindGroupCameraIndex_' + index,
  52289. layout,
  52290. entries
  52291. } );
  52292. }
  52293. /**
  52294. * Creates a GPU bind group for the given bind group and GPU layout.
  52295. *
  52296. * @param {BindGroup} bindGroup - The bind group.
  52297. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  52298. * @return {GPUBindGroup} The GPU bind group.
  52299. */
  52300. createBindGroup( bindGroup, layoutGPU ) {
  52301. const backend = this.backend;
  52302. const device = backend.device;
  52303. let bindingPoint = 0;
  52304. const entriesGPU = [];
  52305. for ( const binding of bindGroup.bindings ) {
  52306. if ( binding.isUniformBuffer ) {
  52307. const bindingData = backend.get( binding );
  52308. if ( bindingData.buffer === undefined ) {
  52309. const byteLength = binding.byteLength;
  52310. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  52311. const bufferGPU = device.createBuffer( {
  52312. label: 'bindingBuffer_' + binding.name,
  52313. size: byteLength,
  52314. usage: usage
  52315. } );
  52316. bindingData.buffer = bufferGPU;
  52317. }
  52318. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52319. } else if ( binding.isStorageBuffer ) {
  52320. const bindingData = backend.get( binding );
  52321. if ( bindingData.buffer === undefined ) {
  52322. const attribute = binding.attribute;
  52323. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  52324. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  52325. bindingData.buffer = backend.get( attribute ).buffer;
  52326. }
  52327. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  52328. } else if ( binding.isSampledTexture ) {
  52329. const textureData = backend.get( binding.texture );
  52330. let resourceGPU;
  52331. if ( textureData.externalTexture !== undefined ) {
  52332. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  52333. } else {
  52334. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  52335. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  52336. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  52337. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  52338. }
  52339. propertyName += `-${ mipLevelCount }`;
  52340. resourceGPU = textureData[ propertyName ];
  52341. if ( resourceGPU === undefined ) {
  52342. const aspectGPU = GPUTextureAspect.All;
  52343. let dimensionViewGPU;
  52344. if ( binding.isSampledCubeTexture ) {
  52345. dimensionViewGPU = GPUTextureViewDimension.Cube;
  52346. } else if ( binding.isSampledTexture3D ) {
  52347. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  52348. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  52349. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  52350. } else {
  52351. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  52352. }
  52353. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  52354. }
  52355. }
  52356. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  52357. } else if ( binding.isSampler ) {
  52358. const textureGPU = backend.get( binding.texture );
  52359. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  52360. }
  52361. bindingPoint ++;
  52362. }
  52363. return device.createBindGroup( {
  52364. label: 'bindGroup_' + bindGroup.name,
  52365. layout: layoutGPU,
  52366. entries: entriesGPU
  52367. } );
  52368. }
  52369. }
  52370. /**
  52371. * A WebGPU backend utility module for managing pipelines.
  52372. *
  52373. * @private
  52374. */
  52375. class WebGPUPipelineUtils {
  52376. /**
  52377. * Constructs a new utility object.
  52378. *
  52379. * @param {WebGPUBackend} backend - The WebGPU backend.
  52380. */
  52381. constructor( backend ) {
  52382. /**
  52383. * A reference to the WebGPU backend.
  52384. *
  52385. * @type {WebGPUBackend}
  52386. */
  52387. this.backend = backend;
  52388. /**
  52389. * A Weak Map that tracks the active pipeline for render or compute passes.
  52390. *
  52391. * @private
  52392. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  52393. */
  52394. this._activePipelines = new WeakMap();
  52395. }
  52396. /**
  52397. * Sets the given pipeline for the given pass. The method makes sure to only set the
  52398. * pipeline when necessary.
  52399. *
  52400. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  52401. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  52402. */
  52403. setPipeline( pass, pipeline ) {
  52404. const currentPipeline = this._activePipelines.get( pass );
  52405. if ( currentPipeline !== pipeline ) {
  52406. pass.setPipeline( pipeline );
  52407. this._activePipelines.set( pass, pipeline );
  52408. }
  52409. }
  52410. /**
  52411. * Returns the sample count derived from the given render context.
  52412. *
  52413. * @private
  52414. * @param {RenderContext} renderContext - The render context.
  52415. * @return {number} The sample count.
  52416. */
  52417. _getSampleCount( renderContext ) {
  52418. return this.backend.utils.getSampleCountRenderContext( renderContext );
  52419. }
  52420. /**
  52421. * Creates a render pipeline for the given render object.
  52422. *
  52423. * @param {RenderObject} renderObject - The render object.
  52424. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  52425. */
  52426. createRenderPipeline( renderObject, promises ) {
  52427. const { object, material, geometry, pipeline } = renderObject;
  52428. const { vertexProgram, fragmentProgram } = pipeline;
  52429. const backend = this.backend;
  52430. const device = backend.device;
  52431. const utils = backend.utils;
  52432. const pipelineData = backend.get( pipeline );
  52433. // bind group layouts
  52434. const bindGroupLayouts = [];
  52435. for ( const bindGroup of renderObject.getBindings() ) {
  52436. const bindingsData = backend.get( bindGroup );
  52437. bindGroupLayouts.push( bindingsData.layout );
  52438. }
  52439. // vertex buffers
  52440. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  52441. // blending
  52442. let blending;
  52443. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  52444. blending = this._getBlending( material );
  52445. }
  52446. // stencil
  52447. let stencilFront = {};
  52448. if ( material.stencilWrite === true ) {
  52449. stencilFront = {
  52450. compare: this._getStencilCompare( material ),
  52451. failOp: this._getStencilOperation( material.stencilFail ),
  52452. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  52453. passOp: this._getStencilOperation( material.stencilZPass )
  52454. };
  52455. }
  52456. const colorWriteMask = this._getColorWriteMask( material );
  52457. const targets = [];
  52458. if ( renderObject.context.textures !== null ) {
  52459. const textures = renderObject.context.textures;
  52460. for ( let i = 0; i < textures.length; i ++ ) {
  52461. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  52462. targets.push( {
  52463. format: colorFormat,
  52464. blend: blending,
  52465. writeMask: colorWriteMask
  52466. } );
  52467. }
  52468. } else {
  52469. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  52470. targets.push( {
  52471. format: colorFormat,
  52472. blend: blending,
  52473. writeMask: colorWriteMask
  52474. } );
  52475. }
  52476. const vertexModule = backend.get( vertexProgram ).module;
  52477. const fragmentModule = backend.get( fragmentProgram ).module;
  52478. const primitiveState = this._getPrimitiveState( object, geometry, material );
  52479. const depthCompare = this._getDepthCompare( material );
  52480. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  52481. const sampleCount = this._getSampleCount( renderObject.context );
  52482. const pipelineDescriptor = {
  52483. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  52484. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  52485. fragment: Object.assign( {}, fragmentModule, { targets } ),
  52486. primitive: primitiveState,
  52487. multisample: {
  52488. count: sampleCount,
  52489. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  52490. },
  52491. layout: device.createPipelineLayout( {
  52492. bindGroupLayouts
  52493. } )
  52494. };
  52495. const depthStencil = {};
  52496. const renderDepth = renderObject.context.depth;
  52497. const renderStencil = renderObject.context.stencil;
  52498. if ( renderDepth === true || renderStencil === true ) {
  52499. if ( renderDepth === true ) {
  52500. depthStencil.format = depthStencilFormat;
  52501. depthStencil.depthWriteEnabled = material.depthWrite;
  52502. depthStencil.depthCompare = depthCompare;
  52503. }
  52504. if ( renderStencil === true ) {
  52505. depthStencil.stencilFront = stencilFront;
  52506. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  52507. depthStencil.stencilReadMask = material.stencilFuncMask;
  52508. depthStencil.stencilWriteMask = material.stencilWriteMask;
  52509. }
  52510. if ( material.polygonOffset === true ) {
  52511. depthStencil.depthBias = material.polygonOffsetUnits;
  52512. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  52513. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  52514. }
  52515. pipelineDescriptor.depthStencil = depthStencil;
  52516. }
  52517. if ( promises === null ) {
  52518. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  52519. } else {
  52520. const p = new Promise( ( resolve /*, reject*/ ) => {
  52521. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  52522. pipelineData.pipeline = pipeline;
  52523. resolve();
  52524. } );
  52525. } );
  52526. promises.push( p );
  52527. }
  52528. }
  52529. /**
  52530. * Creates GPU render bundle encoder for the given render context.
  52531. *
  52532. * @param {RenderContext} renderContext - The render context.
  52533. * @param {?string} [label='renderBundleEncoder'] - The label.
  52534. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  52535. */
  52536. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  52537. const backend = this.backend;
  52538. const { utils, device } = backend;
  52539. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  52540. const colorFormats = utils.getCurrentColorFormats( renderContext );
  52541. const sampleCount = this._getSampleCount( renderContext );
  52542. const descriptor = {
  52543. label,
  52544. colorFormats,
  52545. depthStencilFormat,
  52546. sampleCount
  52547. };
  52548. return device.createRenderBundleEncoder( descriptor );
  52549. }
  52550. /**
  52551. * Creates a compute pipeline for the given compute node.
  52552. *
  52553. * @param {ComputePipeline} pipeline - The compute pipeline.
  52554. * @param {Array<BindGroup>} bindings - The bindings.
  52555. */
  52556. createComputePipeline( pipeline, bindings ) {
  52557. const backend = this.backend;
  52558. const device = backend.device;
  52559. const computeProgram = backend.get( pipeline.computeProgram ).module;
  52560. const pipelineGPU = backend.get( pipeline );
  52561. // bind group layouts
  52562. const bindGroupLayouts = [];
  52563. for ( const bindingsGroup of bindings ) {
  52564. const bindingsData = backend.get( bindingsGroup );
  52565. bindGroupLayouts.push( bindingsData.layout );
  52566. }
  52567. pipelineGPU.pipeline = device.createComputePipeline( {
  52568. compute: computeProgram,
  52569. layout: device.createPipelineLayout( {
  52570. bindGroupLayouts
  52571. } )
  52572. } );
  52573. }
  52574. /**
  52575. * Returns the blending state as a descriptor object required
  52576. * for the pipeline creation.
  52577. *
  52578. * @private
  52579. * @param {Material} material - The material.
  52580. * @return {Object} The blending state.
  52581. */
  52582. _getBlending( material ) {
  52583. let color, alpha;
  52584. const blending = material.blending;
  52585. const blendSrc = material.blendSrc;
  52586. const blendDst = material.blendDst;
  52587. const blendEquation = material.blendEquation;
  52588. if ( blending === CustomBlending ) {
  52589. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  52590. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  52591. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  52592. color = {
  52593. srcFactor: this._getBlendFactor( blendSrc ),
  52594. dstFactor: this._getBlendFactor( blendDst ),
  52595. operation: this._getBlendOperation( blendEquation )
  52596. };
  52597. alpha = {
  52598. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  52599. dstFactor: this._getBlendFactor( blendDstAlpha ),
  52600. operation: this._getBlendOperation( blendEquationAlpha )
  52601. };
  52602. } else {
  52603. const premultipliedAlpha = material.premultipliedAlpha;
  52604. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  52605. color = {
  52606. srcFactor: srcRGB,
  52607. dstFactor: dstRGB,
  52608. operation: GPUBlendOperation.Add
  52609. };
  52610. alpha = {
  52611. srcFactor: srcAlpha,
  52612. dstFactor: dstAlpha,
  52613. operation: GPUBlendOperation.Add
  52614. };
  52615. };
  52616. if ( premultipliedAlpha ) {
  52617. switch ( blending ) {
  52618. case NormalBlending:
  52619. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  52620. break;
  52621. case AdditiveBlending:
  52622. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  52623. break;
  52624. case SubtractiveBlending:
  52625. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  52626. break;
  52627. case MultiplyBlending:
  52628. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  52629. break;
  52630. }
  52631. } else {
  52632. switch ( blending ) {
  52633. case NormalBlending:
  52634. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  52635. break;
  52636. case AdditiveBlending:
  52637. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  52638. break;
  52639. case SubtractiveBlending:
  52640. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  52641. break;
  52642. case MultiplyBlending:
  52643. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  52644. break;
  52645. }
  52646. }
  52647. }
  52648. if ( color !== undefined && alpha !== undefined ) {
  52649. return { color, alpha };
  52650. } else {
  52651. error( 'WebGPURenderer: Invalid blending: ', blending );
  52652. }
  52653. }
  52654. /**
  52655. * Returns the GPU blend factor which is required for the pipeline creation.
  52656. *
  52657. * @private
  52658. * @param {number} blend - The blend factor as a three.js constant.
  52659. * @return {string} The GPU blend factor.
  52660. */
  52661. _getBlendFactor( blend ) {
  52662. let blendFactor;
  52663. switch ( blend ) {
  52664. case ZeroFactor:
  52665. blendFactor = GPUBlendFactor.Zero;
  52666. break;
  52667. case OneFactor:
  52668. blendFactor = GPUBlendFactor.One;
  52669. break;
  52670. case SrcColorFactor:
  52671. blendFactor = GPUBlendFactor.Src;
  52672. break;
  52673. case OneMinusSrcColorFactor:
  52674. blendFactor = GPUBlendFactor.OneMinusSrc;
  52675. break;
  52676. case SrcAlphaFactor:
  52677. blendFactor = GPUBlendFactor.SrcAlpha;
  52678. break;
  52679. case OneMinusSrcAlphaFactor:
  52680. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  52681. break;
  52682. case DstColorFactor:
  52683. blendFactor = GPUBlendFactor.Dst;
  52684. break;
  52685. case OneMinusDstColorFactor:
  52686. blendFactor = GPUBlendFactor.OneMinusDst;
  52687. break;
  52688. case DstAlphaFactor:
  52689. blendFactor = GPUBlendFactor.DstAlpha;
  52690. break;
  52691. case OneMinusDstAlphaFactor:
  52692. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  52693. break;
  52694. case SrcAlphaSaturateFactor:
  52695. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  52696. break;
  52697. case BlendColorFactor:
  52698. blendFactor = GPUBlendFactor.Constant;
  52699. break;
  52700. case OneMinusBlendColorFactor:
  52701. blendFactor = GPUBlendFactor.OneMinusConstant;
  52702. break;
  52703. default:
  52704. error( 'WebGPURenderer: Blend factor not supported.', blend );
  52705. }
  52706. return blendFactor;
  52707. }
  52708. /**
  52709. * Returns the GPU stencil compare function which is required for the pipeline creation.
  52710. *
  52711. * @private
  52712. * @param {Material} material - The material.
  52713. * @return {string} The GPU stencil compare function.
  52714. */
  52715. _getStencilCompare( material ) {
  52716. let stencilCompare;
  52717. const stencilFunc = material.stencilFunc;
  52718. switch ( stencilFunc ) {
  52719. case NeverStencilFunc:
  52720. stencilCompare = GPUCompareFunction.Never;
  52721. break;
  52722. case AlwaysStencilFunc:
  52723. stencilCompare = GPUCompareFunction.Always;
  52724. break;
  52725. case LessStencilFunc:
  52726. stencilCompare = GPUCompareFunction.Less;
  52727. break;
  52728. case LessEqualStencilFunc:
  52729. stencilCompare = GPUCompareFunction.LessEqual;
  52730. break;
  52731. case EqualStencilFunc:
  52732. stencilCompare = GPUCompareFunction.Equal;
  52733. break;
  52734. case GreaterEqualStencilFunc:
  52735. stencilCompare = GPUCompareFunction.GreaterEqual;
  52736. break;
  52737. case GreaterStencilFunc:
  52738. stencilCompare = GPUCompareFunction.Greater;
  52739. break;
  52740. case NotEqualStencilFunc:
  52741. stencilCompare = GPUCompareFunction.NotEqual;
  52742. break;
  52743. default:
  52744. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  52745. }
  52746. return stencilCompare;
  52747. }
  52748. /**
  52749. * Returns the GPU stencil operation which is required for the pipeline creation.
  52750. *
  52751. * @private
  52752. * @param {number} op - A three.js constant defining the stencil operation.
  52753. * @return {string} The GPU stencil operation.
  52754. */
  52755. _getStencilOperation( op ) {
  52756. let stencilOperation;
  52757. switch ( op ) {
  52758. case KeepStencilOp:
  52759. stencilOperation = GPUStencilOperation.Keep;
  52760. break;
  52761. case ZeroStencilOp:
  52762. stencilOperation = GPUStencilOperation.Zero;
  52763. break;
  52764. case ReplaceStencilOp:
  52765. stencilOperation = GPUStencilOperation.Replace;
  52766. break;
  52767. case InvertStencilOp:
  52768. stencilOperation = GPUStencilOperation.Invert;
  52769. break;
  52770. case IncrementStencilOp:
  52771. stencilOperation = GPUStencilOperation.IncrementClamp;
  52772. break;
  52773. case DecrementStencilOp:
  52774. stencilOperation = GPUStencilOperation.DecrementClamp;
  52775. break;
  52776. case IncrementWrapStencilOp:
  52777. stencilOperation = GPUStencilOperation.IncrementWrap;
  52778. break;
  52779. case DecrementWrapStencilOp:
  52780. stencilOperation = GPUStencilOperation.DecrementWrap;
  52781. break;
  52782. default:
  52783. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  52784. }
  52785. return stencilOperation;
  52786. }
  52787. /**
  52788. * Returns the GPU blend operation which is required for the pipeline creation.
  52789. *
  52790. * @private
  52791. * @param {number} blendEquation - A three.js constant defining the blend equation.
  52792. * @return {string} The GPU blend operation.
  52793. */
  52794. _getBlendOperation( blendEquation ) {
  52795. let blendOperation;
  52796. switch ( blendEquation ) {
  52797. case AddEquation:
  52798. blendOperation = GPUBlendOperation.Add;
  52799. break;
  52800. case SubtractEquation:
  52801. blendOperation = GPUBlendOperation.Subtract;
  52802. break;
  52803. case ReverseSubtractEquation:
  52804. blendOperation = GPUBlendOperation.ReverseSubtract;
  52805. break;
  52806. case MinEquation:
  52807. blendOperation = GPUBlendOperation.Min;
  52808. break;
  52809. case MaxEquation:
  52810. blendOperation = GPUBlendOperation.Max;
  52811. break;
  52812. default:
  52813. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  52814. }
  52815. return blendOperation;
  52816. }
  52817. /**
  52818. * Returns the primitive state as a descriptor object required
  52819. * for the pipeline creation.
  52820. *
  52821. * @private
  52822. * @param {Object3D} object - The 3D object.
  52823. * @param {BufferGeometry} geometry - The geometry.
  52824. * @param {Material} material - The material.
  52825. * @return {Object} The primitive state.
  52826. */
  52827. _getPrimitiveState( object, geometry, material ) {
  52828. const descriptor = {};
  52829. const utils = this.backend.utils;
  52830. //
  52831. descriptor.topology = utils.getPrimitiveTopology( object, material );
  52832. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  52833. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  52834. }
  52835. //
  52836. let flipSided = ( material.side === BackSide );
  52837. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  52838. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  52839. //
  52840. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  52841. return descriptor;
  52842. }
  52843. /**
  52844. * Returns the GPU color write mask which is required for the pipeline creation.
  52845. *
  52846. * @private
  52847. * @param {Material} material - The material.
  52848. * @return {number} The GPU color write mask.
  52849. */
  52850. _getColorWriteMask( material ) {
  52851. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  52852. }
  52853. /**
  52854. * Returns the GPU depth compare function which is required for the pipeline creation.
  52855. *
  52856. * @private
  52857. * @param {Material} material - The material.
  52858. * @return {string} The GPU depth compare function.
  52859. */
  52860. _getDepthCompare( material ) {
  52861. let depthCompare;
  52862. if ( material.depthTest === false ) {
  52863. depthCompare = GPUCompareFunction.Always;
  52864. } else {
  52865. const depthFunc = material.depthFunc;
  52866. switch ( depthFunc ) {
  52867. case NeverDepth:
  52868. depthCompare = GPUCompareFunction.Never;
  52869. break;
  52870. case AlwaysDepth:
  52871. depthCompare = GPUCompareFunction.Always;
  52872. break;
  52873. case LessDepth:
  52874. depthCompare = GPUCompareFunction.Less;
  52875. break;
  52876. case LessEqualDepth:
  52877. depthCompare = GPUCompareFunction.LessEqual;
  52878. break;
  52879. case EqualDepth:
  52880. depthCompare = GPUCompareFunction.Equal;
  52881. break;
  52882. case GreaterEqualDepth:
  52883. depthCompare = GPUCompareFunction.GreaterEqual;
  52884. break;
  52885. case GreaterDepth:
  52886. depthCompare = GPUCompareFunction.Greater;
  52887. break;
  52888. case NotEqualDepth:
  52889. depthCompare = GPUCompareFunction.NotEqual;
  52890. break;
  52891. default:
  52892. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  52893. }
  52894. }
  52895. return depthCompare;
  52896. }
  52897. }
  52898. /**
  52899. * Manages a pool of WebGPU timestamp queries for performance measurement.
  52900. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  52901. *
  52902. * @augments TimestampQueryPool
  52903. */
  52904. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  52905. /**
  52906. * Creates a new WebGPU timestamp query pool.
  52907. *
  52908. * @param {GPUDevice} device - The WebGPU device to create queries on.
  52909. * @param {string} type - The type identifier for this query pool.
  52910. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  52911. */
  52912. constructor( device, type, maxQueries = 2048 ) {
  52913. super( maxQueries );
  52914. this.device = device;
  52915. this.type = type;
  52916. this.querySet = this.device.createQuerySet( {
  52917. type: 'timestamp',
  52918. count: this.maxQueries,
  52919. label: `queryset_global_timestamp_${type}`
  52920. } );
  52921. const bufferSize = this.maxQueries * 8;
  52922. this.resolveBuffer = this.device.createBuffer( {
  52923. label: `buffer_timestamp_resolve_${type}`,
  52924. size: bufferSize,
  52925. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  52926. } );
  52927. this.resultBuffer = this.device.createBuffer( {
  52928. label: `buffer_timestamp_result_${type}`,
  52929. size: bufferSize,
  52930. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52931. } );
  52932. }
  52933. /**
  52934. * Allocates a pair of queries for a given render context.
  52935. *
  52936. * @param {string} uid - A unique identifier for the render context.
  52937. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  52938. */
  52939. allocateQueriesForContext( uid ) {
  52940. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  52941. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  52942. 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() } ).` );
  52943. return null;
  52944. }
  52945. const baseOffset = this.currentQueryIndex;
  52946. this.currentQueryIndex += 2;
  52947. this.queryOffsets.set( uid, baseOffset );
  52948. return baseOffset;
  52949. }
  52950. /**
  52951. * Asynchronously resolves all pending queries and returns the total duration.
  52952. * If there's already a pending resolve operation, returns that promise instead.
  52953. *
  52954. * @async
  52955. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  52956. */
  52957. async resolveQueriesAsync() {
  52958. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  52959. return this.lastValue;
  52960. }
  52961. if ( this.pendingResolve ) {
  52962. return this.pendingResolve;
  52963. }
  52964. this.pendingResolve = this._resolveQueries();
  52965. try {
  52966. const result = await this.pendingResolve;
  52967. return result;
  52968. } finally {
  52969. this.pendingResolve = null;
  52970. }
  52971. }
  52972. /**
  52973. * Internal method to resolve queries and calculate total duration.
  52974. *
  52975. * @async
  52976. * @private
  52977. * @returns {Promise<number>} The total duration in milliseconds.
  52978. */
  52979. async _resolveQueries() {
  52980. if ( this.isDisposed ) {
  52981. return this.lastValue;
  52982. }
  52983. try {
  52984. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  52985. return this.lastValue;
  52986. }
  52987. const currentOffsets = new Map( this.queryOffsets );
  52988. const queryCount = this.currentQueryIndex;
  52989. const bytesUsed = queryCount * 8;
  52990. // Reset state before GPU work
  52991. this.currentQueryIndex = 0;
  52992. this.queryOffsets.clear();
  52993. const commandEncoder = this.device.createCommandEncoder();
  52994. commandEncoder.resolveQuerySet(
  52995. this.querySet,
  52996. 0,
  52997. queryCount,
  52998. this.resolveBuffer,
  52999. 0
  53000. );
  53001. commandEncoder.copyBufferToBuffer(
  53002. this.resolveBuffer,
  53003. 0,
  53004. this.resultBuffer,
  53005. 0,
  53006. bytesUsed
  53007. );
  53008. const commandBuffer = commandEncoder.finish();
  53009. this.device.queue.submit( [ commandBuffer ] );
  53010. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  53011. return this.lastValue;
  53012. }
  53013. // Create and track the mapping operation
  53014. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  53015. if ( this.isDisposed ) {
  53016. if ( this.resultBuffer.mapState === 'mapped' ) {
  53017. this.resultBuffer.unmap();
  53018. }
  53019. return this.lastValue;
  53020. }
  53021. //
  53022. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  53023. const framesDuration = {};
  53024. const frames = [];
  53025. for ( const [ uid, baseOffset ] of currentOffsets ) {
  53026. const match = uid.match( /^(.*):f(\d+)$/ );
  53027. const frame = parseInt( match[ 2 ] );
  53028. if ( frames.includes( frame ) === false ) {
  53029. frames.push( frame );
  53030. }
  53031. if ( framesDuration[ frame ] === undefined ) framesDuration[ frame ] = 0;
  53032. const startTime = times[ baseOffset ];
  53033. const endTime = times[ baseOffset + 1 ];
  53034. const duration = Number( endTime - startTime ) / 1e6;
  53035. this.timestamps.set( uid, duration );
  53036. framesDuration[ frame ] += duration;
  53037. }
  53038. // Return the total duration of the last frame
  53039. const totalDuration = framesDuration[ frames[ frames.length - 1 ] ];
  53040. this.resultBuffer.unmap();
  53041. this.lastValue = totalDuration;
  53042. this.frames = frames;
  53043. return totalDuration;
  53044. } catch ( error ) {
  53045. error( 'Error resolving queries:', error );
  53046. if ( this.resultBuffer.mapState === 'mapped' ) {
  53047. this.resultBuffer.unmap();
  53048. }
  53049. return this.lastValue;
  53050. }
  53051. }
  53052. /**
  53053. * Dispose of the query pool.
  53054. *
  53055. * @async
  53056. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  53057. */
  53058. async dispose() {
  53059. if ( this.isDisposed ) {
  53060. return;
  53061. }
  53062. this.isDisposed = true;
  53063. // Wait for pending resolve operation
  53064. if ( this.pendingResolve ) {
  53065. try {
  53066. await this.pendingResolve;
  53067. } catch ( error ) {
  53068. error( 'Error waiting for pending resolve:', error );
  53069. }
  53070. }
  53071. // Ensure buffer is unmapped before destroying
  53072. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  53073. try {
  53074. this.resultBuffer.unmap();
  53075. } catch ( error ) {
  53076. error( 'Error unmapping buffer:', error );
  53077. }
  53078. }
  53079. // Destroy resources
  53080. if ( this.querySet ) {
  53081. this.querySet.destroy();
  53082. this.querySet = null;
  53083. }
  53084. if ( this.resolveBuffer ) {
  53085. this.resolveBuffer.destroy();
  53086. this.resolveBuffer = null;
  53087. }
  53088. if ( this.resultBuffer ) {
  53089. this.resultBuffer.destroy();
  53090. this.resultBuffer = null;
  53091. }
  53092. this.queryOffsets.clear();
  53093. this.pendingResolve = null;
  53094. }
  53095. }
  53096. /*// debugger tools
  53097. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  53098. //*/
  53099. /**
  53100. * A backend implementation targeting WebGPU.
  53101. *
  53102. * @private
  53103. * @augments Backend
  53104. */
  53105. class WebGPUBackend extends Backend {
  53106. /**
  53107. * WebGPUBackend options.
  53108. *
  53109. * @typedef {Object} WebGPUBackend~Options
  53110. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  53111. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  53112. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  53113. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  53114. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  53115. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  53116. * @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.
  53117. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  53118. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  53119. * @property {string} [powerPreference=undefined] - The power preference.
  53120. * @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.
  53121. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  53122. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  53123. */
  53124. /**
  53125. * Constructs a new WebGPU backend.
  53126. *
  53127. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  53128. */
  53129. constructor( parameters = {} ) {
  53130. super( parameters );
  53131. /**
  53132. * This flag can be used for type testing.
  53133. *
  53134. * @type {boolean}
  53135. * @readonly
  53136. * @default true
  53137. */
  53138. this.isWebGPUBackend = true;
  53139. // some parameters require default values other than "undefined"
  53140. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  53141. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  53142. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  53143. /**
  53144. * Indicates whether the backend is in compatibility mode or not.
  53145. * @type {boolean}
  53146. * @default false
  53147. */
  53148. this.compatibilityMode = this.parameters.compatibilityMode;
  53149. /**
  53150. * A reference to the device.
  53151. *
  53152. * @type {?GPUDevice}
  53153. * @default null
  53154. */
  53155. this.device = null;
  53156. /**
  53157. * A reference to the default render pass descriptor.
  53158. *
  53159. * @type {?Object}
  53160. * @default null
  53161. */
  53162. this.defaultRenderPassdescriptor = null;
  53163. /**
  53164. * A reference to a backend module holding common utility functions.
  53165. *
  53166. * @type {WebGPUUtils}
  53167. */
  53168. this.utils = new WebGPUUtils( this );
  53169. /**
  53170. * A reference to a backend module holding shader attribute-related
  53171. * utility functions.
  53172. *
  53173. * @type {WebGPUAttributeUtils}
  53174. */
  53175. this.attributeUtils = new WebGPUAttributeUtils( this );
  53176. /**
  53177. * A reference to a backend module holding shader binding-related
  53178. * utility functions.
  53179. *
  53180. * @type {WebGPUBindingUtils}
  53181. */
  53182. this.bindingUtils = new WebGPUBindingUtils( this );
  53183. /**
  53184. * A reference to a backend module holding shader pipeline-related
  53185. * utility functions.
  53186. *
  53187. * @type {WebGPUPipelineUtils}
  53188. */
  53189. this.pipelineUtils = new WebGPUPipelineUtils( this );
  53190. /**
  53191. * A reference to a backend module holding shader texture-related
  53192. * utility functions.
  53193. *
  53194. * @type {WebGPUTextureUtils}
  53195. */
  53196. this.textureUtils = new WebGPUTextureUtils( this );
  53197. /**
  53198. * A map that manages the resolve buffers for occlusion queries.
  53199. *
  53200. * @type {Map<number,GPUBuffer>}
  53201. */
  53202. this.occludedResolveCache = new Map();
  53203. }
  53204. /**
  53205. * Initializes the backend so it is ready for usage.
  53206. *
  53207. * @async
  53208. * @param {Renderer} renderer - The renderer.
  53209. * @return {Promise} A Promise that resolves when the backend has been initialized.
  53210. */
  53211. async init( renderer ) {
  53212. await super.init( renderer );
  53213. //
  53214. const parameters = this.parameters;
  53215. // create the device if it is not passed with parameters
  53216. let device;
  53217. if ( parameters.device === undefined ) {
  53218. const adapterOptions = {
  53219. powerPreference: parameters.powerPreference,
  53220. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  53221. };
  53222. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  53223. if ( adapter === null ) {
  53224. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  53225. }
  53226. // feature support
  53227. const features = Object.values( GPUFeatureName );
  53228. const supportedFeatures = [];
  53229. for ( const name of features ) {
  53230. if ( adapter.features.has( name ) ) {
  53231. supportedFeatures.push( name );
  53232. }
  53233. }
  53234. const deviceDescriptor = {
  53235. requiredFeatures: supportedFeatures,
  53236. requiredLimits: parameters.requiredLimits
  53237. };
  53238. device = await adapter.requestDevice( deviceDescriptor );
  53239. } else {
  53240. device = parameters.device;
  53241. }
  53242. device.lost.then( ( info ) => {
  53243. const deviceLossInfo = {
  53244. api: 'WebGPU',
  53245. message: info.message || 'Unknown reason',
  53246. reason: info.reason || null,
  53247. originalEvent: info
  53248. };
  53249. renderer.onDeviceLost( deviceLossInfo );
  53250. } );
  53251. this.device = device;
  53252. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  53253. this.updateSize();
  53254. }
  53255. /**
  53256. * A reference to the context.
  53257. *
  53258. * @type {?GPUCanvasContext}
  53259. * @default null
  53260. */
  53261. get context() {
  53262. const canvasTarget = this.renderer.getCanvasTarget();
  53263. const canvasData = this.get( canvasTarget );
  53264. let context = canvasData.context;
  53265. if ( context === undefined ) {
  53266. const parameters = this.parameters;
  53267. if ( canvasTarget.isDefaultCanvasTarget === true && parameters.context !== undefined ) {
  53268. context = parameters.context;
  53269. } else {
  53270. context = canvasTarget.domElement.getContext( 'webgpu' );
  53271. }
  53272. // OffscreenCanvas does not have setAttribute, see #22811
  53273. if ( 'setAttribute' in canvasTarget.domElement ) canvasTarget.domElement.setAttribute( 'data-engine', `three.js r${ REVISION } webgpu` );
  53274. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  53275. const toneMappingMode = parameters.outputType === HalfFloatType ? 'extended' : 'standard';
  53276. context.configure( {
  53277. device: this.device,
  53278. format: this.utils.getPreferredCanvasFormat(),
  53279. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  53280. alphaMode: alphaMode,
  53281. toneMapping: {
  53282. mode: toneMappingMode
  53283. }
  53284. } );
  53285. canvasData.context = context;
  53286. }
  53287. return context;
  53288. }
  53289. /**
  53290. * The coordinate system of the backend.
  53291. *
  53292. * @type {number}
  53293. * @readonly
  53294. */
  53295. get coordinateSystem() {
  53296. return WebGPUCoordinateSystem;
  53297. }
  53298. /**
  53299. * This method performs a readback operation by moving buffer data from
  53300. * a storage buffer attribute from the GPU to the CPU.
  53301. *
  53302. * @async
  53303. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  53304. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  53305. */
  53306. async getArrayBufferAsync( attribute ) {
  53307. return await this.attributeUtils.getArrayBufferAsync( attribute );
  53308. }
  53309. /**
  53310. * Returns the backend's rendering context.
  53311. *
  53312. * @return {GPUCanvasContext} The rendering context.
  53313. */
  53314. getContext() {
  53315. return this.context;
  53316. }
  53317. /**
  53318. * Returns the default render pass descriptor.
  53319. *
  53320. * In WebGPU, the default framebuffer must be configured
  53321. * like custom framebuffers so the backend needs a render
  53322. * pass descriptor even when rendering directly to screen.
  53323. *
  53324. * @private
  53325. * @return {Object} The render pass descriptor.
  53326. */
  53327. _getDefaultRenderPassDescriptor() {
  53328. const renderer = this.renderer;
  53329. const canvasTarget = renderer.getCanvasTarget();
  53330. const canvasData = this.get( canvasTarget );
  53331. const samples = renderer.currentSamples;
  53332. let descriptor = canvasData.descriptor;
  53333. if ( descriptor === undefined || canvasData.samples !== samples ) {
  53334. descriptor = {
  53335. colorAttachments: [ {
  53336. view: null
  53337. } ]
  53338. };
  53339. if ( renderer.depth === true || renderer.stencil === true ) {
  53340. descriptor.depthStencilAttachment = {
  53341. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  53342. };
  53343. }
  53344. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53345. if ( samples > 0 ) {
  53346. colorAttachment.view = this.textureUtils.getColorBuffer().createView();
  53347. } else {
  53348. colorAttachment.resolveTarget = undefined;
  53349. }
  53350. canvasData.descriptor = descriptor;
  53351. canvasData.samples = samples;
  53352. }
  53353. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53354. if ( samples > 0 ) {
  53355. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  53356. } else {
  53357. colorAttachment.view = this.context.getCurrentTexture().createView();
  53358. }
  53359. return descriptor;
  53360. }
  53361. /**
  53362. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  53363. *
  53364. * @param {RenderContext} renderContext - The render context.
  53365. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  53366. *
  53367. * @private
  53368. */
  53369. _isRenderCameraDepthArray( renderContext ) {
  53370. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  53371. }
  53372. /**
  53373. * Returns the render pass descriptor for the given render context.
  53374. *
  53375. * @private
  53376. * @param {RenderContext} renderContext - The render context.
  53377. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  53378. * @return {Object} The render pass descriptor.
  53379. */
  53380. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  53381. const renderTarget = renderContext.renderTarget;
  53382. const renderTargetData = this.get( renderTarget );
  53383. let descriptors = renderTargetData.descriptors;
  53384. if ( descriptors === undefined ||
  53385. renderTargetData.width !== renderTarget.width ||
  53386. renderTargetData.height !== renderTarget.height ||
  53387. renderTargetData.samples !== renderTarget.samples
  53388. ) {
  53389. descriptors = {};
  53390. renderTargetData.descriptors = descriptors;
  53391. }
  53392. const cacheKey = renderContext.getCacheKey();
  53393. let descriptorBase = descriptors[ cacheKey ];
  53394. if ( descriptorBase === undefined ) {
  53395. const textures = renderContext.textures;
  53396. const textureViews = [];
  53397. let sliceIndex;
  53398. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  53399. for ( let i = 0; i < textures.length; i ++ ) {
  53400. const textureData = this.get( textures[ i ] );
  53401. const viewDescriptor = {
  53402. label: `colorAttachment_${ i }`,
  53403. baseMipLevel: renderContext.activeMipmapLevel,
  53404. mipLevelCount: 1,
  53405. baseArrayLayer: renderContext.activeCubeFace,
  53406. arrayLayerCount: 1,
  53407. dimension: GPUTextureViewDimension.TwoD
  53408. };
  53409. if ( renderTarget.isRenderTarget3D ) {
  53410. sliceIndex = renderContext.activeCubeFace;
  53411. viewDescriptor.baseArrayLayer = 0;
  53412. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  53413. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53414. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  53415. if ( isRenderCameraDepthArray === true ) {
  53416. const cameras = renderContext.camera.cameras;
  53417. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  53418. const layerViewDescriptor = {
  53419. ...viewDescriptor,
  53420. baseArrayLayer: layer,
  53421. arrayLayerCount: 1,
  53422. dimension: GPUTextureViewDimension.TwoD
  53423. };
  53424. const textureView = textureData.texture.createView( layerViewDescriptor );
  53425. textureViews.push( {
  53426. view: textureView,
  53427. resolveTarget: undefined,
  53428. depthSlice: undefined
  53429. } );
  53430. }
  53431. } else {
  53432. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  53433. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  53434. }
  53435. }
  53436. if ( isRenderCameraDepthArray !== true ) {
  53437. const textureView = textureData.texture.createView( viewDescriptor );
  53438. let view, resolveTarget;
  53439. if ( textureData.msaaTexture !== undefined ) {
  53440. view = textureData.msaaTexture.createView();
  53441. resolveTarget = textureView;
  53442. } else {
  53443. view = textureView;
  53444. resolveTarget = undefined;
  53445. }
  53446. textureViews.push( {
  53447. view,
  53448. resolveTarget,
  53449. depthSlice: sliceIndex
  53450. } );
  53451. }
  53452. }
  53453. descriptorBase = { textureViews };
  53454. if ( renderContext.depth ) {
  53455. const depthTextureData = this.get( renderContext.depthTexture );
  53456. const options = {};
  53457. if ( renderContext.depthTexture.isArrayTexture ) {
  53458. options.dimension = GPUTextureViewDimension.TwoD;
  53459. options.arrayLayerCount = 1;
  53460. options.baseArrayLayer = renderContext.activeCubeFace;
  53461. }
  53462. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  53463. }
  53464. descriptors[ cacheKey ] = descriptorBase;
  53465. renderTargetData.width = renderTarget.width;
  53466. renderTargetData.height = renderTarget.height;
  53467. renderTargetData.samples = renderTarget.samples;
  53468. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  53469. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  53470. }
  53471. const descriptor = {
  53472. colorAttachments: []
  53473. };
  53474. // Apply dynamic properties to cached views
  53475. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  53476. const viewInfo = descriptorBase.textureViews[ i ];
  53477. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  53478. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  53479. clearValue = colorAttachmentsConfig.clearValue;
  53480. }
  53481. descriptor.colorAttachments.push( {
  53482. view: viewInfo.view,
  53483. depthSlice: viewInfo.depthSlice,
  53484. resolveTarget: viewInfo.resolveTarget,
  53485. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  53486. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  53487. clearValue: clearValue
  53488. } );
  53489. }
  53490. if ( descriptorBase.depthStencilView ) {
  53491. descriptor.depthStencilAttachment = {
  53492. view: descriptorBase.depthStencilView
  53493. };
  53494. }
  53495. return descriptor;
  53496. }
  53497. /**
  53498. * This method is executed at the beginning of a render call and prepares
  53499. * the WebGPU state for upcoming render calls
  53500. *
  53501. * @param {RenderContext} renderContext - The render context.
  53502. */
  53503. beginRender( renderContext ) {
  53504. const renderContextData = this.get( renderContext );
  53505. //
  53506. const device = this.device;
  53507. const occlusionQueryCount = renderContext.occlusionQueryCount;
  53508. let occlusionQuerySet;
  53509. if ( occlusionQueryCount > 0 ) {
  53510. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  53511. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  53512. // Get a reference to the array of objects with queries. The renderContextData property
  53513. // can be changed by another render pass before the buffer.mapAsyc() completes.
  53514. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  53515. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  53516. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  53517. //
  53518. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  53519. renderContextData.occlusionQuerySet = occlusionQuerySet;
  53520. renderContextData.occlusionQueryIndex = 0;
  53521. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  53522. renderContextData.lastOcclusionObject = null;
  53523. }
  53524. let descriptor;
  53525. if ( renderContext.textures === null ) {
  53526. descriptor = this._getDefaultRenderPassDescriptor();
  53527. } else {
  53528. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  53529. }
  53530. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  53531. descriptor.occlusionQuerySet = occlusionQuerySet;
  53532. const depthStencilAttachment = descriptor.depthStencilAttachment;
  53533. if ( renderContext.textures !== null ) {
  53534. const colorAttachments = descriptor.colorAttachments;
  53535. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  53536. const colorAttachment = colorAttachments[ i ];
  53537. if ( renderContext.clearColor ) {
  53538. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  53539. colorAttachment.loadOp = GPULoadOp.Clear;
  53540. } else {
  53541. colorAttachment.loadOp = GPULoadOp.Load;
  53542. }
  53543. colorAttachment.storeOp = GPUStoreOp.Store;
  53544. }
  53545. } else {
  53546. const colorAttachment = descriptor.colorAttachments[ 0 ];
  53547. if ( renderContext.clearColor ) {
  53548. colorAttachment.clearValue = renderContext.clearColorValue;
  53549. colorAttachment.loadOp = GPULoadOp.Clear;
  53550. } else {
  53551. colorAttachment.loadOp = GPULoadOp.Load;
  53552. }
  53553. colorAttachment.storeOp = GPUStoreOp.Store;
  53554. }
  53555. //
  53556. if ( renderContext.depth ) {
  53557. if ( renderContext.clearDepth ) {
  53558. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  53559. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  53560. } else {
  53561. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53562. }
  53563. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  53564. }
  53565. if ( renderContext.stencil ) {
  53566. if ( renderContext.clearStencil ) {
  53567. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  53568. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  53569. } else {
  53570. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53571. }
  53572. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  53573. }
  53574. //
  53575. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  53576. // shadow arrays - prepare bundle encoders for each camera in an array camera
  53577. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  53578. const cameras = renderContext.camera.cameras;
  53579. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  53580. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  53581. } else {
  53582. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  53583. }
  53584. // Create bundle encoders for each layer
  53585. renderContextData.bundleEncoders = [];
  53586. renderContextData.bundleSets = [];
  53587. // Create separate bundle encoders for each camera in the array
  53588. for ( let i = 0; i < cameras.length; i ++ ) {
  53589. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  53590. renderContext,
  53591. 'renderBundleArrayCamera_' + i
  53592. );
  53593. // Initialize state tracking for this bundle
  53594. const bundleSets = {
  53595. attributes: {},
  53596. bindingGroups: [],
  53597. pipeline: null,
  53598. index: null
  53599. };
  53600. renderContextData.bundleEncoders.push( bundleEncoder );
  53601. renderContextData.bundleSets.push( bundleSets );
  53602. }
  53603. // We'll complete the bundles in finishRender
  53604. renderContextData.currentPass = null;
  53605. } else {
  53606. const currentPass = encoder.beginRenderPass( descriptor );
  53607. renderContextData.currentPass = currentPass;
  53608. if ( renderContext.viewport ) {
  53609. this.updateViewport( renderContext );
  53610. }
  53611. if ( renderContext.scissor ) {
  53612. const { x, y, width, height } = renderContext.scissorValue;
  53613. currentPass.setScissorRect( x, y, width, height );
  53614. }
  53615. }
  53616. //
  53617. renderContextData.descriptor = descriptor;
  53618. renderContextData.encoder = encoder;
  53619. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53620. renderContextData.renderBundles = [];
  53621. }
  53622. /**
  53623. * This method creates layer descriptors for each camera in an array camera
  53624. * to prepare for rendering to a depth array texture.
  53625. *
  53626. * @param {RenderContext} renderContext - The render context.
  53627. * @param {Object} renderContextData - The render context data.
  53628. * @param {Object} descriptor - The render pass descriptor.
  53629. * @param {ArrayCamera} cameras - The array camera.
  53630. *
  53631. * @private
  53632. */
  53633. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  53634. const depthStencilAttachment = descriptor.depthStencilAttachment;
  53635. renderContextData.layerDescriptors = [];
  53636. const depthTextureData = this.get( renderContext.depthTexture );
  53637. if ( ! depthTextureData.viewCache ) {
  53638. depthTextureData.viewCache = [];
  53639. }
  53640. for ( let i = 0; i < cameras.length; i ++ ) {
  53641. const layerDescriptor = {
  53642. ...descriptor,
  53643. colorAttachments: [ {
  53644. ...descriptor.colorAttachments[ 0 ],
  53645. view: descriptor.colorAttachments[ i ].view
  53646. } ]
  53647. };
  53648. if ( descriptor.depthStencilAttachment ) {
  53649. const layerIndex = i;
  53650. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  53651. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  53652. dimension: GPUTextureViewDimension.TwoD,
  53653. baseArrayLayer: i,
  53654. arrayLayerCount: 1
  53655. } );
  53656. }
  53657. layerDescriptor.depthStencilAttachment = {
  53658. view: depthTextureData.viewCache[ layerIndex ],
  53659. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  53660. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  53661. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  53662. };
  53663. if ( renderContext.stencil ) {
  53664. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  53665. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  53666. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  53667. }
  53668. } else {
  53669. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  53670. }
  53671. renderContextData.layerDescriptors.push( layerDescriptor );
  53672. }
  53673. }
  53674. /**
  53675. * This method updates the layer descriptors for each camera in an array camera
  53676. * to prepare for rendering to a depth array texture.
  53677. *
  53678. * @param {RenderContext} renderContext - The render context.
  53679. * @param {Object} renderContextData - The render context data.
  53680. * @param {ArrayCamera} cameras - The array camera.
  53681. *
  53682. */
  53683. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  53684. for ( let i = 0; i < cameras.length; i ++ ) {
  53685. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  53686. if ( layerDescriptor.depthStencilAttachment ) {
  53687. const depthAttachment = layerDescriptor.depthStencilAttachment;
  53688. if ( renderContext.depth ) {
  53689. if ( renderContext.clearDepth ) {
  53690. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  53691. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  53692. } else {
  53693. depthAttachment.depthLoadOp = GPULoadOp.Load;
  53694. }
  53695. }
  53696. if ( renderContext.stencil ) {
  53697. if ( renderContext.clearStencil ) {
  53698. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  53699. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  53700. } else {
  53701. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  53702. }
  53703. }
  53704. }
  53705. }
  53706. }
  53707. /**
  53708. * This method is executed at the end of a render call and finalizes work
  53709. * after draw calls.
  53710. *
  53711. * @param {RenderContext} renderContext - The render context.
  53712. */
  53713. finishRender( renderContext ) {
  53714. const renderContextData = this.get( renderContext );
  53715. const occlusionQueryCount = renderContext.occlusionQueryCount;
  53716. if ( renderContextData.renderBundles.length > 0 ) {
  53717. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  53718. }
  53719. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  53720. renderContextData.currentPass.endOcclusionQuery();
  53721. }
  53722. // shadow arrays - Execute bundles for each layer
  53723. const encoder = renderContextData.encoder;
  53724. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  53725. const bundles = [];
  53726. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  53727. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  53728. bundles.push( bundleEncoder.finish() );
  53729. }
  53730. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  53731. if ( i < bundles.length ) {
  53732. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  53733. const renderPass = encoder.beginRenderPass( layerDescriptor );
  53734. if ( renderContext.viewport ) {
  53735. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  53736. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  53737. }
  53738. if ( renderContext.scissor ) {
  53739. const { x, y, width, height } = renderContext.scissorValue;
  53740. renderPass.setScissorRect( x, y, width, height );
  53741. }
  53742. renderPass.executeBundles( [ bundles[ i ] ] );
  53743. renderPass.end();
  53744. }
  53745. }
  53746. } else if ( renderContextData.currentPass ) {
  53747. renderContextData.currentPass.end();
  53748. }
  53749. if ( occlusionQueryCount > 0 ) {
  53750. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  53751. //
  53752. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  53753. if ( queryResolveBuffer === undefined ) {
  53754. queryResolveBuffer = this.device.createBuffer(
  53755. {
  53756. size: bufferSize,
  53757. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  53758. }
  53759. );
  53760. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  53761. }
  53762. //
  53763. const readBuffer = this.device.createBuffer(
  53764. {
  53765. size: bufferSize,
  53766. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  53767. }
  53768. );
  53769. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  53770. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  53771. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  53772. renderContextData.occlusionQueryBuffer = readBuffer;
  53773. //
  53774. this.resolveOccludedAsync( renderContext );
  53775. }
  53776. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  53777. //
  53778. if ( renderContext.textures !== null ) {
  53779. const textures = renderContext.textures;
  53780. for ( let i = 0; i < textures.length; i ++ ) {
  53781. const texture = textures[ i ];
  53782. if ( texture.generateMipmaps === true ) {
  53783. this.textureUtils.generateMipmaps( texture );
  53784. }
  53785. }
  53786. }
  53787. }
  53788. /**
  53789. * Returns `true` if the given 3D object is fully occluded by other
  53790. * 3D objects in the scene.
  53791. *
  53792. * @param {RenderContext} renderContext - The render context.
  53793. * @param {Object3D} object - The 3D object to test.
  53794. * @return {boolean} Whether the 3D object is fully occluded or not.
  53795. */
  53796. isOccluded( renderContext, object ) {
  53797. const renderContextData = this.get( renderContext );
  53798. return renderContextData.occluded && renderContextData.occluded.has( object );
  53799. }
  53800. /**
  53801. * This method processes the result of occlusion queries and writes it
  53802. * into render context data.
  53803. *
  53804. * @async
  53805. * @param {RenderContext} renderContext - The render context.
  53806. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  53807. */
  53808. async resolveOccludedAsync( renderContext ) {
  53809. const renderContextData = this.get( renderContext );
  53810. // handle occlusion query results
  53811. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  53812. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  53813. const occluded = new WeakSet();
  53814. renderContextData.currentOcclusionQueryObjects = null;
  53815. renderContextData.currentOcclusionQueryBuffer = null;
  53816. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  53817. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  53818. const results = new BigUint64Array( buffer );
  53819. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  53820. if ( results[ i ] === BigInt( 0 ) ) {
  53821. occluded.add( currentOcclusionQueryObjects[ i ] );
  53822. }
  53823. }
  53824. currentOcclusionQueryBuffer.destroy();
  53825. renderContextData.occluded = occluded;
  53826. }
  53827. }
  53828. /**
  53829. * Updates the viewport with the values from the given render context.
  53830. *
  53831. * @param {RenderContext} renderContext - The render context.
  53832. */
  53833. updateViewport( renderContext ) {
  53834. const { currentPass } = this.get( renderContext );
  53835. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  53836. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  53837. }
  53838. /**
  53839. * Returns the clear color and alpha into a single
  53840. * color object.
  53841. *
  53842. * @return {Color4} The clear color.
  53843. */
  53844. getClearColor() {
  53845. const clearColor = super.getClearColor();
  53846. // only premultiply alpha when alphaMode is "premultiplied"
  53847. if ( this.renderer.alpha === true ) {
  53848. clearColor.r *= clearColor.a;
  53849. clearColor.g *= clearColor.a;
  53850. clearColor.b *= clearColor.a;
  53851. }
  53852. return clearColor;
  53853. }
  53854. /**
  53855. * Performs a clear operation.
  53856. *
  53857. * @param {boolean} color - Whether the color buffer should be cleared or not.
  53858. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  53859. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  53860. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  53861. */
  53862. clear( color, depth, stencil, renderTargetContext = null ) {
  53863. const device = this.device;
  53864. const renderer = this.renderer;
  53865. let colorAttachments = [];
  53866. let depthStencilAttachment;
  53867. let clearValue;
  53868. let supportsDepth;
  53869. let supportsStencil;
  53870. if ( color ) {
  53871. const clearColor = this.getClearColor();
  53872. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  53873. }
  53874. if ( renderTargetContext === null ) {
  53875. supportsDepth = renderer.depth;
  53876. supportsStencil = renderer.stencil;
  53877. const descriptor = this._getDefaultRenderPassDescriptor();
  53878. if ( color ) {
  53879. colorAttachments = descriptor.colorAttachments;
  53880. const colorAttachment = colorAttachments[ 0 ];
  53881. colorAttachment.clearValue = clearValue;
  53882. colorAttachment.loadOp = GPULoadOp.Clear;
  53883. colorAttachment.storeOp = GPUStoreOp.Store;
  53884. }
  53885. if ( supportsDepth || supportsStencil ) {
  53886. depthStencilAttachment = descriptor.depthStencilAttachment;
  53887. }
  53888. } else {
  53889. supportsDepth = renderTargetContext.depth;
  53890. supportsStencil = renderTargetContext.stencil;
  53891. const clearConfig = {
  53892. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  53893. clearValue: color ? clearValue : undefined
  53894. };
  53895. if ( supportsDepth ) {
  53896. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  53897. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  53898. clearConfig.depthStoreOp = GPUStoreOp.Store;
  53899. }
  53900. if ( supportsStencil ) {
  53901. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  53902. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  53903. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  53904. }
  53905. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  53906. colorAttachments = descriptor.colorAttachments;
  53907. depthStencilAttachment = descriptor.depthStencilAttachment;
  53908. }
  53909. if ( supportsDepth && depthStencilAttachment ) {
  53910. if ( depth ) {
  53911. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  53912. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  53913. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  53914. } else {
  53915. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53916. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  53917. }
  53918. }
  53919. //
  53920. if ( supportsStencil && depthStencilAttachment ) {
  53921. if ( stencil ) {
  53922. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  53923. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  53924. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  53925. } else {
  53926. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53927. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  53928. }
  53929. }
  53930. //
  53931. const encoder = device.createCommandEncoder( { label: 'clear' } );
  53932. const currentPass = encoder.beginRenderPass( {
  53933. colorAttachments,
  53934. depthStencilAttachment
  53935. } );
  53936. currentPass.end();
  53937. device.queue.submit( [ encoder.finish() ] );
  53938. }
  53939. // compute
  53940. /**
  53941. * This method is executed at the beginning of a compute call and
  53942. * prepares the state for upcoming compute tasks.
  53943. *
  53944. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  53945. */
  53946. beginCompute( computeGroup ) {
  53947. const groupGPU = this.get( computeGroup );
  53948. //
  53949. const descriptor = {
  53950. label: 'computeGroup_' + computeGroup.id
  53951. };
  53952. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  53953. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  53954. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  53955. }
  53956. /**
  53957. * Executes a compute command for the given compute node.
  53958. *
  53959. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  53960. * @param {Node} computeNode - The compute node.
  53961. * @param {Array<BindGroup>} bindings - The bindings.
  53962. * @param {ComputePipeline} pipeline - The compute pipeline.
  53963. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  53964. */
  53965. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  53966. const computeNodeData = this.get( computeNode );
  53967. const { passEncoderGPU } = this.get( computeGroup );
  53968. // pipeline
  53969. const pipelineGPU = this.get( pipeline ).pipeline;
  53970. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  53971. // bind groups
  53972. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  53973. const bindGroup = bindings[ i ];
  53974. const bindingsData = this.get( bindGroup );
  53975. passEncoderGPU.setBindGroup( i, bindingsData.group );
  53976. }
  53977. let dispatchSize;
  53978. if ( dispatchSizeOrCount === null ) {
  53979. dispatchSizeOrCount = computeNode.count;
  53980. }
  53981. if ( typeof dispatchSizeOrCount === 'number' ) {
  53982. // If a single number is given, we calculate the dispatch size based on the workgroup size
  53983. const count = dispatchSizeOrCount;
  53984. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  53985. // cache dispatch size to avoid recalculating it every time
  53986. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  53987. computeNodeData.count = count;
  53988. const workgroupSize = computeNode.workgroupSize;
  53989. let size = workgroupSize[ 0 ];
  53990. for ( let i = 1; i < workgroupSize.length; i ++ )
  53991. size *= workgroupSize[ i ];
  53992. const dispatchCount = Math.ceil( count / size );
  53993. //
  53994. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  53995. dispatchSize = [ dispatchCount, 1, 1 ];
  53996. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  53997. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  53998. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  53999. }
  54000. computeNodeData.dispatchSize = dispatchSize;
  54001. }
  54002. dispatchSize = computeNodeData.dispatchSize;
  54003. } else {
  54004. dispatchSize = dispatchSizeOrCount;
  54005. }
  54006. //
  54007. passEncoderGPU.dispatchWorkgroups(
  54008. dispatchSize[ 0 ],
  54009. dispatchSize[ 1 ] || 1,
  54010. dispatchSize[ 2 ] || 1
  54011. );
  54012. }
  54013. /**
  54014. * This method is executed at the end of a compute call and
  54015. * finalizes work after compute tasks.
  54016. *
  54017. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  54018. */
  54019. finishCompute( computeGroup ) {
  54020. const groupData = this.get( computeGroup );
  54021. groupData.passEncoderGPU.end();
  54022. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  54023. }
  54024. /**
  54025. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  54026. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  54027. *
  54028. * @async
  54029. * @return {Promise} A Promise that resolves when synchronization has been finished.
  54030. */
  54031. async waitForGPU() {
  54032. await this.device.queue.onSubmittedWorkDone();
  54033. }
  54034. // render object
  54035. /**
  54036. * Executes a draw command for the given render object.
  54037. *
  54038. * @param {RenderObject} renderObject - The render object to draw.
  54039. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  54040. */
  54041. draw( renderObject, info ) {
  54042. const { object, material, context, pipeline } = renderObject;
  54043. const bindings = renderObject.getBindings();
  54044. const renderContextData = this.get( context );
  54045. const pipelineGPU = this.get( pipeline ).pipeline;
  54046. const index = renderObject.getIndex();
  54047. const hasIndex = ( index !== null );
  54048. const drawParams = renderObject.getDrawParameters();
  54049. if ( drawParams === null ) return;
  54050. // pipeline
  54051. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  54052. // pipeline
  54053. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  54054. currentSets.pipeline = pipelineGPU;
  54055. // bind groups
  54056. const currentBindingGroups = currentSets.bindingGroups;
  54057. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  54058. const bindGroup = bindings[ i ];
  54059. const bindingsData = this.get( bindGroup );
  54060. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  54061. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  54062. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  54063. }
  54064. }
  54065. // attributes
  54066. // index
  54067. if ( hasIndex === true ) {
  54068. if ( currentSets.index !== index ) {
  54069. const buffer = this.get( index ).buffer;
  54070. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  54071. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  54072. currentSets.index = index;
  54073. }
  54074. }
  54075. // vertex buffers
  54076. const vertexBuffers = renderObject.getVertexBuffers();
  54077. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  54078. const vertexBuffer = vertexBuffers[ i ];
  54079. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  54080. const buffer = this.get( vertexBuffer ).buffer;
  54081. passEncoderGPU.setVertexBuffer( i, buffer );
  54082. currentSets.attributes[ i ] = vertexBuffer;
  54083. }
  54084. }
  54085. // stencil
  54086. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  54087. passEncoderGPU.setStencilReference( material.stencilRef );
  54088. renderContextData.currentStencilRef = material.stencilRef;
  54089. }
  54090. };
  54091. // Define draw function
  54092. const draw = ( passEncoderGPU, currentSets ) => {
  54093. setPipelineAndBindings( passEncoderGPU, currentSets );
  54094. if ( object.isBatchedMesh === true ) {
  54095. const starts = object._multiDrawStarts;
  54096. const counts = object._multiDrawCounts;
  54097. const drawCount = object._multiDrawCount;
  54098. const drawInstances = object._multiDrawInstances;
  54099. if ( drawInstances !== null ) {
  54100. // @deprecated, r174
  54101. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  54102. }
  54103. for ( let i = 0; i < drawCount; i ++ ) {
  54104. const count = drawInstances ? drawInstances[ i ] : 1;
  54105. const firstInstance = count > 1 ? 0 : i;
  54106. if ( hasIndex === true ) {
  54107. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  54108. } else {
  54109. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  54110. }
  54111. info.update( object, counts[ i ], count );
  54112. }
  54113. } else if ( hasIndex === true ) {
  54114. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  54115. const indirect = renderObject.getIndirect();
  54116. if ( indirect !== null ) {
  54117. const buffer = this.get( indirect ).buffer;
  54118. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  54119. } else {
  54120. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  54121. }
  54122. info.update( object, indexCount, instanceCount );
  54123. } else {
  54124. const { vertexCount, instanceCount, firstVertex } = drawParams;
  54125. const indirect = renderObject.getIndirect();
  54126. if ( indirect !== null ) {
  54127. const buffer = this.get( indirect ).buffer;
  54128. passEncoderGPU.drawIndirect( buffer, 0 );
  54129. } else {
  54130. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  54131. }
  54132. info.update( object, vertexCount, instanceCount );
  54133. }
  54134. };
  54135. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  54136. const cameraData = this.get( renderObject.camera );
  54137. const cameras = renderObject.camera.cameras;
  54138. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  54139. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  54140. const bindingsData = this.get( cameraIndex );
  54141. const indexesGPU = [];
  54142. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  54143. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54144. data[ 0 ] = i;
  54145. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  54146. indexesGPU.push( bindGroupIndex );
  54147. }
  54148. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  54149. }
  54150. const pixelRatio = this.renderer.getPixelRatio();
  54151. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  54152. const subCamera = cameras[ i ];
  54153. if ( object.layers.test( subCamera.layers ) ) {
  54154. const vp = subCamera.viewport;
  54155. let pass = renderContextData.currentPass;
  54156. let sets = renderContextData.currentSets;
  54157. if ( renderContextData.bundleEncoders ) {
  54158. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  54159. const bundleSets = renderContextData.bundleSets[ i ];
  54160. pass = bundleEncoder;
  54161. sets = bundleSets;
  54162. }
  54163. if ( vp ) {
  54164. pass.setViewport(
  54165. Math.floor( vp.x * pixelRatio ),
  54166. Math.floor( vp.y * pixelRatio ),
  54167. Math.floor( vp.width * pixelRatio ),
  54168. Math.floor( vp.height * pixelRatio ),
  54169. context.viewportValue.minDepth,
  54170. context.viewportValue.maxDepth
  54171. );
  54172. }
  54173. // Set camera index binding for this layer
  54174. if ( cameraIndex && cameraData.indexesGPU ) {
  54175. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  54176. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  54177. }
  54178. draw( pass, sets );
  54179. }
  54180. }
  54181. } else {
  54182. // Regular single camera rendering
  54183. if ( renderContextData.currentPass ) {
  54184. // Handle occlusion queries
  54185. if ( renderContextData.occlusionQuerySet !== undefined ) {
  54186. const lastObject = renderContextData.lastOcclusionObject;
  54187. if ( lastObject !== object ) {
  54188. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  54189. renderContextData.currentPass.endOcclusionQuery();
  54190. renderContextData.occlusionQueryIndex ++;
  54191. }
  54192. if ( object.occlusionTest === true ) {
  54193. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  54194. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  54195. }
  54196. renderContextData.lastOcclusionObject = object;
  54197. }
  54198. }
  54199. draw( renderContextData.currentPass, renderContextData.currentSets );
  54200. }
  54201. }
  54202. }
  54203. // cache key
  54204. /**
  54205. * Returns `true` if the render pipeline requires an update.
  54206. *
  54207. * @param {RenderObject} renderObject - The render object.
  54208. * @return {boolean} Whether the render pipeline requires an update or not.
  54209. */
  54210. needsRenderUpdate( renderObject ) {
  54211. const data = this.get( renderObject );
  54212. const { object, material } = renderObject;
  54213. const utils = this.utils;
  54214. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  54215. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  54216. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  54217. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  54218. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  54219. let needsUpdate = false;
  54220. if ( data.material !== material || data.materialVersion !== material.version ||
  54221. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  54222. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  54223. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  54224. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  54225. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  54226. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  54227. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  54228. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  54229. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  54230. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  54231. data.primitiveTopology !== primitiveTopology ||
  54232. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  54233. ) {
  54234. data.material = material; data.materialVersion = material.version;
  54235. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  54236. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  54237. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  54238. data.colorWrite = material.colorWrite;
  54239. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  54240. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  54241. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  54242. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  54243. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  54244. data.sampleCount = sampleCount;
  54245. data.colorSpace = colorSpace;
  54246. data.colorFormat = colorFormat;
  54247. data.depthStencilFormat = depthStencilFormat;
  54248. data.primitiveTopology = primitiveTopology;
  54249. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  54250. needsUpdate = true;
  54251. }
  54252. return needsUpdate;
  54253. }
  54254. /**
  54255. * Returns a cache key that is used to identify render pipelines.
  54256. *
  54257. * @param {RenderObject} renderObject - The render object.
  54258. * @return {string} The cache key.
  54259. */
  54260. getRenderCacheKey( renderObject ) {
  54261. const { object, material } = renderObject;
  54262. const utils = this.utils;
  54263. const renderContext = renderObject.context;
  54264. // meshes with negative scale have a different frontFace render pipeline
  54265. // descriptor value so the following must be honored in the cache key
  54266. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  54267. return [
  54268. material.transparent, material.blending, material.premultipliedAlpha,
  54269. material.blendSrc, material.blendDst, material.blendEquation,
  54270. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  54271. material.colorWrite,
  54272. material.depthWrite, material.depthTest, material.depthFunc,
  54273. material.stencilWrite, material.stencilFunc,
  54274. material.stencilFail, material.stencilZFail, material.stencilZPass,
  54275. material.stencilFuncMask, material.stencilWriteMask,
  54276. material.side,
  54277. frontFaceCW,
  54278. utils.getSampleCountRenderContext( renderContext ),
  54279. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  54280. utils.getPrimitiveTopology( object, material ),
  54281. renderObject.getGeometryCacheKey(),
  54282. renderObject.clippingContextCacheKey
  54283. ].join();
  54284. }
  54285. // textures
  54286. /**
  54287. * Updates a GPU sampler for the given texture.
  54288. *
  54289. * @param {Texture} texture - The texture to update the sampler for.
  54290. * @return {string} The current sampler key.
  54291. */
  54292. updateSampler( texture ) {
  54293. return this.textureUtils.updateSampler( texture );
  54294. }
  54295. /**
  54296. * Creates a default texture for the given texture that can be used
  54297. * as a placeholder until the actual texture is ready for usage.
  54298. *
  54299. * @param {Texture} texture - The texture to create a default texture for.
  54300. * @return {boolean} Whether the sampler has been updated or not.
  54301. */
  54302. createDefaultTexture( texture ) {
  54303. return this.textureUtils.createDefaultTexture( texture );
  54304. }
  54305. /**
  54306. * Defines a texture on the GPU for the given texture object.
  54307. *
  54308. * @param {Texture} texture - The texture.
  54309. * @param {Object} [options={}] - Optional configuration parameter.
  54310. */
  54311. createTexture( texture, options ) {
  54312. this.textureUtils.createTexture( texture, options );
  54313. }
  54314. /**
  54315. * Uploads the updated texture data to the GPU.
  54316. *
  54317. * @param {Texture} texture - The texture.
  54318. * @param {Object} [options={}] - Optional configuration parameter.
  54319. */
  54320. updateTexture( texture, options ) {
  54321. this.textureUtils.updateTexture( texture, options );
  54322. }
  54323. /**
  54324. * Generates mipmaps for the given texture.
  54325. *
  54326. * @param {Texture} texture - The texture.
  54327. */
  54328. generateMipmaps( texture ) {
  54329. this.textureUtils.generateMipmaps( texture );
  54330. }
  54331. /**
  54332. * Destroys the GPU data for the given texture object.
  54333. *
  54334. * @param {Texture} texture - The texture.
  54335. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  54336. */
  54337. destroyTexture( texture, isDefaultTexture = false ) {
  54338. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  54339. }
  54340. /**
  54341. * Returns texture data as a typed array.
  54342. *
  54343. * @async
  54344. * @param {Texture} texture - The texture to copy.
  54345. * @param {number} x - The x coordinate of the copy origin.
  54346. * @param {number} y - The y coordinate of the copy origin.
  54347. * @param {number} width - The width of the copy.
  54348. * @param {number} height - The height of the copy.
  54349. * @param {number} faceIndex - The face index.
  54350. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  54351. */
  54352. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  54353. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  54354. }
  54355. /**
  54356. * Inits a time stamp query for the given render context.
  54357. *
  54358. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  54359. * @param {number} uid - Unique id for the context (e.g. render context id).
  54360. * @param {Object} descriptor - The query descriptor.
  54361. */
  54362. initTimestampQuery( type, uid, descriptor ) {
  54363. if ( ! this.trackTimestamp ) return;
  54364. if ( ! this.timestampQueryPool[ type ] ) {
  54365. // TODO: Variable maxQueries?
  54366. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  54367. }
  54368. const timestampQueryPool = this.timestampQueryPool[ type ];
  54369. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  54370. descriptor.timestampWrites = {
  54371. querySet: timestampQueryPool.querySet,
  54372. beginningOfPassWriteIndex: baseOffset,
  54373. endOfPassWriteIndex: baseOffset + 1,
  54374. };
  54375. }
  54376. // node builder
  54377. /**
  54378. * Returns a node builder for the given render object.
  54379. *
  54380. * @param {RenderObject} object - The render object.
  54381. * @param {Renderer} renderer - The renderer.
  54382. * @return {WGSLNodeBuilder} The node builder.
  54383. */
  54384. createNodeBuilder( object, renderer ) {
  54385. return new WGSLNodeBuilder( object, renderer );
  54386. }
  54387. // program
  54388. /**
  54389. * Creates a shader program from the given programmable stage.
  54390. *
  54391. * @param {ProgrammableStage} program - The programmable stage.
  54392. */
  54393. createProgram( program ) {
  54394. const programGPU = this.get( program );
  54395. programGPU.module = {
  54396. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  54397. entryPoint: 'main'
  54398. };
  54399. }
  54400. /**
  54401. * Destroys the shader program of the given programmable stage.
  54402. *
  54403. * @param {ProgrammableStage} program - The programmable stage.
  54404. */
  54405. destroyProgram( program ) {
  54406. this.delete( program );
  54407. }
  54408. // pipelines
  54409. /**
  54410. * Creates a render pipeline for the given render object.
  54411. *
  54412. * @param {RenderObject} renderObject - The render object.
  54413. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  54414. */
  54415. createRenderPipeline( renderObject, promises ) {
  54416. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  54417. }
  54418. /**
  54419. * Creates a compute pipeline for the given compute node.
  54420. *
  54421. * @param {ComputePipeline} computePipeline - The compute pipeline.
  54422. * @param {Array<BindGroup>} bindings - The bindings.
  54423. */
  54424. createComputePipeline( computePipeline, bindings ) {
  54425. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  54426. }
  54427. /**
  54428. * Prepares the state for encoding render bundles.
  54429. *
  54430. * @param {RenderContext} renderContext - The render context.
  54431. */
  54432. beginBundle( renderContext ) {
  54433. const renderContextData = this.get( renderContext );
  54434. renderContextData._currentPass = renderContextData.currentPass;
  54435. renderContextData._currentSets = renderContextData.currentSets;
  54436. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54437. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  54438. }
  54439. /**
  54440. * After processing render bundles this method finalizes related work.
  54441. *
  54442. * @param {RenderContext} renderContext - The render context.
  54443. * @param {RenderBundle} bundle - The render bundle.
  54444. */
  54445. finishBundle( renderContext, bundle ) {
  54446. const renderContextData = this.get( renderContext );
  54447. const bundleEncoder = renderContextData.currentPass;
  54448. const bundleGPU = bundleEncoder.finish();
  54449. this.get( bundle ).bundleGPU = bundleGPU;
  54450. // restore render pass state
  54451. renderContextData.currentSets = renderContextData._currentSets;
  54452. renderContextData.currentPass = renderContextData._currentPass;
  54453. }
  54454. /**
  54455. * Adds a render bundle to the render context data.
  54456. *
  54457. * @param {RenderContext} renderContext - The render context.
  54458. * @param {RenderBundle} bundle - The render bundle to add.
  54459. */
  54460. addBundle( renderContext, bundle ) {
  54461. const renderContextData = this.get( renderContext );
  54462. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  54463. }
  54464. // bindings
  54465. /**
  54466. * Creates bindings from the given bind group definition.
  54467. *
  54468. * @param {BindGroup} bindGroup - The bind group.
  54469. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54470. * @param {number} cacheIndex - The cache index.
  54471. * @param {number} version - The version.
  54472. */
  54473. createBindings( bindGroup, bindings, cacheIndex, version ) {
  54474. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  54475. }
  54476. /**
  54477. * Updates the given bind group definition.
  54478. *
  54479. * @param {BindGroup} bindGroup - The bind group.
  54480. * @param {Array<BindGroup>} bindings - Array of bind groups.
  54481. * @param {number} cacheIndex - The cache index.
  54482. * @param {number} version - The version.
  54483. */
  54484. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  54485. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  54486. }
  54487. /**
  54488. * Updates a buffer binding.
  54489. *
  54490. * @param {Buffer} binding - The buffer binding to update.
  54491. */
  54492. updateBinding( binding ) {
  54493. this.bindingUtils.updateBinding( binding );
  54494. }
  54495. // attributes
  54496. /**
  54497. * Creates the buffer of an indexed shader attribute.
  54498. *
  54499. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  54500. */
  54501. createIndexAttribute( attribute ) {
  54502. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  54503. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  54504. usage |= GPUBufferUsage.STORAGE;
  54505. }
  54506. this.attributeUtils.createAttribute( attribute, usage );
  54507. }
  54508. /**
  54509. * Creates the GPU buffer of a shader attribute.
  54510. *
  54511. * @param {BufferAttribute} attribute - The buffer attribute.
  54512. */
  54513. createAttribute( attribute ) {
  54514. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54515. }
  54516. /**
  54517. * Creates the GPU buffer of a storage attribute.
  54518. *
  54519. * @param {BufferAttribute} attribute - The buffer attribute.
  54520. */
  54521. createStorageAttribute( attribute ) {
  54522. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54523. }
  54524. /**
  54525. * Creates the GPU buffer of an indirect storage attribute.
  54526. *
  54527. * @param {BufferAttribute} attribute - The buffer attribute.
  54528. */
  54529. createIndirectStorageAttribute( attribute ) {
  54530. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  54531. }
  54532. /**
  54533. * Updates the GPU buffer of a shader attribute.
  54534. *
  54535. * @param {BufferAttribute} attribute - The buffer attribute to update.
  54536. */
  54537. updateAttribute( attribute ) {
  54538. this.attributeUtils.updateAttribute( attribute );
  54539. }
  54540. /**
  54541. * Destroys the GPU buffer of a shader attribute.
  54542. *
  54543. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  54544. */
  54545. destroyAttribute( attribute ) {
  54546. this.attributeUtils.destroyAttribute( attribute );
  54547. }
  54548. // canvas
  54549. /**
  54550. * Triggers an update of the default render pass descriptor.
  54551. */
  54552. updateSize() {
  54553. this.delete( this.renderer.getCanvasTarget() );
  54554. }
  54555. // utils public
  54556. /**
  54557. * Returns the maximum anisotropy texture filtering value.
  54558. *
  54559. * @return {number} The maximum anisotropy texture filtering value.
  54560. */
  54561. getMaxAnisotropy() {
  54562. return 16;
  54563. }
  54564. /**
  54565. * Checks if the given feature is supported by the backend.
  54566. *
  54567. * @param {string} name - The feature's name.
  54568. * @return {boolean} Whether the feature is supported or not.
  54569. */
  54570. hasFeature( name ) {
  54571. return this.device.features.has( name );
  54572. }
  54573. /**
  54574. * Copies data of the given source texture to the given destination texture.
  54575. *
  54576. * @param {Texture} srcTexture - The source texture.
  54577. * @param {Texture} dstTexture - The destination texture.
  54578. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  54579. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  54580. * @param {number} [srcLevel=0] - The mipmap level to copy.
  54581. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  54582. */
  54583. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  54584. let dstX = 0;
  54585. let dstY = 0;
  54586. let dstZ = 0;
  54587. let srcX = 0;
  54588. let srcY = 0;
  54589. let srcZ = 0;
  54590. let srcWidth = srcTexture.image.width;
  54591. let srcHeight = srcTexture.image.height;
  54592. let srcDepth = 1;
  54593. if ( srcRegion !== null ) {
  54594. if ( srcRegion.isBox3 === true ) {
  54595. srcX = srcRegion.min.x;
  54596. srcY = srcRegion.min.y;
  54597. srcZ = srcRegion.min.z;
  54598. srcWidth = srcRegion.max.x - srcRegion.min.x;
  54599. srcHeight = srcRegion.max.y - srcRegion.min.y;
  54600. srcDepth = srcRegion.max.z - srcRegion.min.z;
  54601. } else {
  54602. // Assume it's a Box2
  54603. srcX = srcRegion.min.x;
  54604. srcY = srcRegion.min.y;
  54605. srcWidth = srcRegion.max.x - srcRegion.min.x;
  54606. srcHeight = srcRegion.max.y - srcRegion.min.y;
  54607. srcDepth = 1;
  54608. }
  54609. }
  54610. if ( dstPosition !== null ) {
  54611. dstX = dstPosition.x;
  54612. dstY = dstPosition.y;
  54613. dstZ = dstPosition.z || 0;
  54614. }
  54615. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  54616. const sourceGPU = this.get( srcTexture ).texture;
  54617. const destinationGPU = this.get( dstTexture ).texture;
  54618. encoder.copyTextureToTexture(
  54619. {
  54620. texture: sourceGPU,
  54621. mipLevel: srcLevel,
  54622. origin: { x: srcX, y: srcY, z: srcZ }
  54623. },
  54624. {
  54625. texture: destinationGPU,
  54626. mipLevel: dstLevel,
  54627. origin: { x: dstX, y: dstY, z: dstZ }
  54628. },
  54629. [
  54630. srcWidth,
  54631. srcHeight,
  54632. srcDepth
  54633. ]
  54634. );
  54635. this.device.queue.submit( [ encoder.finish() ] );
  54636. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54637. this.textureUtils.generateMipmaps( dstTexture );
  54638. }
  54639. }
  54640. /**
  54641. * Copies the current bound framebuffer to the given texture.
  54642. *
  54643. * @param {Texture} texture - The destination texture.
  54644. * @param {RenderContext} renderContext - The render context.
  54645. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  54646. */
  54647. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  54648. const renderContextData = this.get( renderContext );
  54649. let sourceGPU = null;
  54650. if ( renderContext.renderTarget ) {
  54651. if ( texture.isDepthTexture ) {
  54652. sourceGPU = this.get( renderContext.depthTexture ).texture;
  54653. } else {
  54654. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  54655. }
  54656. } else {
  54657. if ( texture.isDepthTexture ) {
  54658. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  54659. } else {
  54660. sourceGPU = this.context.getCurrentTexture();
  54661. }
  54662. }
  54663. const destinationGPU = this.get( texture ).texture;
  54664. if ( sourceGPU.format !== destinationGPU.format ) {
  54665. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  54666. return;
  54667. }
  54668. let encoder;
  54669. if ( renderContextData.currentPass ) {
  54670. renderContextData.currentPass.end();
  54671. encoder = renderContextData.encoder;
  54672. } else {
  54673. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  54674. }
  54675. encoder.copyTextureToTexture(
  54676. {
  54677. texture: sourceGPU,
  54678. origin: [ rectangle.x, rectangle.y, 0 ],
  54679. },
  54680. {
  54681. texture: destinationGPU
  54682. },
  54683. [
  54684. rectangle.z,
  54685. rectangle.w
  54686. ]
  54687. );
  54688. if ( renderContextData.currentPass ) {
  54689. const { descriptor } = renderContextData;
  54690. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  54691. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  54692. }
  54693. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  54694. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  54695. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  54696. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  54697. if ( renderContext.viewport ) {
  54698. this.updateViewport( renderContext );
  54699. }
  54700. if ( renderContext.scissor ) {
  54701. const { x, y, width, height } = renderContext.scissorValue;
  54702. renderContextData.currentPass.setScissorRect( x, y, width, height );
  54703. }
  54704. } else {
  54705. this.device.queue.submit( [ encoder.finish() ] );
  54706. }
  54707. if ( texture.generateMipmaps ) {
  54708. this.textureUtils.generateMipmaps( texture );
  54709. }
  54710. }
  54711. dispose() {
  54712. this.textureUtils.dispose();
  54713. }
  54714. }
  54715. /**
  54716. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  54717. *
  54718. * @augments SpotLight
  54719. */
  54720. class IESSpotLight extends SpotLight {
  54721. /**
  54722. * Constructs a new IES spot light.
  54723. *
  54724. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  54725. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  54726. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  54727. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  54728. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  54729. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  54730. */
  54731. constructor( color, intensity, distance, angle, penumbra, decay ) {
  54732. super( color, intensity, distance, angle, penumbra, decay );
  54733. /**
  54734. * TODO
  54735. *
  54736. * @type {?Texture}
  54737. * @default null
  54738. */
  54739. this.iesMap = null;
  54740. }
  54741. copy( source, recursive ) {
  54742. super.copy( source, recursive );
  54743. this.iesMap = source.iesMap;
  54744. return this;
  54745. }
  54746. }
  54747. /**
  54748. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  54749. *
  54750. * @augments SpotLight
  54751. */
  54752. class ProjectorLight extends SpotLight {
  54753. /**
  54754. * Constructs a new projector light.
  54755. *
  54756. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  54757. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  54758. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  54759. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  54760. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  54761. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  54762. */
  54763. constructor( color, intensity, distance, angle, penumbra, decay ) {
  54764. super( color, intensity, distance, angle, penumbra, decay );
  54765. /**
  54766. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  54767. *
  54768. * @type {?number}
  54769. * @default null
  54770. */
  54771. this.aspect = null;
  54772. }
  54773. copy( source, recursive ) {
  54774. super.copy( source, recursive );
  54775. this.aspect = source.aspect;
  54776. return this;
  54777. }
  54778. }
  54779. /**
  54780. * This version of a node library represents the standard version
  54781. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  54782. * techniques and materials to node-based implementations.
  54783. *
  54784. * @private
  54785. * @augments NodeLibrary
  54786. */
  54787. class StandardNodeLibrary extends NodeLibrary {
  54788. /**
  54789. * Constructs a new standard node library.
  54790. */
  54791. constructor() {
  54792. super();
  54793. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  54794. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  54795. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  54796. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  54797. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  54798. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  54799. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  54800. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  54801. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  54802. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  54803. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  54804. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  54805. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  54806. this.addLight( PointLightNode, PointLight );
  54807. this.addLight( DirectionalLightNode, DirectionalLight );
  54808. this.addLight( RectAreaLightNode, RectAreaLight );
  54809. this.addLight( SpotLightNode, SpotLight );
  54810. this.addLight( AmbientLightNode, AmbientLight );
  54811. this.addLight( HemisphereLightNode, HemisphereLight );
  54812. this.addLight( LightProbeNode, LightProbe );
  54813. this.addLight( IESSpotLightNode, IESSpotLight );
  54814. this.addLight( ProjectorLightNode, ProjectorLight );
  54815. this.addToneMapping( linearToneMapping, LinearToneMapping );
  54816. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  54817. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  54818. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  54819. this.addToneMapping( agxToneMapping, AgXToneMapping );
  54820. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  54821. }
  54822. }
  54823. /*
  54824. const debugHandler = {
  54825. get: function ( target, name ) {
  54826. // Add |update
  54827. if ( /^(create|destroy)/.test( name ) ) log( 'WebGPUBackend.' + name );
  54828. return target[ name ];
  54829. }
  54830. };
  54831. */
  54832. /**
  54833. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  54834. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  54835. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  54836. *
  54837. * @augments Renderer
  54838. */
  54839. class WebGPURenderer extends Renderer {
  54840. /**
  54841. * WebGPURenderer options.
  54842. *
  54843. * @typedef {Object} WebGPURenderer~Options
  54844. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  54845. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  54846. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  54847. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  54848. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  54849. * @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.
  54850. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  54851. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  54852. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  54853. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  54854. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  54855. */
  54856. /**
  54857. * Constructs a new WebGPU renderer.
  54858. *
  54859. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  54860. */
  54861. constructor( parameters = {} ) {
  54862. let BackendClass;
  54863. if ( parameters.forceWebGL ) {
  54864. BackendClass = WebGLBackend;
  54865. } else {
  54866. BackendClass = WebGPUBackend;
  54867. parameters.getFallback = () => {
  54868. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  54869. return new WebGLBackend( parameters );
  54870. };
  54871. }
  54872. const backend = new BackendClass( parameters );
  54873. //super( new Proxy( backend, debugHandler ) );
  54874. super( backend, parameters );
  54875. /**
  54876. * The generic default value is overwritten with the
  54877. * standard node library for type mapping.
  54878. *
  54879. * @type {StandardNodeLibrary}
  54880. */
  54881. this.library = new StandardNodeLibrary();
  54882. /**
  54883. * This flag can be used for type testing.
  54884. *
  54885. * @type {boolean}
  54886. * @readonly
  54887. * @default true
  54888. */
  54889. this.isWebGPURenderer = true;
  54890. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  54891. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  54892. }
  54893. }
  54894. }
  54895. /**
  54896. * A specialized group which enables applications access to the
  54897. * Render Bundle API of WebGPU. The group with all its descendant nodes
  54898. * are considered as one render bundle and processed as such by
  54899. * the renderer.
  54900. *
  54901. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  54902. * With a WebGL backend, the group can technically be rendered but without
  54903. * any performance improvements.
  54904. *
  54905. * @augments Group
  54906. */
  54907. class BundleGroup extends Group {
  54908. /**
  54909. * Constructs a new bundle group.
  54910. */
  54911. constructor() {
  54912. super();
  54913. /**
  54914. * This flag can be used for type testing.
  54915. *
  54916. * @type {boolean}
  54917. * @readonly
  54918. * @default true
  54919. */
  54920. this.isBundleGroup = true;
  54921. /**
  54922. * This property is only relevant for detecting types
  54923. * during serialization/deserialization. It should always
  54924. * match the class name.
  54925. *
  54926. * @type {string}
  54927. * @readonly
  54928. * @default 'BundleGroup'
  54929. */
  54930. this.type = 'BundleGroup';
  54931. /**
  54932. * Whether the bundle is static or not. When set to `true`, the structure
  54933. * is assumed to be static and does not change. E.g. no new objects are
  54934. * added to the group
  54935. *
  54936. * If a change is required, an update can still be forced by setting the
  54937. * `needsUpdate` flag to `true`.
  54938. *
  54939. * @type {boolean}
  54940. * @default true
  54941. */
  54942. this.static = true;
  54943. /**
  54944. * The bundle group's version.
  54945. *
  54946. * @type {number}
  54947. * @readonly
  54948. * @default 0
  54949. */
  54950. this.version = 0;
  54951. }
  54952. /**
  54953. * Set this property to `true` when the bundle group has changed.
  54954. *
  54955. * @type {boolean}
  54956. * @default false
  54957. * @param {boolean} value
  54958. */
  54959. set needsUpdate( value ) {
  54960. if ( value === true ) this.version ++;
  54961. }
  54962. }
  54963. /**
  54964. * This module is responsible to manage the post processing setups in apps.
  54965. * You usually create a single instance of this class and use it to define
  54966. * the output of your post processing effect chain.
  54967. * ```js
  54968. * const postProcessing = new PostProcessing( renderer );
  54969. *
  54970. * const scenePass = pass( scene, camera );
  54971. *
  54972. * postProcessing.outputNode = scenePass;
  54973. * ```
  54974. *
  54975. * Note: This module can only be used with `WebGPURenderer`.
  54976. */
  54977. class PostProcessing {
  54978. /**
  54979. * Constructs a new post processing management module.
  54980. *
  54981. * @param {Renderer} renderer - A reference to the renderer.
  54982. * @param {Node<vec4>} outputNode - An optional output node.
  54983. */
  54984. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  54985. /**
  54986. * A reference to the renderer.
  54987. *
  54988. * @type {Renderer}
  54989. */
  54990. this.renderer = renderer;
  54991. /**
  54992. * A node which defines the final output of the post
  54993. * processing. This is usually the last node in a chain
  54994. * of effect nodes.
  54995. *
  54996. * @type {Node<vec4>}
  54997. */
  54998. this.outputNode = outputNode;
  54999. /**
  55000. * Whether the default output tone mapping and color
  55001. * space transformation should be enabled or not.
  55002. *
  55003. * It is enabled by default by it must be disabled when
  55004. * effects must be executed after tone mapping and color
  55005. * space conversion. A typical example is FXAA which
  55006. * requires sRGB input.
  55007. *
  55008. * When set to `false`, the app must control the output
  55009. * transformation with `RenderOutputNode`.
  55010. *
  55011. * ```js
  55012. * const outputPass = renderOutput( scenePass );
  55013. * ```
  55014. *
  55015. * @type {boolean}
  55016. */
  55017. this.outputColorTransform = true;
  55018. /**
  55019. * Must be set to `true` when the output node changes.
  55020. *
  55021. * @type {Node<vec4>}
  55022. */
  55023. this.needsUpdate = true;
  55024. const material = new NodeMaterial();
  55025. material.name = 'PostProcessing';
  55026. /**
  55027. * The full screen quad that is used to render
  55028. * the effects.
  55029. *
  55030. * @private
  55031. * @type {QuadMesh}
  55032. */
  55033. this._quadMesh = new QuadMesh( material );
  55034. this._quadMesh.name = 'Post-Processing';
  55035. /**
  55036. * The context of the post processing stack.
  55037. *
  55038. * @private
  55039. * @type {?Object}
  55040. * @default null
  55041. */
  55042. this._context = null;
  55043. }
  55044. /**
  55045. * When `PostProcessing` is used to apply post processing effects,
  55046. * the application must use this version of `render()` inside
  55047. * its animation loop (not the one from the renderer).
  55048. */
  55049. render() {
  55050. const renderer = this.renderer;
  55051. this._update();
  55052. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  55053. const toneMapping = renderer.toneMapping;
  55054. const outputColorSpace = renderer.outputColorSpace;
  55055. renderer.toneMapping = NoToneMapping;
  55056. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  55057. //
  55058. const currentXR = renderer.xr.enabled;
  55059. renderer.xr.enabled = false;
  55060. this._quadMesh.render( renderer );
  55061. renderer.xr.enabled = currentXR;
  55062. //
  55063. renderer.toneMapping = toneMapping;
  55064. renderer.outputColorSpace = outputColorSpace;
  55065. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  55066. }
  55067. /**
  55068. * Returns the current context of the post processing stack.
  55069. *
  55070. * @readonly
  55071. * @type {?Object}
  55072. */
  55073. get context() {
  55074. return this._context;
  55075. }
  55076. /**
  55077. * Frees internal resources.
  55078. */
  55079. dispose() {
  55080. this._quadMesh.material.dispose();
  55081. }
  55082. /**
  55083. * Updates the state of the module.
  55084. *
  55085. * @private
  55086. */
  55087. _update() {
  55088. if ( this.needsUpdate === true ) {
  55089. const renderer = this.renderer;
  55090. const toneMapping = renderer.toneMapping;
  55091. const outputColorSpace = renderer.outputColorSpace;
  55092. const context = {
  55093. postProcessing: this,
  55094. onBeforePostProcessing: null,
  55095. onAfterPostProcessing: null
  55096. };
  55097. let outputNode = this.outputNode;
  55098. if ( this.outputColorTransform === true ) {
  55099. outputNode = outputNode.context( context );
  55100. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  55101. } else {
  55102. context.toneMapping = toneMapping;
  55103. context.outputColorSpace = outputColorSpace;
  55104. outputNode = outputNode.context( context );
  55105. }
  55106. this._context = context;
  55107. this._quadMesh.material.fragmentNode = outputNode;
  55108. this._quadMesh.material.needsUpdate = true;
  55109. this.needsUpdate = false;
  55110. }
  55111. }
  55112. /**
  55113. * When `PostProcessing` is used to apply post processing effects,
  55114. * the application must use this version of `renderAsync()` inside
  55115. * its animation loop (not the one from the renderer).
  55116. *
  55117. * @async
  55118. * @return {Promise} A Promise that resolves when the render has been finished.
  55119. */
  55120. async renderAsync() {
  55121. this._update();
  55122. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  55123. const renderer = this.renderer;
  55124. const toneMapping = renderer.toneMapping;
  55125. const outputColorSpace = renderer.outputColorSpace;
  55126. renderer.toneMapping = NoToneMapping;
  55127. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  55128. //
  55129. const currentXR = renderer.xr.enabled;
  55130. renderer.xr.enabled = false;
  55131. await this._quadMesh.renderAsync( renderer );
  55132. renderer.xr.enabled = currentXR;
  55133. //
  55134. renderer.toneMapping = toneMapping;
  55135. renderer.outputColorSpace = outputColorSpace;
  55136. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  55137. }
  55138. }
  55139. /**
  55140. * This special type of texture is intended for compute shaders.
  55141. * It can be used to compute the data of a texture with a compute shader.
  55142. *
  55143. * Note: This type of texture can only be used with `WebGPURenderer`
  55144. * and a WebGPU backend.
  55145. *
  55146. * @augments Texture
  55147. */
  55148. class StorageTexture extends Texture {
  55149. /**
  55150. * Constructs a new storage texture.
  55151. *
  55152. * @param {number} [width=1] - The storage texture's width.
  55153. * @param {number} [height=1] - The storage texture's height.
  55154. */
  55155. constructor( width = 1, height = 1 ) {
  55156. super();
  55157. /**
  55158. * The image object which just represents the texture's dimension.
  55159. *
  55160. * @type {{width: number, height: number}}
  55161. */
  55162. this.image = { width, height };
  55163. /**
  55164. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55165. *
  55166. * @type {number}
  55167. */
  55168. this.magFilter = LinearFilter;
  55169. /**
  55170. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55171. *
  55172. * @type {number}
  55173. */
  55174. this.minFilter = LinearFilter;
  55175. /**
  55176. * This flag can be used for type testing.
  55177. *
  55178. * @type {boolean}
  55179. * @readonly
  55180. * @default true
  55181. */
  55182. this.isStorageTexture = true;
  55183. }
  55184. /**
  55185. * Sets the size of the storage texture.
  55186. *
  55187. * @param {number} width - The new width of the storage texture.
  55188. * @param {number} height - The new height of the storage texture.
  55189. */
  55190. setSize( width, height ) {
  55191. if ( this.image.width !== width || this.image.height !== height ) {
  55192. this.image.width = width;
  55193. this.image.height = height;
  55194. this.dispose();
  55195. }
  55196. }
  55197. }
  55198. /**
  55199. * This special type of texture is intended for compute shaders.
  55200. * It can be used to compute the data of a texture with a compute shader.
  55201. *
  55202. * Note: This type of texture can only be used with `WebGPURenderer`
  55203. * and a WebGPU backend.
  55204. *
  55205. * @augments Texture
  55206. */
  55207. class Storage3DTexture extends Texture {
  55208. /**
  55209. * Constructs a new storage texture.
  55210. *
  55211. * @param {number} [width=1] - The storage texture's width.
  55212. * @param {number} [height=1] - The storage texture's height.
  55213. * @param {number} [depth=1] - The storage texture's depth.
  55214. */
  55215. constructor( width = 1, height = 1, depth = 1 ) {
  55216. super();
  55217. //inherited from texture. Must be false for 3DTexture
  55218. this.isArrayTexture = false;
  55219. /**
  55220. * The image object which just represents the texture's dimension.
  55221. *
  55222. * @type {{width: number, height: number, depth: number}}
  55223. */
  55224. this.image = { width, height, depth };
  55225. /**
  55226. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55227. *
  55228. * @type {number}
  55229. */
  55230. this.magFilter = LinearFilter;
  55231. /**
  55232. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55233. *
  55234. * @type {number}
  55235. */
  55236. this.minFilter = LinearFilter;
  55237. /**
  55238. * This defines how the texture is wrapped in the depth direction and corresponds to
  55239. * *W* in UVW mapping.
  55240. *
  55241. * @type {number}
  55242. */
  55243. this.wrapR = ClampToEdgeWrapping;
  55244. /**
  55245. * This flag can be used for type testing.
  55246. *
  55247. * @type {boolean}
  55248. * @readonly
  55249. * @default true
  55250. */
  55251. this.isStorageTexture = true;
  55252. /**
  55253. * Indicates whether this texture is a 3D texture.
  55254. *
  55255. * @type {boolean}
  55256. *
  55257. */
  55258. this.is3DTexture = true;
  55259. }
  55260. /**
  55261. * Sets the size of the storage 3d texture.
  55262. *
  55263. * @param {number} width - The new width of the storage texture.
  55264. * @param {number} height - The new height of the storage texture.
  55265. * @param {number} depth - The new depth of the storage texture.
  55266. */
  55267. setSize( width, height, depth ) {
  55268. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  55269. this.image.width = width;
  55270. this.image.height = height;
  55271. this.image.depth = depth;
  55272. this.dispose();
  55273. }
  55274. }
  55275. }
  55276. /**
  55277. * This special type of texture is intended for compute shaders.
  55278. * It can be used to compute the data of a texture with a compute shader.
  55279. *
  55280. * Note: This type of texture can only be used with `WebGPURenderer`
  55281. * and a WebGPU backend.
  55282. *
  55283. * @augments Texture
  55284. */
  55285. class StorageArrayTexture extends Texture {
  55286. /**
  55287. * Constructs a new storage texture.
  55288. *
  55289. * @param {number} [width=1] - The storage texture's width.
  55290. * @param {number} [height=1] - The storage texture's height.
  55291. * @param {number} [depth=1] - The storage texture's depth.
  55292. */
  55293. constructor( width = 1, height = 1, depth = 1 ) {
  55294. super();
  55295. //inherited from texture
  55296. this.isArrayTexture = true;
  55297. /**
  55298. * The image object which just represents the texture's dimension.
  55299. *
  55300. * @type {{width: number, height: number, depth: number}}
  55301. */
  55302. this.image = { width, height, depth };
  55303. /**
  55304. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  55305. *
  55306. * @type {number}
  55307. */
  55308. this.magFilter = LinearFilter;
  55309. /**
  55310. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  55311. *
  55312. * @type {number}
  55313. */
  55314. this.minFilter = LinearFilter;
  55315. /**
  55316. * This flag can be used for type testing.
  55317. *
  55318. * @type {boolean}
  55319. * @readonly
  55320. * @default true
  55321. */
  55322. this.isStorageTexture = true;
  55323. }
  55324. /**
  55325. * Sets the size of the storage array texture.
  55326. *
  55327. * @param {number} width - The new width of the storage texture.
  55328. * @param {number} height - The new height of the storage texture.
  55329. * @param {number} depth - The new depth of the storage texture.
  55330. */
  55331. setSize( width, height, depth ) {
  55332. if ( this.image.width !== width || this.image.height !== height || this.image.depth !== depth ) {
  55333. this.image.width = width;
  55334. this.image.height = height;
  55335. this.image.depth = depth;
  55336. this.dispose();
  55337. }
  55338. }
  55339. }
  55340. /**
  55341. * This special type of buffer attribute is intended for compute shaders.
  55342. * It can be used to encode draw parameters for indirect draw calls.
  55343. *
  55344. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  55345. * and a WebGPU backend.
  55346. *
  55347. * @augments StorageBufferAttribute
  55348. */
  55349. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  55350. /**
  55351. * Constructs a new storage buffer attribute.
  55352. *
  55353. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  55354. * The subsequent parameter is then obsolete.
  55355. * @param {number} itemSize - The item size.
  55356. */
  55357. constructor( count, itemSize ) {
  55358. super( count, itemSize, Uint32Array );
  55359. /**
  55360. * This flag can be used for type testing.
  55361. *
  55362. * @type {boolean}
  55363. * @readonly
  55364. * @default true
  55365. */
  55366. this.isIndirectStorageBufferAttribute = true;
  55367. }
  55368. }
  55369. /**
  55370. * A loader for loading node objects in the three.js JSON Object/Scene format.
  55371. *
  55372. * @augments Loader
  55373. */
  55374. class NodeLoader extends Loader {
  55375. /**
  55376. * Constructs a new node loader.
  55377. *
  55378. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55379. */
  55380. constructor( manager ) {
  55381. super( manager );
  55382. /**
  55383. * Represents a dictionary of textures.
  55384. *
  55385. * @type {Object<string,Texture>}
  55386. */
  55387. this.textures = {};
  55388. /**
  55389. * Represents a dictionary of node types.
  55390. *
  55391. * @type {Object<string,Node.constructor>}
  55392. */
  55393. this.nodes = {};
  55394. }
  55395. /**
  55396. * Loads the node definitions from the given URL.
  55397. *
  55398. * @param {string} url - The path/URL of the file to be loaded.
  55399. * @param {Function} onLoad - Will be called when load completes.
  55400. * @param {Function} onProgress - Will be called while load progresses.
  55401. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  55402. */
  55403. load( url, onLoad, onProgress, onError ) {
  55404. const loader = new FileLoader( this.manager );
  55405. loader.setPath( this.path );
  55406. loader.setRequestHeader( this.requestHeader );
  55407. loader.setWithCredentials( this.withCredentials );
  55408. loader.load( url, ( text ) => {
  55409. try {
  55410. onLoad( this.parse( JSON.parse( text ) ) );
  55411. } catch ( e ) {
  55412. if ( onError ) {
  55413. onError( e );
  55414. } else {
  55415. error( e );
  55416. }
  55417. this.manager.itemError( url );
  55418. }
  55419. }, onProgress, onError );
  55420. }
  55421. /**
  55422. * Parse the node dependencies for the loaded node.
  55423. *
  55424. * @param {Array<Object>} [json] - The JSON definition
  55425. * @return {Object<string,Node>} A dictionary with node dependencies.
  55426. */
  55427. parseNodes( json ) {
  55428. const nodes = {};
  55429. if ( json !== undefined ) {
  55430. for ( const nodeJSON of json ) {
  55431. const { uuid, type } = nodeJSON;
  55432. nodes[ uuid ] = this.createNodeFromType( type );
  55433. nodes[ uuid ].uuid = uuid;
  55434. }
  55435. const meta = { nodes, textures: this.textures };
  55436. for ( const nodeJSON of json ) {
  55437. nodeJSON.meta = meta;
  55438. const node = nodes[ nodeJSON.uuid ];
  55439. node.deserialize( nodeJSON );
  55440. delete nodeJSON.meta;
  55441. }
  55442. }
  55443. return nodes;
  55444. }
  55445. /**
  55446. * Parses the node from the given JSON.
  55447. *
  55448. * @param {Object} json - The JSON definition
  55449. * @param {string} json.type - The node type.
  55450. * @param {string} json.uuid - The node UUID.
  55451. * @param {Array<Object>} [json.nodes] - The node dependencies.
  55452. * @param {Object} [json.meta] - The meta data.
  55453. * @return {Node} The parsed node.
  55454. */
  55455. parse( json ) {
  55456. const node = this.createNodeFromType( json.type );
  55457. node.uuid = json.uuid;
  55458. const nodes = this.parseNodes( json.nodes );
  55459. const meta = { nodes, textures: this.textures };
  55460. json.meta = meta;
  55461. node.deserialize( json );
  55462. delete json.meta;
  55463. return node;
  55464. }
  55465. /**
  55466. * Defines the dictionary of textures.
  55467. *
  55468. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  55469. * @return {NodeLoader} A reference to this loader.
  55470. */
  55471. setTextures( value ) {
  55472. this.textures = value;
  55473. return this;
  55474. }
  55475. /**
  55476. * Defines the dictionary of node types.
  55477. *
  55478. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55479. * @return {NodeLoader} A reference to this loader.
  55480. */
  55481. setNodes( value ) {
  55482. this.nodes = value;
  55483. return this;
  55484. }
  55485. /**
  55486. * Creates a node object from the given type.
  55487. *
  55488. * @param {string} type - The node type.
  55489. * @return {Node} The created node instance.
  55490. */
  55491. createNodeFromType( type ) {
  55492. if ( this.nodes[ type ] === undefined ) {
  55493. error( 'NodeLoader: Node type not found:', type );
  55494. return float();
  55495. }
  55496. return nodeObject( new this.nodes[ type ]() );
  55497. }
  55498. }
  55499. /**
  55500. * A special type of material loader for loading node materials.
  55501. *
  55502. * @augments MaterialLoader
  55503. */
  55504. class NodeMaterialLoader extends MaterialLoader {
  55505. /**
  55506. * Constructs a new node material loader.
  55507. *
  55508. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55509. */
  55510. constructor( manager ) {
  55511. super( manager );
  55512. /**
  55513. * Represents a dictionary of node types.
  55514. *
  55515. * @type {Object<string,Node.constructor>}
  55516. */
  55517. this.nodes = {};
  55518. /**
  55519. * Represents a dictionary of node material types.
  55520. *
  55521. * @type {Object<string,NodeMaterial.constructor>}
  55522. */
  55523. this.nodeMaterials = {};
  55524. }
  55525. /**
  55526. * Parses the node material from the given JSON.
  55527. *
  55528. * @param {Object} json - The JSON definition
  55529. * @return {NodeMaterial}. The parsed material.
  55530. */
  55531. parse( json ) {
  55532. const material = super.parse( json );
  55533. const nodes = this.nodes;
  55534. const inputNodes = json.inputNodes;
  55535. for ( const property in inputNodes ) {
  55536. const uuid = inputNodes[ property ];
  55537. material[ property ] = nodes[ uuid ];
  55538. }
  55539. return material;
  55540. }
  55541. /**
  55542. * Defines the dictionary of node types.
  55543. *
  55544. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55545. * @return {NodeLoader} A reference to this loader.
  55546. */
  55547. setNodes( value ) {
  55548. this.nodes = value;
  55549. return this;
  55550. }
  55551. /**
  55552. * Defines the dictionary of node material types.
  55553. *
  55554. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  55555. * @return {NodeLoader} A reference to this loader.
  55556. */
  55557. setNodeMaterials( value ) {
  55558. this.nodeMaterials = value;
  55559. return this;
  55560. }
  55561. /**
  55562. * Creates a node material from the given type.
  55563. *
  55564. * @param {string} type - The node material type.
  55565. * @return {Node} The created node material instance.
  55566. */
  55567. createMaterialFromType( type ) {
  55568. const materialClass = this.nodeMaterials[ type ];
  55569. if ( materialClass !== undefined ) {
  55570. return new materialClass();
  55571. }
  55572. return super.createMaterialFromType( type );
  55573. }
  55574. }
  55575. /**
  55576. * A special type of object loader for loading 3D objects using
  55577. * node materials.
  55578. *
  55579. * @augments ObjectLoader
  55580. */
  55581. class NodeObjectLoader extends ObjectLoader {
  55582. /**
  55583. * Constructs a new node object loader.
  55584. *
  55585. * @param {LoadingManager} [manager] - A reference to a loading manager.
  55586. */
  55587. constructor( manager ) {
  55588. super( manager );
  55589. /**
  55590. * Represents a dictionary of node types.
  55591. *
  55592. * @type {Object<string,Node.constructor>}
  55593. */
  55594. this.nodes = {};
  55595. /**
  55596. * Represents a dictionary of node material types.
  55597. *
  55598. * @type {Object<string,NodeMaterial.constructor>}
  55599. */
  55600. this.nodeMaterials = {};
  55601. /**
  55602. * A reference to hold the `nodes` JSON property.
  55603. *
  55604. * @private
  55605. * @type {?Object[]}
  55606. */
  55607. this._nodesJSON = null;
  55608. }
  55609. /**
  55610. * Defines the dictionary of node types.
  55611. *
  55612. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  55613. * @return {NodeObjectLoader} A reference to this loader.
  55614. */
  55615. setNodes( value ) {
  55616. this.nodes = value;
  55617. return this;
  55618. }
  55619. /**
  55620. * Defines the dictionary of node material types.
  55621. *
  55622. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  55623. * @return {NodeObjectLoader} A reference to this loader.
  55624. */
  55625. setNodeMaterials( value ) {
  55626. this.nodeMaterials = value;
  55627. return this;
  55628. }
  55629. /**
  55630. * Parses the node objects from the given JSON.
  55631. *
  55632. * @param {Object} json - The JSON definition
  55633. * @param {Function} onLoad - The onLoad callback function.
  55634. * @return {Object3D}. The parsed 3D object.
  55635. */
  55636. parse( json, onLoad ) {
  55637. this._nodesJSON = json.nodes;
  55638. const data = super.parse( json, onLoad );
  55639. this._nodesJSON = null; // dispose
  55640. return data;
  55641. }
  55642. /**
  55643. * Parses the node objects from the given JSON and textures.
  55644. *
  55645. * @param {Object[]} json - The JSON definition
  55646. * @param {Object<string,Texture>} textures - The texture library.
  55647. * @return {Object<string,Node>}. The parsed nodes.
  55648. */
  55649. parseNodes( json, textures ) {
  55650. if ( json !== undefined ) {
  55651. const loader = new NodeLoader();
  55652. loader.setNodes( this.nodes );
  55653. loader.setTextures( textures );
  55654. return loader.parseNodes( json );
  55655. }
  55656. return {};
  55657. }
  55658. /**
  55659. * Parses the node objects from the given JSON and textures.
  55660. *
  55661. * @param {Object} json - The JSON definition
  55662. * @param {Object<string,Texture>} textures - The texture library.
  55663. * @return {Object<string,NodeMaterial>}. The parsed materials.
  55664. */
  55665. parseMaterials( json, textures ) {
  55666. const materials = {};
  55667. if ( json !== undefined ) {
  55668. const nodes = this.parseNodes( this._nodesJSON, textures );
  55669. const loader = new NodeMaterialLoader();
  55670. loader.setTextures( textures );
  55671. loader.setNodes( nodes );
  55672. loader.setNodeMaterials( this.nodeMaterials );
  55673. for ( let i = 0, l = json.length; i < l; i ++ ) {
  55674. const data = json[ i ];
  55675. materials[ data.uuid ] = loader.parse( data );
  55676. }
  55677. }
  55678. return materials;
  55679. }
  55680. }
  55681. /**
  55682. * In earlier three.js versions, clipping was defined globally
  55683. * on the renderer or on material level. This special version of
  55684. * `THREE.Group` allows to encode the clipping state into the scene
  55685. * graph. Meaning if you create an instance of this group, all
  55686. * descendant 3D objects will be affected by the respective clipping
  55687. * planes.
  55688. *
  55689. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  55690. *
  55691. * @augments Group
  55692. */
  55693. class ClippingGroup extends Group {
  55694. /**
  55695. * Constructs a new clipping group.
  55696. */
  55697. constructor() {
  55698. super();
  55699. /**
  55700. * This flag can be used for type testing.
  55701. *
  55702. * @type {boolean}
  55703. * @readonly
  55704. * @default true
  55705. */
  55706. this.isClippingGroup = true;
  55707. /**
  55708. * An array with clipping planes.
  55709. *
  55710. * @type {Array<Plane>}
  55711. */
  55712. this.clippingPlanes = [];
  55713. /**
  55714. * Whether clipping should be enabled or not.
  55715. *
  55716. * @type {boolean}
  55717. * @default true
  55718. */
  55719. this.enabled = true;
  55720. /**
  55721. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  55722. *
  55723. * @type {boolean}
  55724. * @default false
  55725. */
  55726. this.clipIntersection = false;
  55727. /**
  55728. * Whether shadows should be clipped or not.
  55729. *
  55730. * @type {boolean}
  55731. * @default false
  55732. */
  55733. this.clipShadows = false;
  55734. }
  55735. }
  55736. 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号