three.webgpu.nodes.js 1.8 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136
  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, 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, TimestampQuery, 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. morphChanged = true;
  330. }
  331. }
  332. if ( morphChanged ) return true;
  333. }
  334. // lights
  335. if ( renderObjectData.lights ) {
  336. for ( let i = 0; i < lightsData.length; i ++ ) {
  337. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  338. return false;
  339. }
  340. }
  341. }
  342. // center
  343. if ( renderObjectData.center ) {
  344. if ( renderObjectData.center.equals( object.center ) === false ) {
  345. renderObjectData.center.copy( object.center );
  346. return true;
  347. }
  348. }
  349. // bundle
  350. if ( renderObject.bundle !== null ) {
  351. renderObjectData.version = renderObject.bundle.version;
  352. }
  353. return true;
  354. }
  355. /**
  356. * Returns the lights data for the given material lights.
  357. *
  358. * @param {Array<Light>} materialLights - The material lights.
  359. * @return {Array<Object>} The lights data for the given material lights.
  360. */
  361. getLightsData( materialLights ) {
  362. const lights = [];
  363. for ( const light of materialLights ) {
  364. if ( light.isSpotLight === true && light.map !== null ) {
  365. // only add lights that have a map
  366. lights.push( { map: light.map.version } );
  367. }
  368. }
  369. return lights;
  370. }
  371. /**
  372. * Returns the lights for the given lights node and render ID.
  373. *
  374. * @param {LightsNode} lightsNode - The lights node.
  375. * @param {number} renderId - The render ID.
  376. * @return {Array<Object>} The lights for the given lights node and render ID.
  377. */
  378. getLights( lightsNode, renderId ) {
  379. if ( _lightsCache.has( lightsNode ) ) {
  380. const cached = _lightsCache.get( lightsNode );
  381. if ( cached.renderId === renderId ) {
  382. return cached.lightsData;
  383. }
  384. }
  385. const lightsData = this.getLightsData( lightsNode.getLights() );
  386. _lightsCache.set( lightsNode, { renderId, lightsData } );
  387. return lightsData;
  388. }
  389. /**
  390. * Checks if the given render object requires a refresh.
  391. *
  392. * @param {RenderObject} renderObject - The render object.
  393. * @param {NodeFrame} nodeFrame - The current node frame.
  394. * @return {boolean} Whether the given render object requires a refresh or not.
  395. */
  396. needsRefresh( renderObject, nodeFrame ) {
  397. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  398. return true;
  399. const { renderId } = nodeFrame;
  400. if ( this.renderId !== renderId ) {
  401. this.renderId = renderId;
  402. return true;
  403. }
  404. const isStatic = renderObject.object.static === true;
  405. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  406. if ( isStatic || isBundle )
  407. return false;
  408. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  409. const notEqual = this.equals( renderObject, lightsData ) !== true;
  410. return notEqual;
  411. }
  412. }
  413. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  414. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  415. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  416. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  417. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  418. function cyrb53( value, seed = 0 ) {
  419. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  420. if ( value instanceof Array ) {
  421. for ( let i = 0, val; i < value.length; i ++ ) {
  422. val = value[ i ];
  423. h1 = Math.imul( h1 ^ val, 2654435761 );
  424. h2 = Math.imul( h2 ^ val, 1597334677 );
  425. }
  426. } else {
  427. for ( let i = 0, ch; i < value.length; i ++ ) {
  428. ch = value.charCodeAt( i );
  429. h1 = Math.imul( h1 ^ ch, 2654435761 );
  430. h2 = Math.imul( h2 ^ ch, 1597334677 );
  431. }
  432. }
  433. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  434. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  435. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  436. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  437. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  438. }
  439. /**
  440. * Computes a hash for the given string.
  441. *
  442. * @method
  443. * @param {string} str - The string to be hashed.
  444. * @return {number} The hash.
  445. */
  446. const hashString = ( str ) => cyrb53( str );
  447. /**
  448. * Computes a hash for the given array.
  449. *
  450. * @method
  451. * @param {Array<number>} array - The array to be hashed.
  452. * @return {number} The hash.
  453. */
  454. const hashArray = ( array ) => cyrb53( array );
  455. /**
  456. * Computes a hash for the given list of parameters.
  457. *
  458. * @method
  459. * @param {...number} params - A list of parameters.
  460. * @return {number} The hash.
  461. */
  462. const hash$1 = ( ...params ) => cyrb53( params );
  463. /**
  464. * Computes a cache key for the given node.
  465. *
  466. * @method
  467. * @param {Object|Node} object - The object to be hashed.
  468. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  469. * @return {number} The hash.
  470. */
  471. function getCacheKey$1( object, force = false ) {
  472. const values = [];
  473. if ( object.isNode === true ) {
  474. values.push( object.id );
  475. }
  476. for ( const { property, childNode } of getNodeChildren( object ) ) {
  477. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  478. }
  479. return cyrb53( values );
  480. }
  481. /**
  482. * This generator function can be used to iterate over the node children
  483. * of the given object.
  484. *
  485. * @generator
  486. * @param {Object} node - The object to be hashed.
  487. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  488. * @yields {Object} A result node holding the property, index (if available) and the child node.
  489. */
  490. function* getNodeChildren( node, toJSON = false ) {
  491. for ( const property of Object.getOwnPropertyNames( node ) ) {
  492. // Ignore private properties.
  493. if ( property.startsWith( '_' ) === true ) continue;
  494. const object = node[ property ];
  495. if ( Array.isArray( object ) === true ) {
  496. for ( let i = 0; i < object.length; i ++ ) {
  497. const child = object[ i ];
  498. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  499. yield { property, index: i, childNode: child };
  500. }
  501. }
  502. } else if ( object && object.isNode === true ) {
  503. yield { property, childNode: object };
  504. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  505. for ( const subProperty in object ) {
  506. // Ignore private properties.
  507. if ( subProperty.startsWith( '_' ) === true ) continue;
  508. const child = object[ subProperty ];
  509. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  510. yield { property, index: subProperty, childNode: child };
  511. }
  512. }
  513. }
  514. }
  515. }
  516. const typeFromLength = /*@__PURE__*/ new Map( [
  517. [ 1, 'float' ],
  518. [ 2, 'vec2' ],
  519. [ 3, 'vec3' ],
  520. [ 4, 'vec4' ],
  521. [ 9, 'mat3' ],
  522. [ 16, 'mat4' ]
  523. ] );
  524. const dataFromObject = /*@__PURE__*/ new WeakMap();
  525. /**
  526. * Returns the data type for the given the length.
  527. *
  528. * @method
  529. * @param {number} length - The length.
  530. * @return {string} The data type.
  531. */
  532. function getTypeFromLength( length ) {
  533. return typeFromLength.get( length );
  534. }
  535. /**
  536. * Returns the typed array for the given data type.
  537. *
  538. * @method
  539. * @param {string} type - The data type.
  540. * @return {TypedArray} The typed array.
  541. */
  542. function getTypedArrayFromType( type ) {
  543. // Handle component type for vectors and matrices
  544. if ( /[iu]?vec\d/.test( type ) ) {
  545. // Handle int vectors
  546. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  547. // Handle uint vectors
  548. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  549. // Default to float vectors
  550. return Float32Array;
  551. }
  552. // Handle matrices (always float)
  553. if ( /mat\d/.test( type ) ) return Float32Array;
  554. // Basic types
  555. if ( /float/.test( type ) ) return Float32Array;
  556. if ( /uint/.test( type ) ) return Uint32Array;
  557. if ( /int/.test( type ) ) return Int32Array;
  558. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  559. }
  560. /**
  561. * Returns the length for the given data type.
  562. *
  563. * @method
  564. * @param {string} type - The data type.
  565. * @return {number} The length.
  566. */
  567. function getLengthFromType( type ) {
  568. if ( /float|int|uint/.test( type ) ) return 1;
  569. if ( /vec2/.test( type ) ) return 2;
  570. if ( /vec3/.test( type ) ) return 3;
  571. if ( /vec4/.test( type ) ) return 4;
  572. if ( /mat2/.test( type ) ) return 4;
  573. if ( /mat3/.test( type ) ) return 9;
  574. if ( /mat4/.test( type ) ) return 16;
  575. error( 'TSL: Unsupported type:', type );
  576. }
  577. /**
  578. * Returns the gpu memory length for the given data type.
  579. *
  580. * @method
  581. * @param {string} type - The data type.
  582. * @return {number} The length.
  583. */
  584. function getMemoryLengthFromType( type ) {
  585. if ( /float|int|uint/.test( type ) ) return 1;
  586. if ( /vec2/.test( type ) ) return 2;
  587. if ( /vec3/.test( type ) ) return 3;
  588. if ( /vec4/.test( type ) ) return 4;
  589. if ( /mat2/.test( type ) ) return 4;
  590. if ( /mat3/.test( type ) ) return 12;
  591. if ( /mat4/.test( type ) ) return 16;
  592. error( 'TSL: Unsupported type:', type );
  593. }
  594. /**
  595. * Returns the byte boundary for the given data type.
  596. *
  597. * @method
  598. * @param {string} type - The data type.
  599. * @return {number} The byte boundary.
  600. */
  601. function getByteBoundaryFromType( type ) {
  602. if ( /float|int|uint/.test( type ) ) return 4;
  603. if ( /vec2/.test( type ) ) return 8;
  604. if ( /vec3/.test( type ) ) return 16;
  605. if ( /vec4/.test( type ) ) return 16;
  606. if ( /mat2/.test( type ) ) return 8;
  607. if ( /mat3/.test( type ) ) return 48;
  608. if ( /mat4/.test( type ) ) return 64;
  609. error( 'TSL: Unsupported type:', type );
  610. }
  611. /**
  612. * Returns the data type for the given value.
  613. *
  614. * @method
  615. * @param {any} value - The value.
  616. * @return {?string} The data type.
  617. */
  618. function getValueType( value ) {
  619. if ( value === undefined || value === null ) return null;
  620. const typeOf = typeof value;
  621. if ( value.isNode === true ) {
  622. return 'node';
  623. } else if ( typeOf === 'number' ) {
  624. return 'float';
  625. } else if ( typeOf === 'boolean' ) {
  626. return 'bool';
  627. } else if ( typeOf === 'string' ) {
  628. return 'string';
  629. } else if ( typeOf === 'function' ) {
  630. return 'shader';
  631. } else if ( value.isVector2 === true ) {
  632. return 'vec2';
  633. } else if ( value.isVector3 === true ) {
  634. return 'vec3';
  635. } else if ( value.isVector4 === true ) {
  636. return 'vec4';
  637. } else if ( value.isMatrix2 === true ) {
  638. return 'mat2';
  639. } else if ( value.isMatrix3 === true ) {
  640. return 'mat3';
  641. } else if ( value.isMatrix4 === true ) {
  642. return 'mat4';
  643. } else if ( value.isColor === true ) {
  644. return 'color';
  645. } else if ( value instanceof ArrayBuffer ) {
  646. return 'ArrayBuffer';
  647. }
  648. return null;
  649. }
  650. /**
  651. * Returns the value/object for the given data type and parameters.
  652. *
  653. * @method
  654. * @param {string} type - The given type.
  655. * @param {...any} params - A parameter list.
  656. * @return {any} The value/object.
  657. */
  658. function getValueFromType( type, ...params ) {
  659. const last4 = type ? type.slice( -4 ) : undefined;
  660. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  661. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  662. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  663. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  664. }
  665. if ( type === 'color' ) {
  666. return new Color( ...params );
  667. } else if ( last4 === 'vec2' ) {
  668. return new Vector2( ...params );
  669. } else if ( last4 === 'vec3' ) {
  670. return new Vector3( ...params );
  671. } else if ( last4 === 'vec4' ) {
  672. return new Vector4( ...params );
  673. } else if ( last4 === 'mat2' ) {
  674. return new Matrix2( ...params );
  675. } else if ( last4 === 'mat3' ) {
  676. return new Matrix3( ...params );
  677. } else if ( last4 === 'mat4' ) {
  678. return new Matrix4( ...params );
  679. } else if ( type === 'bool' ) {
  680. return params[ 0 ] || false;
  681. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  682. return params[ 0 ] || 0;
  683. } else if ( type === 'string' ) {
  684. return params[ 0 ] || '';
  685. } else if ( type === 'ArrayBuffer' ) {
  686. return base64ToArrayBuffer( params[ 0 ] );
  687. }
  688. return null;
  689. }
  690. /**
  691. * Gets the object data that can be shared between different rendering steps.
  692. *
  693. * @param {Object} object - The object to get the data for.
  694. * @return {Object} The object data.
  695. */
  696. function getDataFromObject( object ) {
  697. let data = dataFromObject.get( object );
  698. if ( data === undefined ) {
  699. data = {};
  700. dataFromObject.set( object, data );
  701. }
  702. return data;
  703. }
  704. /**
  705. * Converts the given array buffer to a Base64 string.
  706. *
  707. * @method
  708. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  709. * @return {string} The Base64 string.
  710. */
  711. function arrayBufferToBase64( arrayBuffer ) {
  712. let chars = '';
  713. const array = new Uint8Array( arrayBuffer );
  714. for ( let i = 0; i < array.length; i ++ ) {
  715. chars += String.fromCharCode( array[ i ] );
  716. }
  717. return btoa( chars );
  718. }
  719. /**
  720. * Converts the given Base64 string to an array buffer.
  721. *
  722. * @method
  723. * @param {string} base64 - The Base64 string.
  724. * @return {ArrayBuffer} The array buffer.
  725. */
  726. function base64ToArrayBuffer( base64 ) {
  727. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  728. }
  729. var NodeUtils = /*#__PURE__*/Object.freeze({
  730. __proto__: null,
  731. arrayBufferToBase64: arrayBufferToBase64,
  732. base64ToArrayBuffer: base64ToArrayBuffer,
  733. getByteBoundaryFromType: getByteBoundaryFromType,
  734. getCacheKey: getCacheKey$1,
  735. getDataFromObject: getDataFromObject,
  736. getLengthFromType: getLengthFromType,
  737. getMemoryLengthFromType: getMemoryLengthFromType,
  738. getNodeChildren: getNodeChildren,
  739. getTypeFromLength: getTypeFromLength,
  740. getTypedArrayFromType: getTypedArrayFromType,
  741. getValueFromType: getValueFromType,
  742. getValueType: getValueType,
  743. hash: hash$1,
  744. hashArray: hashArray,
  745. hashString: hashString
  746. });
  747. /**
  748. * Possible shader stages.
  749. *
  750. * @property {string} VERTEX The vertex shader stage.
  751. * @property {string} FRAGMENT The fragment shader stage.
  752. */
  753. const NodeShaderStage = {
  754. VERTEX: 'vertex',
  755. FRAGMENT: 'fragment'
  756. };
  757. /**
  758. * Update types of a node.
  759. *
  760. * @property {string} NONE The update method is not executed.
  761. * @property {string} FRAME The update method is executed per frame.
  762. * @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.
  763. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  764. */
  765. const NodeUpdateType = {
  766. NONE: 'none',
  767. FRAME: 'frame',
  768. RENDER: 'render',
  769. OBJECT: 'object'
  770. };
  771. /**
  772. * Data types of a node.
  773. *
  774. * @property {string} BOOLEAN Boolean type.
  775. * @property {string} INTEGER Integer type.
  776. * @property {string} FLOAT Float type.
  777. * @property {string} VECTOR2 Two-dimensional vector type.
  778. * @property {string} VECTOR3 Three-dimensional vector type.
  779. * @property {string} VECTOR4 Four-dimensional vector type.
  780. * @property {string} MATRIX2 2x2 matrix type.
  781. * @property {string} MATRIX3 3x3 matrix type.
  782. * @property {string} MATRIX4 4x4 matrix type.
  783. */
  784. const NodeType = {
  785. BOOLEAN: 'bool',
  786. INTEGER: 'int',
  787. FLOAT: 'float',
  788. VECTOR2: 'vec2',
  789. VECTOR3: 'vec3',
  790. VECTOR4: 'vec4',
  791. MATRIX2: 'mat2',
  792. MATRIX3: 'mat3',
  793. MATRIX4: 'mat4'
  794. };
  795. /**
  796. * Access types of a node. These are relevant for compute and storage usage.
  797. *
  798. * @property {string} READ_ONLY Read-only access
  799. * @property {string} WRITE_ONLY Write-only access.
  800. * @property {string} READ_WRITE Read and write access.
  801. */
  802. const NodeAccess = {
  803. READ_ONLY: 'readOnly',
  804. WRITE_ONLY: 'writeOnly',
  805. READ_WRITE: 'readWrite',
  806. };
  807. const defaultShaderStages = [ 'fragment', 'vertex' ];
  808. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  809. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  810. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  811. const _parentBuildStage = {
  812. analyze: 'setup',
  813. generate: 'analyze'
  814. };
  815. let _nodeId = 0;
  816. /**
  817. * Base class for all nodes.
  818. *
  819. * @augments EventDispatcher
  820. */
  821. class Node extends EventDispatcher {
  822. static get type() {
  823. return 'Node';
  824. }
  825. /**
  826. * Constructs a new node.
  827. *
  828. * @param {?string} nodeType - The node type.
  829. */
  830. constructor( nodeType = null ) {
  831. super();
  832. /**
  833. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  834. *
  835. * @type {?string}
  836. * @default null
  837. */
  838. this.nodeType = nodeType;
  839. /**
  840. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  841. *
  842. * @type {string}
  843. * @default 'none'
  844. */
  845. this.updateType = NodeUpdateType.NONE;
  846. /**
  847. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  848. *
  849. * @type {string}
  850. * @default 'none'
  851. */
  852. this.updateBeforeType = NodeUpdateType.NONE;
  853. /**
  854. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  855. *
  856. * @type {string}
  857. * @default 'none'
  858. */
  859. this.updateAfterType = NodeUpdateType.NONE;
  860. /**
  861. * The UUID of the node.
  862. *
  863. * @type {string}
  864. * @readonly
  865. */
  866. this.uuid = MathUtils.generateUUID();
  867. /**
  868. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  869. *
  870. * @type {number}
  871. * @readonly
  872. * @default 0
  873. */
  874. this.version = 0;
  875. /**
  876. * Whether this node is global or not. This property is relevant for the internal
  877. * node caching system. All nodes which should be declared just once should
  878. * set this flag to `true` (a typical example is {@link AttributeNode}).
  879. *
  880. * @type {boolean}
  881. * @default false
  882. */
  883. this.global = false;
  884. /**
  885. * Create a list of parents for this node during the build process.
  886. *
  887. * @type {boolean}
  888. * @default false
  889. */
  890. this.parents = false;
  891. /**
  892. * This flag can be used for type testing.
  893. *
  894. * @type {boolean}
  895. * @readonly
  896. * @default true
  897. */
  898. this.isNode = true;
  899. // private
  900. /**
  901. * The cache key of this node.
  902. *
  903. * @private
  904. * @type {?number}
  905. * @default null
  906. */
  907. this._cacheKey = null;
  908. /**
  909. * The cache key 's version.
  910. *
  911. * @private
  912. * @type {number}
  913. * @default 0
  914. */
  915. this._cacheKeyVersion = 0;
  916. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  917. }
  918. /**
  919. * Set this property to `true` when the node should be regenerated.
  920. *
  921. * @type {boolean}
  922. * @default false
  923. * @param {boolean} value
  924. */
  925. set needsUpdate( value ) {
  926. if ( value === true ) {
  927. this.version ++;
  928. }
  929. }
  930. /**
  931. * The type of the class. The value is usually the constructor name.
  932. *
  933. * @type {string}
  934. * @readonly
  935. */
  936. get type() {
  937. return this.constructor.type;
  938. }
  939. /**
  940. * Convenient method for defining {@link Node#update}.
  941. *
  942. * @param {Function} callback - The update method.
  943. * @param {string} updateType - The update type.
  944. * @return {Node} A reference to this node.
  945. */
  946. onUpdate( callback, updateType ) {
  947. this.updateType = updateType;
  948. this.update = callback.bind( this );
  949. return this;
  950. }
  951. /**
  952. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  953. * this method automatically sets the update type to `FRAME`.
  954. *
  955. * @param {Function} callback - The update method.
  956. * @return {Node} A reference to this node.
  957. */
  958. onFrameUpdate( callback ) {
  959. return this.onUpdate( callback, NodeUpdateType.FRAME );
  960. }
  961. /**
  962. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  963. * this method automatically sets the update type to `RENDER`.
  964. *
  965. * @param {Function} callback - The update method.
  966. * @return {Node} A reference to this node.
  967. */
  968. onRenderUpdate( callback ) {
  969. return this.onUpdate( callback, NodeUpdateType.RENDER );
  970. }
  971. /**
  972. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  973. * this method automatically sets the update type to `OBJECT`.
  974. *
  975. * @param {Function} callback - The update method.
  976. * @return {Node} A reference to this node.
  977. */
  978. onObjectUpdate( callback ) {
  979. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  980. }
  981. /**
  982. * Convenient method for defining {@link Node#updateReference}.
  983. *
  984. * @param {Function} callback - The update method.
  985. * @return {Node} A reference to this node.
  986. */
  987. onReference( callback ) {
  988. this.updateReference = callback.bind( this );
  989. return this;
  990. }
  991. /**
  992. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  993. * to such objects based on a given state (e.g. the current node frame or builder).
  994. *
  995. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  996. * @return {any} The updated reference.
  997. */
  998. updateReference( /*state*/ ) {
  999. return this;
  1000. }
  1001. /**
  1002. * By default this method returns the value of the {@link Node#global} flag. This method
  1003. * can be overwritten in derived classes if an analytical way is required to determine the
  1004. * global cache referring to the current shader-stage.
  1005. *
  1006. * @param {NodeBuilder} builder - The current node builder.
  1007. * @return {boolean} Whether this node is global or not.
  1008. */
  1009. isGlobal( /*builder*/ ) {
  1010. return this.global;
  1011. }
  1012. /**
  1013. * Generator function that can be used to iterate over the child nodes.
  1014. *
  1015. * @generator
  1016. * @yields {Node} A child node.
  1017. */
  1018. * getChildren() {
  1019. for ( const { childNode } of getNodeChildren( this ) ) {
  1020. yield childNode;
  1021. }
  1022. }
  1023. /**
  1024. * Calling this method dispatches the `dispose` event. This event can be used
  1025. * to register event listeners for clean up tasks.
  1026. */
  1027. dispose() {
  1028. this.dispatchEvent( { type: 'dispose' } );
  1029. }
  1030. /**
  1031. * Callback for {@link Node#traverse}.
  1032. *
  1033. * @callback traverseCallback
  1034. * @param {Node} node - The current node.
  1035. */
  1036. /**
  1037. * Can be used to traverse through the node's hierarchy.
  1038. *
  1039. * @param {traverseCallback} callback - A callback that is executed per node.
  1040. */
  1041. traverse( callback ) {
  1042. callback( this );
  1043. for ( const childNode of this.getChildren() ) {
  1044. childNode.traverse( callback );
  1045. }
  1046. }
  1047. /**
  1048. * Returns the cache key for this node.
  1049. *
  1050. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1051. * @return {number} The cache key of the node.
  1052. */
  1053. getCacheKey( force = false ) {
  1054. force = force || this.version !== this._cacheKeyVersion;
  1055. if ( force === true || this._cacheKey === null ) {
  1056. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1057. this._cacheKeyVersion = this.version;
  1058. }
  1059. return this._cacheKey;
  1060. }
  1061. /**
  1062. * Generate a custom cache key for this node.
  1063. *
  1064. * @return {number} The cache key of the node.
  1065. */
  1066. customCacheKey() {
  1067. return 0;
  1068. }
  1069. /**
  1070. * Returns the references to this node which is by default `this`.
  1071. *
  1072. * @return {Node} A reference to this node.
  1073. */
  1074. getScope() {
  1075. return this;
  1076. }
  1077. /**
  1078. * Returns the hash of the node which is used to identify the node. By default it's
  1079. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1080. * depending on their implementation.
  1081. *
  1082. * @param {NodeBuilder} builder - The current node builder.
  1083. * @return {string} The hash.
  1084. */
  1085. getHash( /*builder*/ ) {
  1086. return this.uuid;
  1087. }
  1088. /**
  1089. * Returns the update type of {@link Node#update}.
  1090. *
  1091. * @return {NodeUpdateType} The update type.
  1092. */
  1093. getUpdateType() {
  1094. return this.updateType;
  1095. }
  1096. /**
  1097. * Returns the update type of {@link Node#updateBefore}.
  1098. *
  1099. * @return {NodeUpdateType} The update type.
  1100. */
  1101. getUpdateBeforeType() {
  1102. return this.updateBeforeType;
  1103. }
  1104. /**
  1105. * Returns the update type of {@link Node#updateAfter}.
  1106. *
  1107. * @return {NodeUpdateType} The update type.
  1108. */
  1109. getUpdateAfterType() {
  1110. return this.updateAfterType;
  1111. }
  1112. /**
  1113. * Certain types are composed of multiple elements. For example a `vec3`
  1114. * is composed of three `float` values. This method returns the type of
  1115. * these elements.
  1116. *
  1117. * @param {NodeBuilder} builder - The current node builder.
  1118. * @return {string} The type of the node.
  1119. */
  1120. getElementType( builder ) {
  1121. const type = this.getNodeType( builder );
  1122. const elementType = builder.getElementType( type );
  1123. return elementType;
  1124. }
  1125. /**
  1126. * Returns the node member type for the given name.
  1127. *
  1128. * @param {NodeBuilder} builder - The current node builder.
  1129. * @param {string} name - The name of the member.
  1130. * @return {string} The type of the node.
  1131. */
  1132. getMemberType( /*builder, name*/ ) {
  1133. return 'void';
  1134. }
  1135. /**
  1136. * Returns the node's type.
  1137. *
  1138. * @param {NodeBuilder} builder - The current node builder.
  1139. * @return {string} The type of the node.
  1140. */
  1141. getNodeType( builder ) {
  1142. const nodeProperties = builder.getNodeProperties( this );
  1143. if ( nodeProperties.outputNode ) {
  1144. return nodeProperties.outputNode.getNodeType( builder );
  1145. }
  1146. return this.nodeType;
  1147. }
  1148. /**
  1149. * This method is used during the build process of a node and ensures
  1150. * equal nodes are not built multiple times but just once. For example if
  1151. * `attribute( 'uv' )` is used multiple times by the user, the build
  1152. * process makes sure to process just the first node.
  1153. *
  1154. * @param {NodeBuilder} builder - The current node builder.
  1155. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1156. */
  1157. getShared( builder ) {
  1158. const hash = this.getHash( builder );
  1159. const nodeFromHash = builder.getNodeFromHash( hash );
  1160. return nodeFromHash || this;
  1161. }
  1162. /**
  1163. * Returns the number of elements in the node array.
  1164. *
  1165. * @param {NodeBuilder} builder - The current node builder.
  1166. * @return {?number} The number of elements in the node array.
  1167. */
  1168. getArrayCount( /*builder*/ ) {
  1169. return null;
  1170. }
  1171. /**
  1172. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1173. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1174. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1175. *
  1176. * @param {NodeBuilder} builder - The current node builder.
  1177. * @return {?Node} The output node.
  1178. */
  1179. setup( builder ) {
  1180. const nodeProperties = builder.getNodeProperties( this );
  1181. let index = 0;
  1182. for ( const childNode of this.getChildren() ) {
  1183. nodeProperties[ 'node' + index ++ ] = childNode;
  1184. }
  1185. // return a outputNode if exists or null
  1186. return nodeProperties.outputNode || null;
  1187. }
  1188. /**
  1189. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1190. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1191. *
  1192. * @param {NodeBuilder} builder - The current node builder.
  1193. * @param {?Node} output - The target output node.
  1194. */
  1195. analyze( builder, output = null ) {
  1196. const usageCount = builder.increaseUsage( this );
  1197. if ( this.parents === true ) {
  1198. const nodeData = builder.getDataFromNode( this, 'any' );
  1199. nodeData.stages = nodeData.stages || {};
  1200. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1201. nodeData.stages[ builder.shaderStage ].push( output );
  1202. }
  1203. if ( usageCount === 1 ) {
  1204. // node flow children
  1205. const nodeProperties = builder.getNodeProperties( this );
  1206. for ( const childNode of Object.values( nodeProperties ) ) {
  1207. if ( childNode && childNode.isNode === true ) {
  1208. childNode.build( builder, this );
  1209. }
  1210. }
  1211. }
  1212. }
  1213. /**
  1214. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1215. * This state builds the output node and returns the resulting shader string.
  1216. *
  1217. * @param {NodeBuilder} builder - The current node builder.
  1218. * @param {?string} [output] - Can be used to define the output type.
  1219. * @return {?string} The generated shader string.
  1220. */
  1221. generate( builder, output ) {
  1222. const { outputNode } = builder.getNodeProperties( this );
  1223. if ( outputNode && outputNode.isNode === true ) {
  1224. return outputNode.build( builder, output );
  1225. }
  1226. }
  1227. /**
  1228. * The method can be implemented to update the node's internal state before it is used to render an object.
  1229. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1230. *
  1231. * @abstract
  1232. * @param {NodeFrame} frame - A reference to the current node frame.
  1233. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1234. */
  1235. updateBefore( /*frame*/ ) {
  1236. warn( 'Abstract function.' );
  1237. }
  1238. /**
  1239. * The method can be implemented to update the node's internal state after it was used to render an object.
  1240. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1241. *
  1242. * @abstract
  1243. * @param {NodeFrame} frame - A reference to the current node frame.
  1244. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1245. */
  1246. updateAfter( /*frame*/ ) {
  1247. warn( 'Abstract function.' );
  1248. }
  1249. /**
  1250. * The method can be implemented to update the node's internal state when it is used to render an object.
  1251. * The {@link Node#updateType} property defines how often the update is executed.
  1252. *
  1253. * @abstract
  1254. * @param {NodeFrame} frame - A reference to the current node frame.
  1255. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1256. */
  1257. update( /*frame*/ ) {
  1258. warn( 'Abstract function.' );
  1259. }
  1260. /**
  1261. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1262. * - **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.
  1263. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1264. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1265. *
  1266. * @param {NodeBuilder} builder - The current node builder.
  1267. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1268. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1269. */
  1270. build( builder, output = null ) {
  1271. const refNode = this.getShared( builder );
  1272. if ( this !== refNode ) {
  1273. return refNode.build( builder, output );
  1274. }
  1275. //
  1276. const nodeData = builder.getDataFromNode( this );
  1277. nodeData.buildStages = nodeData.buildStages || {};
  1278. nodeData.buildStages[ builder.buildStage ] = true;
  1279. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1280. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1281. // force parent build stage (setup or analyze)
  1282. const previousBuildStage = builder.getBuildStage();
  1283. builder.setBuildStage( parentBuildStage );
  1284. this.build( builder );
  1285. builder.setBuildStage( previousBuildStage );
  1286. }
  1287. //
  1288. builder.addNode( this );
  1289. builder.addChain( this );
  1290. /* Build stages expected results:
  1291. - "setup" -> Node
  1292. - "analyze" -> null
  1293. - "generate" -> String
  1294. */
  1295. let result = null;
  1296. const buildStage = builder.getBuildStage();
  1297. if ( buildStage === 'setup' ) {
  1298. this.updateReference( builder );
  1299. const properties = builder.getNodeProperties( this );
  1300. if ( properties.initialized !== true ) {
  1301. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1302. properties.initialized = true;
  1303. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1304. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1305. // !! no outputNode !!
  1306. //outputNode = builder.stack;
  1307. }*/
  1308. for ( const childNode of Object.values( properties ) ) {
  1309. if ( childNode && childNode.isNode === true ) {
  1310. if ( childNode.parents === true ) {
  1311. const childProperties = builder.getNodeProperties( childNode );
  1312. childProperties.parents = childProperties.parents || [];
  1313. childProperties.parents.push( this );
  1314. }
  1315. childNode.build( builder );
  1316. }
  1317. }
  1318. }
  1319. result = properties.outputNode;
  1320. } else if ( buildStage === 'analyze' ) {
  1321. this.analyze( builder, output );
  1322. } else if ( buildStage === 'generate' ) {
  1323. const isGenerateOnce = this.generate.length === 1;
  1324. if ( isGenerateOnce ) {
  1325. const type = this.getNodeType( builder );
  1326. const nodeData = builder.getDataFromNode( this );
  1327. result = nodeData.snippet;
  1328. if ( result === undefined ) {
  1329. if ( nodeData.generated === undefined ) {
  1330. nodeData.generated = true;
  1331. result = this.generate( builder ) || '';
  1332. nodeData.snippet = result;
  1333. } else {
  1334. warn( 'Node: Recursion detected.', this );
  1335. result = '/* Recursion detected. */';
  1336. }
  1337. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1338. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1339. }
  1340. result = builder.format( result, type, output );
  1341. } else {
  1342. result = this.generate( builder, output ) || '';
  1343. }
  1344. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1345. // if no snippet is generated, return a default value
  1346. error( `TSL: Invalid generated code, expected a "${ output }".` );
  1347. result = builder.generateConst( output );
  1348. }
  1349. }
  1350. builder.removeChain( this );
  1351. builder.addSequentialNode( this );
  1352. return result;
  1353. }
  1354. /**
  1355. * Returns the child nodes as a JSON object.
  1356. *
  1357. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1358. */
  1359. getSerializeChildren() {
  1360. return getNodeChildren( this );
  1361. }
  1362. /**
  1363. * Serializes the node to JSON.
  1364. *
  1365. * @param {Object} json - The output JSON object.
  1366. */
  1367. serialize( json ) {
  1368. const nodeChildren = this.getSerializeChildren();
  1369. const inputNodes = {};
  1370. for ( const { property, index, childNode } of nodeChildren ) {
  1371. if ( index !== undefined ) {
  1372. if ( inputNodes[ property ] === undefined ) {
  1373. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1374. }
  1375. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1376. } else {
  1377. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1378. }
  1379. }
  1380. if ( Object.keys( inputNodes ).length > 0 ) {
  1381. json.inputNodes = inputNodes;
  1382. }
  1383. }
  1384. /**
  1385. * Deserializes the node from the given JSON.
  1386. *
  1387. * @param {Object} json - The JSON object.
  1388. */
  1389. deserialize( json ) {
  1390. if ( json.inputNodes !== undefined ) {
  1391. const nodes = json.meta.nodes;
  1392. for ( const property in json.inputNodes ) {
  1393. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1394. const inputArray = [];
  1395. for ( const uuid of json.inputNodes[ property ] ) {
  1396. inputArray.push( nodes[ uuid ] );
  1397. }
  1398. this[ property ] = inputArray;
  1399. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1400. const inputObject = {};
  1401. for ( const subProperty in json.inputNodes[ property ] ) {
  1402. const uuid = json.inputNodes[ property ][ subProperty ];
  1403. inputObject[ subProperty ] = nodes[ uuid ];
  1404. }
  1405. this[ property ] = inputObject;
  1406. } else {
  1407. const uuid = json.inputNodes[ property ];
  1408. this[ property ] = nodes[ uuid ];
  1409. }
  1410. }
  1411. }
  1412. }
  1413. /**
  1414. * Serializes the node into the three.js JSON Object/Scene format.
  1415. *
  1416. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1417. * @return {Object} The serialized node.
  1418. */
  1419. toJSON( meta ) {
  1420. const { uuid, type } = this;
  1421. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1422. if ( isRoot ) {
  1423. meta = {
  1424. textures: {},
  1425. images: {},
  1426. nodes: {}
  1427. };
  1428. }
  1429. // serialize
  1430. let data = meta.nodes[ uuid ];
  1431. if ( data === undefined ) {
  1432. data = {
  1433. uuid,
  1434. type,
  1435. meta,
  1436. metadata: {
  1437. version: 4.7,
  1438. type: 'Node',
  1439. generator: 'Node.toJSON'
  1440. }
  1441. };
  1442. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1443. this.serialize( data );
  1444. delete data.meta;
  1445. }
  1446. // TODO: Copied from Object3D.toJSON
  1447. function extractFromCache( cache ) {
  1448. const values = [];
  1449. for ( const key in cache ) {
  1450. const data = cache[ key ];
  1451. delete data.metadata;
  1452. values.push( data );
  1453. }
  1454. return values;
  1455. }
  1456. if ( isRoot ) {
  1457. const textures = extractFromCache( meta.textures );
  1458. const images = extractFromCache( meta.images );
  1459. const nodes = extractFromCache( meta.nodes );
  1460. if ( textures.length > 0 ) data.textures = textures;
  1461. if ( images.length > 0 ) data.images = images;
  1462. if ( nodes.length > 0 ) data.nodes = nodes;
  1463. }
  1464. return data;
  1465. }
  1466. }
  1467. /**
  1468. * Base class for representing element access on an array-like
  1469. * node data structures.
  1470. *
  1471. * @augments Node
  1472. */
  1473. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1474. static get type() {
  1475. return 'ArrayElementNode';
  1476. }
  1477. /**
  1478. * Constructs an array element node.
  1479. *
  1480. * @param {Node} node - The array-like node.
  1481. * @param {Node} indexNode - The index node that defines the element access.
  1482. */
  1483. constructor( node, indexNode ) {
  1484. super();
  1485. /**
  1486. * The array-like node.
  1487. *
  1488. * @type {Node}
  1489. */
  1490. this.node = node;
  1491. /**
  1492. * The index node that defines the element access.
  1493. *
  1494. * @type {Node}
  1495. */
  1496. this.indexNode = indexNode;
  1497. /**
  1498. * This flag can be used for type testing.
  1499. *
  1500. * @type {boolean}
  1501. * @readonly
  1502. * @default true
  1503. */
  1504. this.isArrayElementNode = true;
  1505. }
  1506. /**
  1507. * This method is overwritten since the node type is inferred from the array-like node.
  1508. *
  1509. * @param {NodeBuilder} builder - The current node builder.
  1510. * @return {string} The node type.
  1511. */
  1512. getNodeType( builder ) {
  1513. return this.node.getElementType( builder );
  1514. }
  1515. generate( builder ) {
  1516. const indexType = this.indexNode.getNodeType( builder );
  1517. const nodeSnippet = this.node.build( builder );
  1518. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1519. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1520. }
  1521. }
  1522. /**
  1523. * This module is part of the TSL core and usually not used in app level code.
  1524. * It represents a convert operation during the shader generation process
  1525. * meaning it converts the data type of a node to a target data type.
  1526. *
  1527. * @augments Node
  1528. */
  1529. class ConvertNode extends Node {
  1530. static get type() {
  1531. return 'ConvertNode';
  1532. }
  1533. /**
  1534. * Constructs a new convert node.
  1535. *
  1536. * @param {Node} node - The node which type should be converted.
  1537. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1538. */
  1539. constructor( node, convertTo ) {
  1540. super();
  1541. /**
  1542. * The node which type should be converted.
  1543. *
  1544. * @type {Node}
  1545. */
  1546. this.node = node;
  1547. /**
  1548. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1549. *
  1550. * @type {string}
  1551. */
  1552. this.convertTo = convertTo;
  1553. }
  1554. /**
  1555. * This method is overwritten since the implementation tries to infer the best
  1556. * matching type from the {@link ConvertNode#convertTo} property.
  1557. *
  1558. * @param {NodeBuilder} builder - The current node builder.
  1559. * @return {string} The node type.
  1560. */
  1561. getNodeType( builder ) {
  1562. const requestType = this.node.getNodeType( builder );
  1563. let convertTo = null;
  1564. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1565. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1566. convertTo = overloadingType;
  1567. }
  1568. }
  1569. return convertTo;
  1570. }
  1571. serialize( data ) {
  1572. super.serialize( data );
  1573. data.convertTo = this.convertTo;
  1574. }
  1575. deserialize( data ) {
  1576. super.deserialize( data );
  1577. this.convertTo = data.convertTo;
  1578. }
  1579. generate( builder, output ) {
  1580. const node = this.node;
  1581. const type = this.getNodeType( builder );
  1582. const snippet = node.build( builder, type );
  1583. return builder.format( snippet, type, output );
  1584. }
  1585. }
  1586. /**
  1587. * This module uses cache management to create temporary variables
  1588. * if the node is used more than once to prevent duplicate calculations.
  1589. *
  1590. * The class acts as a base class for many other nodes types.
  1591. *
  1592. * @augments Node
  1593. */
  1594. class TempNode extends Node {
  1595. static get type() {
  1596. return 'TempNode';
  1597. }
  1598. /**
  1599. * Constructs a temp node.
  1600. *
  1601. * @param {?string} nodeType - The node type.
  1602. */
  1603. constructor( nodeType = null ) {
  1604. super( nodeType );
  1605. /**
  1606. * This flag can be used for type testing.
  1607. *
  1608. * @type {boolean}
  1609. * @readonly
  1610. * @default true
  1611. */
  1612. this.isTempNode = true;
  1613. }
  1614. /**
  1615. * Whether this node is used more than once in context of other nodes.
  1616. *
  1617. * @param {NodeBuilder} builder - The node builder.
  1618. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1619. */
  1620. hasDependencies( builder ) {
  1621. return builder.getDataFromNode( this ).usageCount > 1;
  1622. }
  1623. build( builder, output ) {
  1624. const buildStage = builder.getBuildStage();
  1625. if ( buildStage === 'generate' ) {
  1626. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1627. const nodeData = builder.getDataFromNode( this );
  1628. if ( nodeData.propertyName !== undefined ) {
  1629. return builder.format( nodeData.propertyName, type, output );
  1630. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1631. const snippet = super.build( builder, type );
  1632. const nodeVar = builder.getVarFromNode( this, null, type );
  1633. const propertyName = builder.getPropertyName( nodeVar );
  1634. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1635. nodeData.snippet = snippet;
  1636. nodeData.propertyName = propertyName;
  1637. return builder.format( nodeData.propertyName, type, output );
  1638. }
  1639. }
  1640. return super.build( builder, output );
  1641. }
  1642. }
  1643. /**
  1644. * This module is part of the TSL core and usually not used in app level code.
  1645. * It represents a join operation during the shader generation process.
  1646. * For example in can compose/join two single floats into a `vec2` type.
  1647. *
  1648. * @augments TempNode
  1649. */
  1650. class JoinNode extends TempNode {
  1651. static get type() {
  1652. return 'JoinNode';
  1653. }
  1654. /**
  1655. * Constructs a new join node.
  1656. *
  1657. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1658. * @param {?string} [nodeType=null] - The node type.
  1659. */
  1660. constructor( nodes = [], nodeType = null ) {
  1661. super( nodeType );
  1662. /**
  1663. * An array of nodes that should be joined.
  1664. *
  1665. * @type {Array<Node>}
  1666. */
  1667. this.nodes = nodes;
  1668. }
  1669. /**
  1670. * This method is overwritten since the node type must be inferred from the
  1671. * joined data length if not explicitly defined.
  1672. *
  1673. * @param {NodeBuilder} builder - The current node builder.
  1674. * @return {string} The node type.
  1675. */
  1676. getNodeType( builder ) {
  1677. if ( this.nodeType !== null ) {
  1678. return builder.getVectorType( this.nodeType );
  1679. }
  1680. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1681. }
  1682. generate( builder, output ) {
  1683. const type = this.getNodeType( builder );
  1684. const maxLength = builder.getTypeLength( type );
  1685. const nodes = this.nodes;
  1686. const primitiveType = builder.getComponentType( type );
  1687. const snippetValues = [];
  1688. let length = 0;
  1689. for ( const input of nodes ) {
  1690. if ( length >= maxLength ) {
  1691. error( `TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1692. break;
  1693. }
  1694. let inputType = input.getNodeType( builder );
  1695. let inputTypeLength = builder.getTypeLength( inputType );
  1696. let inputSnippet;
  1697. if ( length + inputTypeLength > maxLength ) {
  1698. error( `TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1699. inputTypeLength = maxLength - length;
  1700. inputType = builder.getTypeFromLength( inputTypeLength );
  1701. }
  1702. length += inputTypeLength;
  1703. inputSnippet = input.build( builder, inputType );
  1704. const inputPrimitiveType = builder.getComponentType( inputType );
  1705. if ( inputPrimitiveType !== primitiveType ) {
  1706. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1707. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1708. }
  1709. snippetValues.push( inputSnippet );
  1710. }
  1711. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1712. return builder.format( snippet, type, output );
  1713. }
  1714. }
  1715. const _stringVectorComponents = vectorComponents.join( '' );
  1716. /**
  1717. * This module is part of the TSL core and usually not used in app level code.
  1718. * `SplitNode` represents a property access operation which means it is
  1719. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1720. * For example:
  1721. * ```js
  1722. * const redValue = color.r;
  1723. * ```
  1724. *
  1725. * @augments Node
  1726. */
  1727. class SplitNode extends Node {
  1728. static get type() {
  1729. return 'SplitNode';
  1730. }
  1731. /**
  1732. * Constructs a new split node.
  1733. *
  1734. * @param {Node} node - The node that should be accessed.
  1735. * @param {string} [components='x'] - The components that should be accessed.
  1736. */
  1737. constructor( node, components = 'x' ) {
  1738. super();
  1739. /**
  1740. * The node that should be accessed.
  1741. *
  1742. * @type {Node}
  1743. */
  1744. this.node = node;
  1745. /**
  1746. * The components that should be accessed.
  1747. *
  1748. * @type {string}
  1749. */
  1750. this.components = components;
  1751. /**
  1752. * This flag can be used for type testing.
  1753. *
  1754. * @type {boolean}
  1755. * @readonly
  1756. * @default true
  1757. */
  1758. this.isSplitNode = true;
  1759. }
  1760. /**
  1761. * Returns the vector length which is computed based on the requested components.
  1762. *
  1763. * @return {number} The vector length.
  1764. */
  1765. getVectorLength() {
  1766. let vectorLength = this.components.length;
  1767. for ( const c of this.components ) {
  1768. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1769. }
  1770. return vectorLength;
  1771. }
  1772. /**
  1773. * Returns the component type of the node's type.
  1774. *
  1775. * @param {NodeBuilder} builder - The current node builder.
  1776. * @return {string} The component type.
  1777. */
  1778. getComponentType( builder ) {
  1779. return builder.getComponentType( this.node.getNodeType( builder ) );
  1780. }
  1781. /**
  1782. * This method is overwritten since the node type is inferred from requested components.
  1783. *
  1784. * @param {NodeBuilder} builder - The current node builder.
  1785. * @return {string} The node type.
  1786. */
  1787. getNodeType( builder ) {
  1788. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1789. }
  1790. /**
  1791. * Returns the scope of the node.
  1792. *
  1793. * @return {Node} The scope of the node.
  1794. */
  1795. getScope() {
  1796. return this.node.getScope();
  1797. }
  1798. generate( builder, output ) {
  1799. const node = this.node;
  1800. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1801. let snippet = null;
  1802. if ( nodeTypeLength > 1 ) {
  1803. let type = null;
  1804. const componentsLength = this.getVectorLength();
  1805. if ( componentsLength >= nodeTypeLength ) {
  1806. // needed expand the input node
  1807. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1808. }
  1809. const nodeSnippet = node.build( builder, type );
  1810. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1811. // unnecessary swizzle
  1812. snippet = builder.format( nodeSnippet, type, output );
  1813. } else {
  1814. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1815. }
  1816. } else {
  1817. // ignore .components if .node returns float/integer
  1818. snippet = node.build( builder, output );
  1819. }
  1820. return snippet;
  1821. }
  1822. serialize( data ) {
  1823. super.serialize( data );
  1824. data.components = this.components;
  1825. }
  1826. deserialize( data ) {
  1827. super.deserialize( data );
  1828. this.components = data.components;
  1829. }
  1830. }
  1831. /**
  1832. * This module is part of the TSL core and usually not used in app level code.
  1833. * `SetNode` represents a set operation which means it is used to implement any
  1834. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1835. * For example:
  1836. * ```js
  1837. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1838. * ```
  1839. *
  1840. * @augments TempNode
  1841. */
  1842. class SetNode extends TempNode {
  1843. static get type() {
  1844. return 'SetNode';
  1845. }
  1846. /**
  1847. * Constructs a new set node.
  1848. *
  1849. * @param {Node} sourceNode - The node that should be updated.
  1850. * @param {string} components - The components that should be updated.
  1851. * @param {Node} targetNode - The value node.
  1852. */
  1853. constructor( sourceNode, components, targetNode ) {
  1854. super();
  1855. /**
  1856. * The node that should be updated.
  1857. *
  1858. * @type {Node}
  1859. */
  1860. this.sourceNode = sourceNode;
  1861. /**
  1862. * The components that should be updated.
  1863. *
  1864. * @type {string}
  1865. */
  1866. this.components = components;
  1867. /**
  1868. * The value node.
  1869. *
  1870. * @type {Node}
  1871. */
  1872. this.targetNode = targetNode;
  1873. }
  1874. /**
  1875. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1876. *
  1877. * @param {NodeBuilder} builder - The current node builder.
  1878. * @return {string} The node type.
  1879. */
  1880. getNodeType( builder ) {
  1881. return this.sourceNode.getNodeType( builder );
  1882. }
  1883. generate( builder ) {
  1884. const { sourceNode, components, targetNode } = this;
  1885. const sourceType = this.getNodeType( builder );
  1886. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1887. const targetType = builder.getTypeFromLength( components.length, componentType );
  1888. const targetSnippet = targetNode.build( builder, targetType );
  1889. const sourceSnippet = sourceNode.build( builder, sourceType );
  1890. const length = builder.getTypeLength( sourceType );
  1891. const snippetValues = [];
  1892. for ( let i = 0; i < length; i ++ ) {
  1893. const component = vectorComponents[ i ];
  1894. if ( component === components[ 0 ] ) {
  1895. snippetValues.push( targetSnippet );
  1896. i += components.length - 1;
  1897. } else {
  1898. snippetValues.push( sourceSnippet + '.' + component );
  1899. }
  1900. }
  1901. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1902. }
  1903. }
  1904. /**
  1905. * This module is part of the TSL core and usually not used in app level code.
  1906. * It represents a flip operation during the shader generation process
  1907. * meaning it flips normalized values with the following formula:
  1908. * ```
  1909. * x = 1 - x;
  1910. * ```
  1911. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1912. * `flipSTPQ()` method invocations on node objects. For example:
  1913. * ```js
  1914. * uvNode = uvNode.flipY();
  1915. * ```
  1916. *
  1917. * @augments TempNode
  1918. */
  1919. class FlipNode extends TempNode {
  1920. static get type() {
  1921. return 'FlipNode';
  1922. }
  1923. /**
  1924. * Constructs a new flip node.
  1925. *
  1926. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1927. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1928. */
  1929. constructor( sourceNode, components ) {
  1930. super();
  1931. /**
  1932. * The node which component(s) should be flipped.
  1933. *
  1934. * @type {Node}
  1935. */
  1936. this.sourceNode = sourceNode;
  1937. /**
  1938. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1939. *
  1940. * @type {string}
  1941. */
  1942. this.components = components;
  1943. }
  1944. /**
  1945. * This method is overwritten since the node type is inferred from the source node.
  1946. *
  1947. * @param {NodeBuilder} builder - The current node builder.
  1948. * @return {string} The node type.
  1949. */
  1950. getNodeType( builder ) {
  1951. return this.sourceNode.getNodeType( builder );
  1952. }
  1953. generate( builder ) {
  1954. const { components, sourceNode } = this;
  1955. const sourceType = this.getNodeType( builder );
  1956. const sourceSnippet = sourceNode.build( builder );
  1957. const sourceCache = builder.getVarFromNode( this );
  1958. const sourceProperty = builder.getPropertyName( sourceCache );
  1959. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1960. const length = builder.getTypeLength( sourceType );
  1961. const snippetValues = [];
  1962. let componentIndex = 0;
  1963. for ( let i = 0; i < length; i ++ ) {
  1964. const component = vectorComponents[ i ];
  1965. if ( component === components[ componentIndex ] ) {
  1966. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1967. componentIndex ++;
  1968. } else {
  1969. snippetValues.push( sourceProperty + '.' + component );
  1970. }
  1971. }
  1972. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1973. }
  1974. }
  1975. /**
  1976. * Base class for representing data input nodes.
  1977. *
  1978. * @augments Node
  1979. */
  1980. class InputNode extends Node {
  1981. static get type() {
  1982. return 'InputNode';
  1983. }
  1984. /**
  1985. * Constructs a new input node.
  1986. *
  1987. * @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).
  1988. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1989. */
  1990. constructor( value, nodeType = null ) {
  1991. super( nodeType );
  1992. /**
  1993. * This flag can be used for type testing.
  1994. *
  1995. * @type {boolean}
  1996. * @readonly
  1997. * @default true
  1998. */
  1999. this.isInputNode = true;
  2000. /**
  2001. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2002. *
  2003. * @type {any}
  2004. */
  2005. this.value = value;
  2006. /**
  2007. * The precision of the value in the shader.
  2008. *
  2009. * @type {?('low'|'medium'|'high')}
  2010. * @default null
  2011. */
  2012. this.precision = null;
  2013. }
  2014. getNodeType( /*builder*/ ) {
  2015. if ( this.nodeType === null ) {
  2016. return getValueType( this.value );
  2017. }
  2018. return this.nodeType;
  2019. }
  2020. /**
  2021. * Returns the input type of the node which is by default the node type. Derived modules
  2022. * might overwrite this method and use a fixed type or compute one analytically.
  2023. *
  2024. * A typical example for different input and node types are textures. The input type of a
  2025. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2026. *
  2027. * @param {NodeBuilder} builder - The current node builder.
  2028. * @return {string} The input type.
  2029. */
  2030. getInputType( builder ) {
  2031. return this.getNodeType( builder );
  2032. }
  2033. /**
  2034. * Sets the precision to the given value. The method can be
  2035. * overwritten in derived classes if the final precision must be computed
  2036. * analytically.
  2037. *
  2038. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2039. * @return {InputNode} A reference to this node.
  2040. */
  2041. setPrecision( precision ) {
  2042. this.precision = precision;
  2043. return this;
  2044. }
  2045. serialize( data ) {
  2046. super.serialize( data );
  2047. data.value = this.value;
  2048. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2049. data.valueType = getValueType( this.value );
  2050. data.nodeType = this.nodeType;
  2051. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2052. data.precision = this.precision;
  2053. }
  2054. deserialize( data ) {
  2055. super.deserialize( data );
  2056. this.nodeType = data.nodeType;
  2057. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2058. this.precision = data.precision || null;
  2059. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2060. }
  2061. generate( /*builder, output*/ ) {
  2062. warn( 'Abstract function.' );
  2063. }
  2064. }
  2065. const _regNum = /float|u?int/;
  2066. /**
  2067. * Class for representing a constant value in the shader.
  2068. *
  2069. * @augments InputNode
  2070. */
  2071. class ConstNode extends InputNode {
  2072. static get type() {
  2073. return 'ConstNode';
  2074. }
  2075. /**
  2076. * Constructs a new input node.
  2077. *
  2078. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2079. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2080. */
  2081. constructor( value, nodeType = null ) {
  2082. super( value, nodeType );
  2083. /**
  2084. * This flag can be used for type testing.
  2085. *
  2086. * @type {boolean}
  2087. * @readonly
  2088. * @default true
  2089. */
  2090. this.isConstNode = true;
  2091. }
  2092. /**
  2093. * Generates the shader string of the value with the current node builder.
  2094. *
  2095. * @param {NodeBuilder} builder - The current node builder.
  2096. * @return {string} The generated value as a shader string.
  2097. */
  2098. generateConst( builder ) {
  2099. return builder.generateConst( this.getNodeType( builder ), this.value );
  2100. }
  2101. generate( builder, output ) {
  2102. const type = this.getNodeType( builder );
  2103. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2104. return builder.generateConst( output, this.value );
  2105. }
  2106. return builder.format( this.generateConst( builder ), type, output );
  2107. }
  2108. }
  2109. /**
  2110. * Base class for representing member access on an object-like
  2111. * node data structures.
  2112. *
  2113. * @augments Node
  2114. */
  2115. class MemberNode extends Node {
  2116. static get type() {
  2117. return 'MemberNode';
  2118. }
  2119. /**
  2120. * Constructs a member node.
  2121. *
  2122. * @param {Node} structNode - The struct node.
  2123. * @param {string} property - The property name.
  2124. */
  2125. constructor( structNode, property ) {
  2126. super();
  2127. /**
  2128. * The struct node.
  2129. *
  2130. * @type {Node}
  2131. */
  2132. this.structNode = structNode;
  2133. /**
  2134. * The property name.
  2135. *
  2136. * @type {Node}
  2137. */
  2138. this.property = property;
  2139. /**
  2140. * This flag can be used for type testing.
  2141. *
  2142. * @type {boolean}
  2143. * @readonly
  2144. * @default true
  2145. */
  2146. this.isMemberNode = true;
  2147. }
  2148. hasMember( builder ) {
  2149. if ( this.structNode.isMemberNode ) {
  2150. if ( this.structNode.hasMember( builder ) === false ) {
  2151. return false;
  2152. }
  2153. }
  2154. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2155. }
  2156. getNodeType( builder ) {
  2157. if ( this.hasMember( builder ) === false ) {
  2158. // default type if member does not exist
  2159. return 'float';
  2160. }
  2161. return this.structNode.getMemberType( builder, this.property );
  2162. }
  2163. getMemberType( builder, name ) {
  2164. if ( this.hasMember( builder ) === false ) {
  2165. // default type if member does not exist
  2166. return 'float';
  2167. }
  2168. const type = this.getNodeType( builder );
  2169. const struct = builder.getStructTypeNode( type );
  2170. return struct.getMemberType( builder, name );
  2171. }
  2172. generate( builder ) {
  2173. if ( this.hasMember( builder ) === false ) {
  2174. warn( `TSL: Member "${ this.property }" does not exist in struct.` );
  2175. const type = this.getNodeType( builder );
  2176. return builder.generateConst( type );
  2177. }
  2178. const propertyName = this.structNode.build( builder );
  2179. return propertyName + '.' + this.property;
  2180. }
  2181. }
  2182. let currentStack = null;
  2183. const NodeElements = new Map();
  2184. // Extend Node Class for TSL using prototype
  2185. function addMethodChaining( name, nodeElement ) {
  2186. if ( NodeElements.has( name ) ) {
  2187. warn( `TSL: Redefinition of method chaining '${ name }'.` );
  2188. return;
  2189. }
  2190. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2191. NodeElements.set( name, nodeElement );
  2192. if ( name !== 'assign' ) {
  2193. // Changing Node prototype to add method chaining
  2194. Node.prototype[ name ] = function ( ...params ) {
  2195. //if ( name === 'toVarIntent' ) return this;
  2196. return this.isStackNode ? this.add( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2197. };
  2198. // Adding assign method chaining
  2199. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2200. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2201. };
  2202. }
  2203. }
  2204. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2205. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2206. Node.prototype.assign = function ( ...params ) {
  2207. if ( this.isStackNode !== true ) {
  2208. if ( currentStack !== null ) {
  2209. currentStack.assign( this, ...params );
  2210. } else {
  2211. error( 'TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2212. }
  2213. return this;
  2214. } else {
  2215. const nodeElement = NodeElements.get( 'assign' );
  2216. return this.add( nodeElement( ...params ) );
  2217. }
  2218. };
  2219. Node.prototype.toVarIntent = function () {
  2220. return this;
  2221. };
  2222. Node.prototype.get = function ( value ) {
  2223. return new MemberNode( this, value );
  2224. };
  2225. // Cache prototype for TSL
  2226. const proto = {};
  2227. // Set swizzle properties for xyzw, rgba, and stpq.
  2228. function setProtoSwizzle( property, altA, altB ) {
  2229. // swizzle properties
  2230. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2231. get() {
  2232. this._cache = this._cache || {};
  2233. //
  2234. let split = this._cache[ property ];
  2235. if ( split === undefined ) {
  2236. split = new SplitNode( this, property );
  2237. this._cache[ property ] = split;
  2238. }
  2239. return split;
  2240. },
  2241. set( value ) {
  2242. this[ property ].assign( nodeObject( value ) );
  2243. }
  2244. };
  2245. // set properties ( swizzle ) and sort to xyzw sequence
  2246. const propUpper = property.toUpperCase();
  2247. const altAUpper = altA.toUpperCase();
  2248. const altBUpper = altB.toUpperCase();
  2249. // Set methods for swizzle properties
  2250. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2251. const swizzle = parseSwizzleAndSort( property );
  2252. return new SetNode( this, swizzle, nodeObject( value ) );
  2253. };
  2254. // Set methods for flip properties
  2255. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2256. const swizzle = parseSwizzleAndSort( property );
  2257. return new FlipNode( this, swizzle );
  2258. };
  2259. }
  2260. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2261. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2262. const swizzleC = [ 's', 't', 'p', 'q' ];
  2263. for ( let a = 0; a < 4; a ++ ) {
  2264. let prop = swizzleA[ a ];
  2265. let altA = swizzleB[ a ];
  2266. let altB = swizzleC[ a ];
  2267. setProtoSwizzle( prop, altA, altB );
  2268. for ( let b = 0; b < 4; b ++ ) {
  2269. prop = swizzleA[ a ] + swizzleA[ b ];
  2270. altA = swizzleB[ a ] + swizzleB[ b ];
  2271. altB = swizzleC[ a ] + swizzleC[ b ];
  2272. setProtoSwizzle( prop, altA, altB );
  2273. for ( let c = 0; c < 4; c ++ ) {
  2274. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2275. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2276. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2277. setProtoSwizzle( prop, altA, altB );
  2278. for ( let d = 0; d < 4; d ++ ) {
  2279. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2280. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2281. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2282. setProtoSwizzle( prop, altA, altB );
  2283. }
  2284. }
  2285. }
  2286. }
  2287. // Set/get static properties for array elements (0-31).
  2288. for ( let i = 0; i < 32; i ++ ) {
  2289. proto[ i ] = {
  2290. get() {
  2291. this._cache = this._cache || {};
  2292. //
  2293. let element = this._cache[ i ];
  2294. if ( element === undefined ) {
  2295. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2296. this._cache[ i ] = element;
  2297. }
  2298. return element;
  2299. },
  2300. set( value ) {
  2301. this[ i ].assign( nodeObject( value ) );
  2302. }
  2303. };
  2304. }
  2305. /*
  2306. // Set properties for width, height, and depth.
  2307. function setProtoProperty( property, target ) {
  2308. proto[ property ] = {
  2309. get() {
  2310. this._cache = this._cache || {};
  2311. //
  2312. let split = this._cache[ target ];
  2313. if ( split === undefined ) {
  2314. split = new SplitNode( this, target );
  2315. this._cache[ target ] = split;
  2316. }
  2317. return split;
  2318. },
  2319. set( value ) {
  2320. this[ target ].assign( nodeObject( value ) );
  2321. }
  2322. };
  2323. }
  2324. setProtoProperty( 'width', 'x' );
  2325. setProtoProperty( 'height', 'y' );
  2326. setProtoProperty( 'depth', 'z' );
  2327. */
  2328. Object.defineProperties( Node.prototype, proto );
  2329. // --- FINISH ---
  2330. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2331. const ShaderNodeObject = function ( obj, altType = null ) {
  2332. const type = getValueType( obj );
  2333. if ( type === 'node' ) {
  2334. return obj;
  2335. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2336. return nodeObject( getConstNode( obj, altType ) );
  2337. } else if ( type === 'shader' ) {
  2338. return obj.isFn ? obj : Fn( obj );
  2339. }
  2340. return obj;
  2341. };
  2342. const ShaderNodeObjects = function ( objects, altType = null ) {
  2343. for ( const name in objects ) {
  2344. objects[ name ] = nodeObject( objects[ name ], altType );
  2345. }
  2346. return objects;
  2347. };
  2348. const ShaderNodeArray = function ( array, altType = null ) {
  2349. const len = array.length;
  2350. for ( let i = 0; i < len; i ++ ) {
  2351. array[ i ] = nodeObject( array[ i ], altType );
  2352. }
  2353. return array;
  2354. };
  2355. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2356. function assignNode( node ) {
  2357. if ( settings !== null ) {
  2358. node = nodeObject( Object.assign( node, settings ) );
  2359. if ( settings.intent === true ) {
  2360. node = node.toVarIntent();
  2361. }
  2362. } else {
  2363. node = nodeObject( node );
  2364. }
  2365. return node;
  2366. }
  2367. let fn, name = scope, minParams, maxParams;
  2368. function verifyParamsLimit( params ) {
  2369. let tslName;
  2370. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2371. else tslName = NodeClass.type;
  2372. if ( minParams !== undefined && params.length < minParams ) {
  2373. error( `TSL: "${ tslName }" parameter length is less than minimum required.` );
  2374. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2375. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2376. error( `TSL: "${ tslName }" parameter length exceeds limit.` );
  2377. return params.slice( 0, maxParams );
  2378. }
  2379. return params;
  2380. }
  2381. if ( scope === null ) {
  2382. fn = ( ...params ) => {
  2383. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2384. };
  2385. } else if ( factor !== null ) {
  2386. factor = nodeObject( factor );
  2387. fn = ( ...params ) => {
  2388. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2389. };
  2390. } else {
  2391. fn = ( ...params ) => {
  2392. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2393. };
  2394. }
  2395. fn.setParameterLength = ( ...params ) => {
  2396. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2397. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2398. return fn;
  2399. };
  2400. fn.setName = ( value ) => {
  2401. name = value;
  2402. return fn;
  2403. };
  2404. return fn;
  2405. };
  2406. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2407. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2408. };
  2409. class ShaderCallNodeInternal extends Node {
  2410. constructor( shaderNode, rawInputs ) {
  2411. super();
  2412. this.shaderNode = shaderNode;
  2413. this.rawInputs = rawInputs;
  2414. this.isShaderCallNodeInternal = true;
  2415. }
  2416. getNodeType( builder ) {
  2417. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2418. }
  2419. getMemberType( builder, name ) {
  2420. return this.getOutputNode( builder ).getMemberType( builder, name );
  2421. }
  2422. call( builder ) {
  2423. const { shaderNode, rawInputs } = this;
  2424. const properties = builder.getNodeProperties( shaderNode );
  2425. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2426. const subBuildProperty = subBuild || 'default';
  2427. if ( properties[ subBuildProperty ] ) {
  2428. return properties[ subBuildProperty ];
  2429. }
  2430. //
  2431. const previousSubBuildFn = builder.subBuildFn;
  2432. builder.subBuildFn = subBuild;
  2433. let result = null;
  2434. if ( shaderNode.layout ) {
  2435. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2436. if ( functionNodesCacheMap === undefined ) {
  2437. functionNodesCacheMap = new WeakMap();
  2438. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2439. }
  2440. let functionNode = functionNodesCacheMap.get( shaderNode );
  2441. if ( functionNode === undefined ) {
  2442. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2443. functionNodesCacheMap.set( shaderNode, functionNode );
  2444. }
  2445. builder.addInclude( functionNode );
  2446. //
  2447. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2448. result = nodeObject( functionNode.call( inputs ) );
  2449. } else {
  2450. const secureNodeBuilder = new Proxy( builder, {
  2451. get: ( target, property, receiver ) => {
  2452. let value;
  2453. if ( Symbol.iterator === property ) {
  2454. value = function* () {
  2455. yield undefined;
  2456. };
  2457. } else {
  2458. value = Reflect.get( target, property, receiver );
  2459. }
  2460. return value;
  2461. }
  2462. } );
  2463. //
  2464. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2465. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2466. const jsFunc = shaderNode.jsFunc;
  2467. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2468. result = nodeObject( outputNode );
  2469. }
  2470. builder.subBuildFn = previousSubBuildFn;
  2471. if ( shaderNode.once ) {
  2472. properties[ subBuildProperty ] = result;
  2473. }
  2474. return result;
  2475. }
  2476. setupOutput( builder ) {
  2477. builder.addStack();
  2478. builder.stack.outputNode = this.call( builder );
  2479. return builder.removeStack();
  2480. }
  2481. getOutputNode( builder ) {
  2482. const properties = builder.getNodeProperties( this );
  2483. const subBuildOutput = builder.getSubBuildOutput( this );
  2484. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2485. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2486. return properties[ subBuildOutput ];
  2487. }
  2488. build( builder, output = null ) {
  2489. let result = null;
  2490. const buildStage = builder.getBuildStage();
  2491. const properties = builder.getNodeProperties( this );
  2492. const subBuildOutput = builder.getSubBuildOutput( this );
  2493. const outputNode = this.getOutputNode( builder );
  2494. if ( buildStage === 'setup' ) {
  2495. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2496. if ( properties[ subBuildInitialized ] !== true ) {
  2497. properties[ subBuildInitialized ] = true;
  2498. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2499. properties[ subBuildOutput ].build( builder );
  2500. // If the shaderNode has subBuilds, add them to the chaining nodes
  2501. // so they can be built later in the build process.
  2502. if ( this.shaderNode.subBuilds ) {
  2503. for ( const node of builder.chaining ) {
  2504. const nodeData = builder.getDataFromNode( node, 'any' );
  2505. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2506. for ( const subBuild of this.shaderNode.subBuilds ) {
  2507. nodeData.subBuilds.add( subBuild );
  2508. }
  2509. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2510. }
  2511. }
  2512. }
  2513. result = properties[ subBuildOutput ];
  2514. } else if ( buildStage === 'analyze' ) {
  2515. outputNode.build( builder, output );
  2516. } else if ( buildStage === 'generate' ) {
  2517. result = outputNode.build( builder, output ) || '';
  2518. }
  2519. return result;
  2520. }
  2521. }
  2522. function getLayoutParameters( params ) {
  2523. let output;
  2524. nodeObjects( params );
  2525. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2526. if ( isArrayAsParameter ) {
  2527. output = [ ...params ];
  2528. } else {
  2529. output = params[ 0 ];
  2530. }
  2531. return output;
  2532. }
  2533. function getProxyParameters( params ) {
  2534. let index = 0;
  2535. nodeObjects( params );
  2536. return new Proxy( params, {
  2537. get: ( target, property, receiver ) => {
  2538. let value;
  2539. if ( property === 'length' ) {
  2540. value = params.length;
  2541. return value;
  2542. }
  2543. if ( Symbol.iterator === property ) {
  2544. value = function* () {
  2545. for ( const inputNode of params ) {
  2546. yield nodeObject( inputNode );
  2547. }
  2548. };
  2549. } else {
  2550. if ( params.length > 0 ) {
  2551. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2552. const objectTarget = params[ 0 ];
  2553. if ( objectTarget[ property ] === undefined ) {
  2554. value = objectTarget[ index ++ ];
  2555. } else {
  2556. value = Reflect.get( objectTarget, property, receiver );
  2557. }
  2558. } else if ( params[ 0 ] instanceof Node ) {
  2559. if ( params[ property ] === undefined ) {
  2560. value = params[ index ++ ];
  2561. } else {
  2562. value = Reflect.get( params, property, receiver );
  2563. }
  2564. }
  2565. } else {
  2566. value = Reflect.get( target, property, receiver );
  2567. }
  2568. value = nodeObject( value );
  2569. }
  2570. return value;
  2571. }
  2572. } );
  2573. }
  2574. class ShaderNodeInternal extends Node {
  2575. constructor( jsFunc, nodeType ) {
  2576. super( nodeType );
  2577. this.jsFunc = jsFunc;
  2578. this.layout = null;
  2579. this.global = true;
  2580. this.once = false;
  2581. }
  2582. setLayout( layout ) {
  2583. this.layout = layout;
  2584. return this;
  2585. }
  2586. call( rawInputs = null ) {
  2587. return nodeObject( new ShaderCallNodeInternal( this, rawInputs ) );
  2588. }
  2589. setup() {
  2590. return this.call();
  2591. }
  2592. }
  2593. const bools = [ false, true ];
  2594. const uints = [ 0, 1, 2, 3 ];
  2595. const ints = [ -1, -2 ];
  2596. 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 ];
  2597. const boolsCacheMap = new Map();
  2598. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2599. const uintsCacheMap = new Map();
  2600. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2601. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2602. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2603. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2604. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2605. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2606. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2607. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2608. const getConstNode = ( value, type ) => {
  2609. if ( constNodesCacheMap.has( value ) ) {
  2610. return constNodesCacheMap.get( value );
  2611. } else if ( value.isNode === true ) {
  2612. return value;
  2613. } else {
  2614. return new ConstNode( value, type );
  2615. }
  2616. };
  2617. const ConvertType = function ( type, cacheMap = null ) {
  2618. return ( ...params ) => {
  2619. for ( const param of params ) {
  2620. if ( param === undefined ) {
  2621. error( `TSL: Invalid parameter for the type "${ type }".` );
  2622. return nodeObject( new ConstNode( 0, type ) );
  2623. }
  2624. }
  2625. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2626. const paramType = typeof param;
  2627. return paramType !== 'object' && paramType !== 'function';
  2628. } ) ) ) {
  2629. params = [ getValueFromType( type, ...params ) ];
  2630. }
  2631. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2632. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2633. }
  2634. if ( params.length === 1 ) {
  2635. const node = getConstNode( params[ 0 ], type );
  2636. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2637. return nodeObjectIntent( new ConvertNode( node, type ) );
  2638. }
  2639. const nodes = params.map( param => getConstNode( param ) );
  2640. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2641. };
  2642. };
  2643. // exports
  2644. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2645. // utils
  2646. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2647. // shader node base
  2648. function ShaderNode( jsFunc, nodeType ) {
  2649. return new ShaderNodeInternal( jsFunc, nodeType );
  2650. }
  2651. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2652. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2653. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2654. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2655. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2656. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2657. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2658. let fnId = 0;
  2659. class FnNode extends Node {
  2660. constructor( jsFunc, layout = null ) {
  2661. super();
  2662. let nodeType = null;
  2663. if ( layout !== null ) {
  2664. if ( typeof layout === 'object' ) {
  2665. nodeType = layout.return;
  2666. } else {
  2667. if ( typeof layout === 'string' ) {
  2668. nodeType = layout;
  2669. } else {
  2670. error( 'TSL: Invalid layout type.' );
  2671. }
  2672. layout = null;
  2673. }
  2674. }
  2675. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2676. if ( layout !== null ) {
  2677. this.setLayout( layout );
  2678. }
  2679. this.isFn = true;
  2680. }
  2681. setLayout( layout ) {
  2682. const nodeType = this.shaderNode.nodeType;
  2683. if ( typeof layout.inputs !== 'object' ) {
  2684. const fullLayout = {
  2685. name: 'fn' + fnId ++,
  2686. type: nodeType,
  2687. inputs: []
  2688. };
  2689. for ( const name in layout ) {
  2690. if ( name === 'return' ) continue;
  2691. fullLayout.inputs.push( {
  2692. name: name,
  2693. type: layout[ name ]
  2694. } );
  2695. }
  2696. layout = fullLayout;
  2697. }
  2698. this.shaderNode.setLayout( layout );
  2699. return this;
  2700. }
  2701. getNodeType( builder ) {
  2702. return this.shaderNode.getNodeType( builder ) || 'float';
  2703. }
  2704. call( ...params ) {
  2705. const fnCall = this.shaderNode.call( params );
  2706. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2707. return fnCall.toVarIntent();
  2708. }
  2709. once( subBuilds = null ) {
  2710. this.shaderNode.once = true;
  2711. this.shaderNode.subBuilds = subBuilds;
  2712. return this;
  2713. }
  2714. generate( builder ) {
  2715. const type = this.getNodeType( builder );
  2716. error( 'TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2717. return builder.generateConst( type );
  2718. }
  2719. }
  2720. function Fn( jsFunc, layout = null ) {
  2721. const instance = new FnNode( jsFunc, layout );
  2722. return new Proxy( () => {}, {
  2723. apply( target, thisArg, params ) {
  2724. return instance.call( ...params );
  2725. },
  2726. get( target, prop, receiver ) {
  2727. return Reflect.get( instance, prop, receiver );
  2728. },
  2729. set( target, prop, value, receiver ) {
  2730. return Reflect.set( instance, prop, value, receiver );
  2731. }
  2732. } );
  2733. }
  2734. //
  2735. const setCurrentStack = ( stack ) => {
  2736. currentStack = stack;
  2737. };
  2738. const getCurrentStack = () => currentStack;
  2739. /**
  2740. * Represent a conditional node using if/else statements.
  2741. *
  2742. * ```js
  2743. * If( condition, function )
  2744. * .ElseIf( condition, function )
  2745. * .Else( function )
  2746. * ```
  2747. * @tsl
  2748. * @function
  2749. * @param {...any} params - The parameters for the conditional node.
  2750. * @returns {StackNode} The conditional node.
  2751. */
  2752. const If = ( ...params ) => currentStack.If( ...params );
  2753. /**
  2754. * Represent a conditional node using switch/case statements.
  2755. *
  2756. * ```js
  2757. * Switch( value )
  2758. * .Case( 1, function )
  2759. * .Case( 2, 3, 4, function )
  2760. * .Default( function )
  2761. * ```
  2762. * @tsl
  2763. * @function
  2764. * @param {...any} params - The parameters for the conditional node.
  2765. * @returns {StackNode} The conditional node.
  2766. */
  2767. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2768. /**
  2769. * Add the given node to the current stack.
  2770. *
  2771. * @param {Node} node - The node to add.
  2772. * @returns {Node} The node that was added to the stack.
  2773. */
  2774. function Stack( node ) {
  2775. if ( currentStack ) currentStack.add( node );
  2776. return node;
  2777. }
  2778. addMethodChaining( 'toStack', Stack );
  2779. // types
  2780. const color = new ConvertType( 'color' );
  2781. const float = new ConvertType( 'float', cacheMaps.float );
  2782. const int = new ConvertType( 'int', cacheMaps.ints );
  2783. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2784. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2785. const vec2 = new ConvertType( 'vec2' );
  2786. const ivec2 = new ConvertType( 'ivec2' );
  2787. const uvec2 = new ConvertType( 'uvec2' );
  2788. const bvec2 = new ConvertType( 'bvec2' );
  2789. const vec3 = new ConvertType( 'vec3' );
  2790. const ivec3 = new ConvertType( 'ivec3' );
  2791. const uvec3 = new ConvertType( 'uvec3' );
  2792. const bvec3 = new ConvertType( 'bvec3' );
  2793. const vec4 = new ConvertType( 'vec4' );
  2794. const ivec4 = new ConvertType( 'ivec4' );
  2795. const uvec4 = new ConvertType( 'uvec4' );
  2796. const bvec4 = new ConvertType( 'bvec4' );
  2797. const mat2 = new ConvertType( 'mat2' );
  2798. const mat3 = new ConvertType( 'mat3' );
  2799. const mat4 = new ConvertType( 'mat4' );
  2800. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2801. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2802. addMethodChaining( 'toColor', color );
  2803. addMethodChaining( 'toFloat', float );
  2804. addMethodChaining( 'toInt', int );
  2805. addMethodChaining( 'toUint', uint );
  2806. addMethodChaining( 'toBool', bool );
  2807. addMethodChaining( 'toVec2', vec2 );
  2808. addMethodChaining( 'toIVec2', ivec2 );
  2809. addMethodChaining( 'toUVec2', uvec2 );
  2810. addMethodChaining( 'toBVec2', bvec2 );
  2811. addMethodChaining( 'toVec3', vec3 );
  2812. addMethodChaining( 'toIVec3', ivec3 );
  2813. addMethodChaining( 'toUVec3', uvec3 );
  2814. addMethodChaining( 'toBVec3', bvec3 );
  2815. addMethodChaining( 'toVec4', vec4 );
  2816. addMethodChaining( 'toIVec4', ivec4 );
  2817. addMethodChaining( 'toUVec4', uvec4 );
  2818. addMethodChaining( 'toBVec4', bvec4 );
  2819. addMethodChaining( 'toMat2', mat2 );
  2820. addMethodChaining( 'toMat3', mat3 );
  2821. addMethodChaining( 'toMat4', mat4 );
  2822. // basic nodes
  2823. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2824. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2825. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2826. addMethodChaining( 'element', element );
  2827. addMethodChaining( 'convert', convert );
  2828. // deprecated
  2829. /**
  2830. * @tsl
  2831. * @function
  2832. * @deprecated since r176. Use {@link Stack} instead.
  2833. *
  2834. * @param {Node} node - The node to add.
  2835. * @returns {Function}
  2836. */
  2837. const append = ( node ) => { // @deprecated, r176
  2838. warn( 'TSL: append() has been renamed to Stack().' );
  2839. return Stack( node );
  2840. };
  2841. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2842. warn( 'TSL: .append() has been renamed to .toStack().' );
  2843. return Stack( node );
  2844. } );
  2845. /**
  2846. * This class represents a shader property. It can be used
  2847. * to explicitly define a property and assign a value to it.
  2848. *
  2849. * ```js
  2850. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2851. *```
  2852. * `PropertyNode` is used by the engine to predefined common material properties
  2853. * for TSL code.
  2854. *
  2855. * @augments Node
  2856. */
  2857. class PropertyNode extends Node {
  2858. static get type() {
  2859. return 'PropertyNode';
  2860. }
  2861. /**
  2862. * Constructs a new property node.
  2863. *
  2864. * @param {string} nodeType - The type of the node.
  2865. * @param {?string} [name=null] - The name of the property in the shader.
  2866. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2867. */
  2868. constructor( nodeType, name = null, varying = false ) {
  2869. super( nodeType );
  2870. /**
  2871. * The name of the property in the shader. If no name is defined,
  2872. * the node system auto-generates one.
  2873. *
  2874. * @type {?string}
  2875. * @default null
  2876. */
  2877. this.name = name;
  2878. /**
  2879. * Whether this property is a varying or not.
  2880. *
  2881. * @type {boolean}
  2882. * @default false
  2883. */
  2884. this.varying = varying;
  2885. /**
  2886. * This flag can be used for type testing.
  2887. *
  2888. * @type {boolean}
  2889. * @readonly
  2890. * @default true
  2891. */
  2892. this.isPropertyNode = true;
  2893. /**
  2894. * This flag is used for global cache.
  2895. *
  2896. * @type {boolean}
  2897. * @default true
  2898. */
  2899. this.global = true;
  2900. }
  2901. getHash( builder ) {
  2902. return this.name || super.getHash( builder );
  2903. }
  2904. generate( builder ) {
  2905. let nodeVar;
  2906. if ( this.varying === true ) {
  2907. nodeVar = builder.getVaryingFromNode( this, this.name );
  2908. nodeVar.needsInterpolation = true;
  2909. } else {
  2910. nodeVar = builder.getVarFromNode( this, this.name );
  2911. }
  2912. return builder.getPropertyName( nodeVar );
  2913. }
  2914. }
  2915. /**
  2916. * TSL function for creating a property node.
  2917. *
  2918. * @tsl
  2919. * @function
  2920. * @param {string} type - The type of the node.
  2921. * @param {?string} [name=null] - The name of the property in the shader.
  2922. * @returns {PropertyNode}
  2923. */
  2924. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2925. /**
  2926. * TSL function for creating a varying property node.
  2927. *
  2928. * @tsl
  2929. * @function
  2930. * @param {string} type - The type of the node.
  2931. * @param {?string} [name=null] - The name of the varying in the shader.
  2932. * @returns {PropertyNode}
  2933. */
  2934. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2935. /**
  2936. * TSL object that represents the shader variable `DiffuseColor`.
  2937. *
  2938. * @tsl
  2939. * @type {PropertyNode<vec4>}
  2940. */
  2941. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2942. /**
  2943. * TSL object that represents the shader variable `EmissiveColor`.
  2944. *
  2945. * @tsl
  2946. * @type {PropertyNode<vec3>}
  2947. */
  2948. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2949. /**
  2950. * TSL object that represents the shader variable `Roughness`.
  2951. *
  2952. * @tsl
  2953. * @type {PropertyNode<float>}
  2954. */
  2955. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2956. /**
  2957. * TSL object that represents the shader variable `Metalness`.
  2958. *
  2959. * @tsl
  2960. * @type {PropertyNode<float>}
  2961. */
  2962. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2963. /**
  2964. * TSL object that represents the shader variable `Clearcoat`.
  2965. *
  2966. * @tsl
  2967. * @type {PropertyNode<float>}
  2968. */
  2969. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2970. /**
  2971. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2972. *
  2973. * @tsl
  2974. * @type {PropertyNode<float>}
  2975. */
  2976. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2977. /**
  2978. * TSL object that represents the shader variable `Sheen`.
  2979. *
  2980. * @tsl
  2981. * @type {PropertyNode<vec3>}
  2982. */
  2983. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2984. /**
  2985. * TSL object that represents the shader variable `SheenRoughness`.
  2986. *
  2987. * @tsl
  2988. * @type {PropertyNode<float>}
  2989. */
  2990. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2991. /**
  2992. * TSL object that represents the shader variable `Iridescence`.
  2993. *
  2994. * @tsl
  2995. * @type {PropertyNode<float>}
  2996. */
  2997. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2998. /**
  2999. * TSL object that represents the shader variable `IridescenceIOR`.
  3000. *
  3001. * @tsl
  3002. * @type {PropertyNode<float>}
  3003. */
  3004. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3005. /**
  3006. * TSL object that represents the shader variable `IridescenceThickness`.
  3007. *
  3008. * @tsl
  3009. * @type {PropertyNode<float>}
  3010. */
  3011. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3012. /**
  3013. * TSL object that represents the shader variable `AlphaT`.
  3014. *
  3015. * @tsl
  3016. * @type {PropertyNode<float>}
  3017. */
  3018. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3019. /**
  3020. * TSL object that represents the shader variable `Anisotropy`.
  3021. *
  3022. * @tsl
  3023. * @type {PropertyNode<float>}
  3024. */
  3025. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3026. /**
  3027. * TSL object that represents the shader variable `AnisotropyT`.
  3028. *
  3029. * @tsl
  3030. * @type {PropertyNode<vec3>}
  3031. */
  3032. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3033. /**
  3034. * TSL object that represents the shader variable `AnisotropyB`.
  3035. *
  3036. * @tsl
  3037. * @type {PropertyNode<vec3>}
  3038. */
  3039. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3040. /**
  3041. * TSL object that represents the shader variable `SpecularColor`.
  3042. *
  3043. * @tsl
  3044. * @type {PropertyNode<color>}
  3045. */
  3046. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3047. /**
  3048. * TSL object that represents the shader variable `SpecularF90`.
  3049. *
  3050. * @tsl
  3051. * @type {PropertyNode<float>}
  3052. */
  3053. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3054. /**
  3055. * TSL object that represents the shader variable `Shininess`.
  3056. *
  3057. * @tsl
  3058. * @type {PropertyNode<float>}
  3059. */
  3060. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3061. /**
  3062. * TSL object that represents the shader variable `Output`.
  3063. *
  3064. * @tsl
  3065. * @type {PropertyNode<vec4>}
  3066. */
  3067. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3068. /**
  3069. * TSL object that represents the shader variable `dashSize`.
  3070. *
  3071. * @tsl
  3072. * @type {PropertyNode<float>}
  3073. */
  3074. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3075. /**
  3076. * TSL object that represents the shader variable `gapSize`.
  3077. *
  3078. * @tsl
  3079. * @type {PropertyNode<float>}
  3080. */
  3081. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3082. /**
  3083. * TSL object that represents the shader variable `pointWidth`.
  3084. *
  3085. * @tsl
  3086. * @type {PropertyNode<float>}
  3087. */
  3088. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3089. /**
  3090. * TSL object that represents the shader variable `IOR`.
  3091. *
  3092. * @tsl
  3093. * @type {PropertyNode<float>}
  3094. */
  3095. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3096. /**
  3097. * TSL object that represents the shader variable `Transmission`.
  3098. *
  3099. * @tsl
  3100. * @type {PropertyNode<float>}
  3101. */
  3102. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3103. /**
  3104. * TSL object that represents the shader variable `Thickness`.
  3105. *
  3106. * @tsl
  3107. * @type {PropertyNode<float>}
  3108. */
  3109. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3110. /**
  3111. * TSL object that represents the shader variable `AttenuationDistance`.
  3112. *
  3113. * @tsl
  3114. * @type {PropertyNode<float>}
  3115. */
  3116. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3117. /**
  3118. * TSL object that represents the shader variable `AttenuationColor`.
  3119. *
  3120. * @tsl
  3121. * @type {PropertyNode<color>}
  3122. */
  3123. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3124. /**
  3125. * TSL object that represents the shader variable `Dispersion`.
  3126. *
  3127. * @tsl
  3128. * @type {PropertyNode<float>}
  3129. */
  3130. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3131. /**
  3132. * This node can be used to group single instances of {@link UniformNode}
  3133. * and manage them as a uniform buffer.
  3134. *
  3135. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3136. * will be used when defining the {@link UniformNode#groupNode} property.
  3137. *
  3138. * - `objectGroup`: Uniform buffer per object.
  3139. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3140. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3141. *
  3142. * @augments Node
  3143. */
  3144. class UniformGroupNode extends Node {
  3145. static get type() {
  3146. return 'UniformGroupNode';
  3147. }
  3148. /**
  3149. * Constructs a new uniform group node.
  3150. *
  3151. * @param {string} name - The name of the uniform group node.
  3152. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3153. * @param {number} [order=1] - Influences the internal sorting.
  3154. */
  3155. constructor( name, shared = false, order = 1 ) {
  3156. super( 'string' );
  3157. /**
  3158. * The name of the uniform group node.
  3159. *
  3160. * @type {string}
  3161. */
  3162. this.name = name;
  3163. /**
  3164. * Whether this uniform group node is shared or not.
  3165. *
  3166. * @type {boolean}
  3167. * @default false
  3168. */
  3169. this.shared = shared;
  3170. /**
  3171. * Influences the internal sorting.
  3172. * TODO: Add details when this property should be changed.
  3173. *
  3174. * @type {number}
  3175. * @default 1
  3176. */
  3177. this.order = order;
  3178. /**
  3179. * This flag can be used for type testing.
  3180. *
  3181. * @type {boolean}
  3182. * @readonly
  3183. * @default true
  3184. */
  3185. this.isUniformGroup = true;
  3186. }
  3187. serialize( data ) {
  3188. super.serialize( data );
  3189. data.name = this.name;
  3190. data.version = this.version;
  3191. data.shared = this.shared;
  3192. }
  3193. deserialize( data ) {
  3194. super.deserialize( data );
  3195. this.name = data.name;
  3196. this.version = data.version;
  3197. this.shared = data.shared;
  3198. }
  3199. }
  3200. /**
  3201. * TSL function for creating a uniform group node with the given name.
  3202. *
  3203. * @tsl
  3204. * @function
  3205. * @param {string} name - The name of the uniform group node.
  3206. * @returns {UniformGroupNode}
  3207. */
  3208. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3209. /**
  3210. * TSL function for creating a shared uniform group node with the given name and order.
  3211. *
  3212. * @tsl
  3213. * @function
  3214. * @param {string} name - The name of the uniform group node.
  3215. * @param {number} [order=0] - Influences the internal sorting.
  3216. * @returns {UniformGroupNode}
  3217. */
  3218. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3219. /**
  3220. * TSL object that represents a shared uniform group node which is updated once per frame.
  3221. *
  3222. * @tsl
  3223. * @type {UniformGroupNode}
  3224. */
  3225. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3226. /**
  3227. * TSL object that represents a shared uniform group node which is updated once per render.
  3228. *
  3229. * @tsl
  3230. * @type {UniformGroupNode}
  3231. */
  3232. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3233. /**
  3234. * TSL object that represents a uniform group node which is updated once per object.
  3235. *
  3236. * @tsl
  3237. * @type {UniformGroupNode}
  3238. */
  3239. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3240. /**
  3241. * Class for representing a uniform.
  3242. *
  3243. * @augments InputNode
  3244. */
  3245. class UniformNode extends InputNode {
  3246. static get type() {
  3247. return 'UniformNode';
  3248. }
  3249. /**
  3250. * Constructs a new uniform node.
  3251. *
  3252. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3253. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3254. */
  3255. constructor( value, nodeType = null ) {
  3256. super( value, nodeType );
  3257. /**
  3258. * This flag can be used for type testing.
  3259. *
  3260. * @type {boolean}
  3261. * @readonly
  3262. * @default true
  3263. */
  3264. this.isUniformNode = true;
  3265. /**
  3266. * The name or label of the uniform.
  3267. *
  3268. * @type {string}
  3269. * @default ''
  3270. */
  3271. this.name = '';
  3272. /**
  3273. * The uniform group of this uniform. By default, uniforms are
  3274. * managed per object but they might belong to a shared group
  3275. * which is updated per frame or render call.
  3276. *
  3277. * @type {UniformGroupNode}
  3278. */
  3279. this.groupNode = objectGroup;
  3280. }
  3281. /**
  3282. * Sets the {@link UniformNode#name} property.
  3283. *
  3284. * @param {string} name - The name of the uniform.
  3285. * @return {UniformNode} A reference to this node.
  3286. */
  3287. setName( name ) {
  3288. this.name = name;
  3289. return this;
  3290. }
  3291. /**
  3292. * Sets the {@link UniformNode#name} property.
  3293. *
  3294. * @deprecated
  3295. * @param {string} name - The name of the uniform.
  3296. * @return {UniformNode} A reference to this node.
  3297. */
  3298. label( name ) {
  3299. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3300. return this.setName( name );
  3301. }
  3302. /**
  3303. * Sets the {@link UniformNode#groupNode} property.
  3304. *
  3305. * @param {UniformGroupNode} group - The uniform group.
  3306. * @return {UniformNode} A reference to this node.
  3307. */
  3308. setGroup( group ) {
  3309. this.groupNode = group;
  3310. return this;
  3311. }
  3312. /**
  3313. * Returns the {@link UniformNode#groupNode}.
  3314. *
  3315. * @return {UniformGroupNode} The uniform group.
  3316. */
  3317. getGroup() {
  3318. return this.groupNode;
  3319. }
  3320. /**
  3321. * By default, this method returns the result of {@link Node#getHash} but derived
  3322. * classes might overwrite this method with a different implementation.
  3323. *
  3324. * @param {NodeBuilder} builder - The current node builder.
  3325. * @return {string} The uniform hash.
  3326. */
  3327. getUniformHash( builder ) {
  3328. return this.getHash( builder );
  3329. }
  3330. onUpdate( callback, updateType ) {
  3331. callback = callback.bind( this );
  3332. return super.onUpdate( ( frame ) => {
  3333. const value = callback( frame, this );
  3334. if ( value !== undefined ) {
  3335. this.value = value;
  3336. }
  3337. }, updateType );
  3338. }
  3339. getInputType( builder ) {
  3340. let type = super.getInputType( builder );
  3341. if ( type === 'bool' ) {
  3342. type = 'uint';
  3343. }
  3344. return type;
  3345. }
  3346. generate( builder, output ) {
  3347. const type = this.getNodeType( builder );
  3348. const hash = this.getUniformHash( builder );
  3349. let sharedNode = builder.getNodeFromHash( hash );
  3350. if ( sharedNode === undefined ) {
  3351. builder.setHashNode( this, hash );
  3352. sharedNode = this;
  3353. }
  3354. const sharedNodeType = sharedNode.getInputType( builder );
  3355. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3356. const uniformName = builder.getPropertyName( nodeUniform );
  3357. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3358. //
  3359. let snippet = uniformName;
  3360. if ( type === 'bool' ) {
  3361. // cache to variable
  3362. const nodeData = builder.getDataFromNode( this );
  3363. let propertyName = nodeData.propertyName;
  3364. if ( propertyName === undefined ) {
  3365. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3366. propertyName = builder.getPropertyName( nodeVar );
  3367. nodeData.propertyName = propertyName;
  3368. snippet = builder.format( uniformName, sharedNodeType, type );
  3369. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3370. }
  3371. snippet = propertyName;
  3372. }
  3373. return builder.format( snippet, type, output );
  3374. }
  3375. }
  3376. /**
  3377. * TSL function for creating a uniform node.
  3378. *
  3379. * @tsl
  3380. * @function
  3381. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3382. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3383. * @returns {UniformNode}
  3384. */
  3385. const uniform = ( value, type ) => {
  3386. const nodeType = getConstNodeType( type || value );
  3387. if ( nodeType === value ) {
  3388. // if the value is a type but no having a value
  3389. value = getValueFromType( nodeType );
  3390. }
  3391. // @TODO: get ConstNode from .traverse() in the future
  3392. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3393. return nodeObject( new UniformNode( value, nodeType ) );
  3394. };
  3395. /**
  3396. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3397. * ```js
  3398. * const colors = array( [
  3399. * vec3( 1, 0, 0 ),
  3400. * vec3( 0, 1, 0 ),
  3401. * vec3( 0, 0, 1 )
  3402. * ] );
  3403. *
  3404. * const redColor = tintColors.element( 0 );
  3405. *
  3406. * @augments TempNode
  3407. */
  3408. class ArrayNode extends TempNode {
  3409. static get type() {
  3410. return 'ArrayNode';
  3411. }
  3412. /**
  3413. * Constructs a new array node.
  3414. *
  3415. * @param {?string} nodeType - The data type of the elements.
  3416. * @param {number} count - Size of the array.
  3417. * @param {?Array<Node>} [values=null] - Array default values.
  3418. */
  3419. constructor( nodeType, count, values = null ) {
  3420. super( nodeType );
  3421. /**
  3422. * Array size.
  3423. *
  3424. * @type {number}
  3425. */
  3426. this.count = count;
  3427. /**
  3428. * Array default values.
  3429. *
  3430. * @type {?Array<Node>}
  3431. */
  3432. this.values = values;
  3433. /**
  3434. * This flag can be used for type testing.
  3435. *
  3436. * @type {boolean}
  3437. * @readonly
  3438. * @default true
  3439. */
  3440. this.isArrayNode = true;
  3441. }
  3442. /**
  3443. * Returns the number of elements in the node array.
  3444. *
  3445. * @param {NodeBuilder} builder - The current node builder.
  3446. * @return {number} The number of elements in the node array.
  3447. */
  3448. getArrayCount( /*builder*/ ) {
  3449. return this.count;
  3450. }
  3451. /**
  3452. * Returns the node's type.
  3453. *
  3454. * @param {NodeBuilder} builder - The current node builder.
  3455. * @return {string} The type of the node.
  3456. */
  3457. getNodeType( builder ) {
  3458. if ( this.nodeType === null ) {
  3459. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3460. }
  3461. return this.nodeType;
  3462. }
  3463. /**
  3464. * Returns the node's type.
  3465. *
  3466. * @param {NodeBuilder} builder - The current node builder.
  3467. * @return {string} The type of the node.
  3468. */
  3469. getElementType( builder ) {
  3470. return this.getNodeType( builder );
  3471. }
  3472. /**
  3473. * This method builds the output node and returns the resulting array as a shader string.
  3474. *
  3475. * @param {NodeBuilder} builder - The current node builder.
  3476. * @return {string} The generated shader string.
  3477. */
  3478. generate( builder ) {
  3479. const type = this.getNodeType( builder );
  3480. return builder.generateArray( type, this.count, this.values );
  3481. }
  3482. }
  3483. /**
  3484. * TSL function for creating an array node.
  3485. *
  3486. * @tsl
  3487. * @function
  3488. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3489. * or an array containing the default values (e.g., [ vec3() ]).
  3490. * @param {?number} [count] - Size of the array.
  3491. * @returns {ArrayNode}
  3492. */
  3493. const array = ( ...params ) => {
  3494. let node;
  3495. if ( params.length === 1 ) {
  3496. const values = params[ 0 ];
  3497. node = new ArrayNode( null, values.length, values );
  3498. } else {
  3499. const nodeType = params[ 0 ];
  3500. const count = params[ 1 ];
  3501. node = new ArrayNode( nodeType, count );
  3502. }
  3503. return nodeObject( node );
  3504. };
  3505. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3506. /**
  3507. * These node represents an assign operation. Meaning a node is assigned
  3508. * to another node.
  3509. *
  3510. * @augments TempNode
  3511. */
  3512. class AssignNode extends TempNode {
  3513. static get type() {
  3514. return 'AssignNode';
  3515. }
  3516. /**
  3517. * Constructs a new assign node.
  3518. *
  3519. * @param {Node} targetNode - The target node.
  3520. * @param {Node} sourceNode - The source type.
  3521. */
  3522. constructor( targetNode, sourceNode ) {
  3523. super();
  3524. /**
  3525. * The target node.
  3526. *
  3527. * @type {Node}
  3528. */
  3529. this.targetNode = targetNode;
  3530. /**
  3531. * The source node.
  3532. *
  3533. * @type {Node}
  3534. */
  3535. this.sourceNode = sourceNode;
  3536. /**
  3537. * This flag can be used for type testing.
  3538. *
  3539. * @type {boolean}
  3540. * @readonly
  3541. * @default true
  3542. */
  3543. this.isAssignNode = true;
  3544. }
  3545. /**
  3546. * Whether this node is used more than once in context of other nodes. This method
  3547. * is overwritten since it always returns `false` (assigns are unique).
  3548. *
  3549. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3550. */
  3551. hasDependencies() {
  3552. return false;
  3553. }
  3554. getNodeType( builder, output ) {
  3555. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3556. }
  3557. /**
  3558. * Whether a split is required when assigning source to target. This can happen when the component length of
  3559. * target and source data type does not match.
  3560. *
  3561. * @param {NodeBuilder} builder - The current node builder.
  3562. * @return {boolean} Whether a split is required when assigning source to target.
  3563. */
  3564. needsSplitAssign( builder ) {
  3565. const { targetNode } = this;
  3566. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3567. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3568. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3569. return assignDifferentVector;
  3570. }
  3571. return false;
  3572. }
  3573. setup( builder ) {
  3574. const { targetNode, sourceNode } = this;
  3575. const scope = targetNode.getScope();
  3576. const targetProperties = builder.getNodeProperties( scope );
  3577. targetProperties.assign = true;
  3578. const properties = builder.getNodeProperties( this );
  3579. properties.sourceNode = sourceNode;
  3580. properties.targetNode = targetNode.context( { assign: true } );
  3581. }
  3582. generate( builder, output ) {
  3583. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3584. const needsSplitAssign = this.needsSplitAssign( builder );
  3585. const target = targetNode.build( builder );
  3586. const targetType = targetNode.getNodeType( builder );
  3587. const source = sourceNode.build( builder, targetType );
  3588. const sourceType = sourceNode.getNodeType( builder );
  3589. const nodeData = builder.getDataFromNode( this );
  3590. //
  3591. let snippet;
  3592. if ( nodeData.initialized === true ) {
  3593. if ( output !== 'void' ) {
  3594. snippet = target;
  3595. }
  3596. } else if ( needsSplitAssign ) {
  3597. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3598. const sourceProperty = builder.getPropertyName( sourceVar );
  3599. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3600. const splitNode = targetNode.node;
  3601. const splitTargetNode = splitNode.node.context( { assign: true } );
  3602. const targetRoot = splitTargetNode.build( builder );
  3603. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3604. const component = splitNode.components[ i ];
  3605. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3606. }
  3607. if ( output !== 'void' ) {
  3608. snippet = target;
  3609. }
  3610. } else {
  3611. snippet = `${ target } = ${ source }`;
  3612. if ( output === 'void' || sourceType === 'void' ) {
  3613. builder.addLineFlowCode( snippet, this );
  3614. if ( output !== 'void' ) {
  3615. snippet = target;
  3616. }
  3617. }
  3618. }
  3619. nodeData.initialized = true;
  3620. return builder.format( snippet, targetType, output );
  3621. }
  3622. }
  3623. /**
  3624. * TSL function for creating an assign node.
  3625. *
  3626. * @tsl
  3627. * @function
  3628. * @param {Node} targetNode - The target node.
  3629. * @param {Node} sourceNode - The source type.
  3630. * @returns {AssignNode}
  3631. */
  3632. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3633. addMethodChaining( 'assign', assign );
  3634. /**
  3635. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3636. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3637. * this logic.
  3638. *
  3639. * @augments TempNode
  3640. */
  3641. class FunctionCallNode extends TempNode {
  3642. static get type() {
  3643. return 'FunctionCallNode';
  3644. }
  3645. /**
  3646. * Constructs a new function call node.
  3647. *
  3648. * @param {?FunctionNode} functionNode - The function node.
  3649. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3650. */
  3651. constructor( functionNode = null, parameters = {} ) {
  3652. super();
  3653. /**
  3654. * The function node.
  3655. *
  3656. * @type {?FunctionNode}
  3657. * @default null
  3658. */
  3659. this.functionNode = functionNode;
  3660. /**
  3661. * The parameters of the function call.
  3662. *
  3663. * @type {Object<string, Node>}
  3664. * @default {}
  3665. */
  3666. this.parameters = parameters;
  3667. }
  3668. /**
  3669. * Sets the parameters of the function call node.
  3670. *
  3671. * @param {Object<string, Node>} parameters - The parameters to set.
  3672. * @return {FunctionCallNode} A reference to this node.
  3673. */
  3674. setParameters( parameters ) {
  3675. this.parameters = parameters;
  3676. return this;
  3677. }
  3678. /**
  3679. * Returns the parameters of the function call node.
  3680. *
  3681. * @return {Object<string, Node>} The parameters of this node.
  3682. */
  3683. getParameters() {
  3684. return this.parameters;
  3685. }
  3686. /**
  3687. * Returns the type of this function call node.
  3688. *
  3689. * @param {NodeBuilder} builder - The current node builder.
  3690. * @returns {string} The type of this node.
  3691. */
  3692. getNodeType( builder ) {
  3693. return this.functionNode.getNodeType( builder );
  3694. }
  3695. /**
  3696. * Returns the function node of this function call node.
  3697. *
  3698. * @param {NodeBuilder} builder - The current node builder.
  3699. * @param {string} [name] - The name of the member.
  3700. * @returns {string} The type of the member.
  3701. */
  3702. getMemberType( builder, name ) {
  3703. return this.functionNode.getMemberType( builder, name );
  3704. }
  3705. generate( builder ) {
  3706. const params = [];
  3707. const functionNode = this.functionNode;
  3708. const inputs = functionNode.getInputs( builder );
  3709. const parameters = this.parameters;
  3710. const generateInput = ( node, inputNode ) => {
  3711. const type = inputNode.type;
  3712. const pointer = type === 'pointer';
  3713. let output;
  3714. if ( pointer ) output = '&' + node.build( builder );
  3715. else output = node.build( builder, type );
  3716. return output;
  3717. };
  3718. if ( Array.isArray( parameters ) ) {
  3719. if ( parameters.length > inputs.length ) {
  3720. error( 'TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3721. parameters.length = inputs.length;
  3722. } else if ( parameters.length < inputs.length ) {
  3723. error( 'TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3724. while ( parameters.length < inputs.length ) {
  3725. parameters.push( float( 0 ) );
  3726. }
  3727. }
  3728. for ( let i = 0; i < parameters.length; i ++ ) {
  3729. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3730. }
  3731. } else {
  3732. for ( const inputNode of inputs ) {
  3733. const node = parameters[ inputNode.name ];
  3734. if ( node !== undefined ) {
  3735. params.push( generateInput( node, inputNode ) );
  3736. } else {
  3737. error( `TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3738. params.push( generateInput( float( 0 ), inputNode ) );
  3739. }
  3740. }
  3741. }
  3742. const functionName = functionNode.build( builder, 'property' );
  3743. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3744. }
  3745. }
  3746. const call = ( func, ...params ) => {
  3747. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3748. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3749. };
  3750. addMethodChaining( 'call', call );
  3751. const _vectorOperators = {
  3752. '==': 'equal',
  3753. '!=': 'notEqual',
  3754. '<': 'lessThan',
  3755. '>': 'greaterThan',
  3756. '<=': 'lessThanEqual',
  3757. '>=': 'greaterThanEqual',
  3758. '%': 'mod'
  3759. };
  3760. /**
  3761. * This node represents basic mathematical and logical operations like addition,
  3762. * subtraction or comparisons (e.g. `equal()`).
  3763. *
  3764. * @augments TempNode
  3765. */
  3766. class OperatorNode extends TempNode {
  3767. static get type() {
  3768. return 'OperatorNode';
  3769. }
  3770. /**
  3771. * Constructs a new operator node.
  3772. *
  3773. * @param {string} op - The operator.
  3774. * @param {Node} aNode - The first input.
  3775. * @param {Node} bNode - The second input.
  3776. * @param {...Node} params - Additional input parameters.
  3777. */
  3778. constructor( op, aNode, bNode, ...params ) {
  3779. super();
  3780. if ( params.length > 0 ) {
  3781. let finalOp = new OperatorNode( op, aNode, bNode );
  3782. for ( let i = 0; i < params.length - 1; i ++ ) {
  3783. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3784. }
  3785. aNode = finalOp;
  3786. bNode = params[ params.length - 1 ];
  3787. }
  3788. /**
  3789. * The operator.
  3790. *
  3791. * @type {string}
  3792. */
  3793. this.op = op;
  3794. /**
  3795. * The first input.
  3796. *
  3797. * @type {Node}
  3798. */
  3799. this.aNode = aNode;
  3800. /**
  3801. * The second input.
  3802. *
  3803. * @type {Node}
  3804. */
  3805. this.bNode = bNode;
  3806. /**
  3807. * This flag can be used for type testing.
  3808. *
  3809. * @type {boolean}
  3810. * @readonly
  3811. * @default true
  3812. */
  3813. this.isOperatorNode = true;
  3814. }
  3815. /**
  3816. * Returns the operator method name.
  3817. *
  3818. * @param {NodeBuilder} builder - The current node builder.
  3819. * @param {string} output - The output type.
  3820. * @returns {string} The operator method name.
  3821. */
  3822. getOperatorMethod( builder, output ) {
  3823. return builder.getMethod( _vectorOperators[ this.op ], output );
  3824. }
  3825. /**
  3826. * This method is overwritten since the node type is inferred from the operator
  3827. * and the input node types.
  3828. *
  3829. * @param {NodeBuilder} builder - The current node builder.
  3830. * @param {?string} [output=null] - The output type.
  3831. * @return {string} The node type.
  3832. */
  3833. getNodeType( builder, output = null ) {
  3834. const op = this.op;
  3835. const aNode = this.aNode;
  3836. const bNode = this.bNode;
  3837. const typeA = aNode.getNodeType( builder );
  3838. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3839. if ( typeA === 'void' || typeB === 'void' ) {
  3840. return output || 'void';
  3841. } else if ( op === '%' ) {
  3842. return typeA;
  3843. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3844. return builder.getIntegerType( typeA );
  3845. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3846. return 'bool';
  3847. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3848. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3849. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3850. } else {
  3851. // Handle matrix operations
  3852. if ( builder.isMatrix( typeA ) ) {
  3853. if ( typeB === 'float' ) {
  3854. return typeA; // matrix * scalar = matrix
  3855. } else if ( builder.isVector( typeB ) ) {
  3856. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3857. } else if ( builder.isMatrix( typeB ) ) {
  3858. return typeA; // matrix * matrix
  3859. }
  3860. } else if ( builder.isMatrix( typeB ) ) {
  3861. if ( typeA === 'float' ) {
  3862. return typeB; // scalar * matrix = matrix
  3863. } else if ( builder.isVector( typeA ) ) {
  3864. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3865. }
  3866. }
  3867. // Handle non-matrix cases
  3868. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3869. // anytype x anytype: use the greater length vector
  3870. return typeB;
  3871. }
  3872. return typeA;
  3873. }
  3874. }
  3875. generate( builder, output ) {
  3876. const op = this.op;
  3877. const { aNode, bNode } = this;
  3878. const type = this.getNodeType( builder, output );
  3879. let typeA = null;
  3880. let typeB = null;
  3881. if ( type !== 'void' ) {
  3882. typeA = aNode.getNodeType( builder );
  3883. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3884. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3885. if ( builder.isVector( typeA ) ) {
  3886. typeB = typeA;
  3887. } else if ( builder.isVector( typeB ) ) {
  3888. typeA = typeB;
  3889. } else if ( typeA !== typeB ) {
  3890. typeA = typeB = 'float';
  3891. }
  3892. } else if ( op === '>>' || op === '<<' ) {
  3893. typeA = type;
  3894. typeB = builder.changeComponentType( typeB, 'uint' );
  3895. } else if ( op === '%' ) {
  3896. typeA = type;
  3897. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3898. } else if ( builder.isMatrix( typeA ) ) {
  3899. if ( typeB === 'float' ) {
  3900. // Keep matrix type for typeA, but ensure typeB stays float
  3901. typeB = 'float';
  3902. } else if ( builder.isVector( typeB ) ) {
  3903. // matrix x vector
  3904. typeB = builder.getVectorFromMatrix( typeA );
  3905. } else if ( builder.isMatrix( typeB ) ) ; else {
  3906. typeA = typeB = type;
  3907. }
  3908. } else if ( builder.isMatrix( typeB ) ) {
  3909. if ( typeA === 'float' ) {
  3910. // Keep matrix type for typeB, but ensure typeA stays float
  3911. typeA = 'float';
  3912. } else if ( builder.isVector( typeA ) ) {
  3913. // vector x matrix
  3914. typeA = builder.getVectorFromMatrix( typeB );
  3915. } else {
  3916. typeA = typeB = type;
  3917. }
  3918. } else {
  3919. // anytype x anytype
  3920. typeA = typeB = type;
  3921. }
  3922. } else {
  3923. typeA = typeB = type;
  3924. }
  3925. const a = aNode.build( builder, typeA );
  3926. const b = bNode ? bNode.build( builder, typeB ) : null;
  3927. const fnOpSnippet = builder.getFunctionOperator( op );
  3928. if ( output !== 'void' ) {
  3929. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3930. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3931. if ( isGLSL ) {
  3932. if ( builder.isVector( typeA ) ) {
  3933. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3934. } else {
  3935. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3936. }
  3937. } else {
  3938. // WGSL
  3939. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3940. }
  3941. } else if ( op === '%' ) {
  3942. if ( builder.isInteger( typeB ) ) {
  3943. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3944. } else {
  3945. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3946. }
  3947. } else if ( op === '!' || op === '~' ) {
  3948. return builder.format( `(${op}${a})`, typeA, output );
  3949. } else if ( fnOpSnippet ) {
  3950. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3951. } else {
  3952. // Handle matrix operations
  3953. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3954. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3955. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3956. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3957. } else {
  3958. let snippet = `( ${ a } ${ op } ${ b } )`;
  3959. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3960. snippet = `all${ snippet }`;
  3961. }
  3962. return builder.format( snippet, type, output );
  3963. }
  3964. }
  3965. } else if ( typeA !== 'void' ) {
  3966. if ( fnOpSnippet ) {
  3967. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3968. } else {
  3969. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3970. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3971. } else {
  3972. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3973. }
  3974. }
  3975. }
  3976. }
  3977. serialize( data ) {
  3978. super.serialize( data );
  3979. data.op = this.op;
  3980. }
  3981. deserialize( data ) {
  3982. super.deserialize( data );
  3983. this.op = data.op;
  3984. }
  3985. }
  3986. /**
  3987. * Returns the addition of two or more value.
  3988. *
  3989. * @tsl
  3990. * @function
  3991. * @param {Node} a - The first input.
  3992. * @param {Node} b - The second input.
  3993. * @param {...Node} params - Additional input parameters.
  3994. * @returns {OperatorNode}
  3995. */
  3996. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3997. /**
  3998. * Returns the subtraction of two or more value.
  3999. *
  4000. * @tsl
  4001. * @function
  4002. * @param {Node} a - The first input.
  4003. * @param {Node} b - The second input.
  4004. * @param {...Node} params - Additional input parameters.
  4005. * @returns {OperatorNode}
  4006. */
  4007. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4008. /**
  4009. * Returns the multiplication of two or more value.
  4010. *
  4011. * @tsl
  4012. * @function
  4013. * @param {Node} a - The first input.
  4014. * @param {Node} b - The second input.
  4015. * @param {...Node} params - Additional input parameters.
  4016. * @returns {OperatorNode}
  4017. */
  4018. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4019. /**
  4020. * Returns the division of two or more value.
  4021. *
  4022. * @tsl
  4023. * @function
  4024. * @param {Node} a - The first input.
  4025. * @param {Node} b - The second input.
  4026. * @param {...Node} params - Additional input parameters.
  4027. * @returns {OperatorNode}
  4028. */
  4029. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4030. /**
  4031. * Computes the remainder of dividing the first node by the second one.
  4032. *
  4033. * @tsl
  4034. * @function
  4035. * @param {Node} a - The first input.
  4036. * @param {Node} b - The second input.
  4037. * @returns {OperatorNode}
  4038. */
  4039. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4040. /**
  4041. * Checks if two nodes are equal.
  4042. *
  4043. * @tsl
  4044. * @function
  4045. * @param {Node} a - The first input.
  4046. * @param {Node} b - The second input.
  4047. * @returns {OperatorNode}
  4048. */
  4049. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4050. /**
  4051. * Checks if two nodes are not equal.
  4052. *
  4053. * @tsl
  4054. * @function
  4055. * @param {Node} a - The first input.
  4056. * @param {Node} b - The second input.
  4057. * @returns {OperatorNode}
  4058. */
  4059. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4060. /**
  4061. * Checks if the first node is less than the second.
  4062. *
  4063. * @tsl
  4064. * @function
  4065. * @param {Node} a - The first input.
  4066. * @param {Node} b - The second input.
  4067. * @returns {OperatorNode}
  4068. */
  4069. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4070. /**
  4071. * Checks if the first node is greater than the second.
  4072. *
  4073. * @tsl
  4074. * @function
  4075. * @param {Node} a - The first input.
  4076. * @param {Node} b - The second input.
  4077. * @returns {OperatorNode}
  4078. */
  4079. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4080. /**
  4081. * Checks if the first node is less than or equal to the second.
  4082. *
  4083. * @tsl
  4084. * @function
  4085. * @param {Node} a - The first input.
  4086. * @param {Node} b - The second input.
  4087. * @returns {OperatorNode}
  4088. */
  4089. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4090. /**
  4091. * Checks if the first node is greater than or equal to the second.
  4092. *
  4093. * @tsl
  4094. * @function
  4095. * @param {Node} a - The first input.
  4096. * @param {Node} b - The second input.
  4097. * @returns {OperatorNode}
  4098. */
  4099. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4100. /**
  4101. * Performs a logical AND operation on multiple nodes.
  4102. *
  4103. * @tsl
  4104. * @function
  4105. * @param {...Node} nodes - The input nodes to be combined using AND.
  4106. * @returns {OperatorNode}
  4107. */
  4108. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4109. /**
  4110. * Performs a logical OR operation on multiple nodes.
  4111. *
  4112. * @tsl
  4113. * @function
  4114. * @param {...Node} nodes - The input nodes to be combined using OR.
  4115. * @returns {OperatorNode}
  4116. */
  4117. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4118. /**
  4119. * Performs logical NOT on a node.
  4120. *
  4121. * @tsl
  4122. * @function
  4123. * @param {Node} value - The value.
  4124. * @returns {OperatorNode}
  4125. */
  4126. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4127. /**
  4128. * Performs logical XOR on two nodes.
  4129. *
  4130. * @tsl
  4131. * @function
  4132. * @param {Node} a - The first input.
  4133. * @param {Node} b - The second input.
  4134. * @returns {OperatorNode}
  4135. */
  4136. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4137. /**
  4138. * Performs bitwise AND on two nodes.
  4139. *
  4140. * @tsl
  4141. * @function
  4142. * @param {Node} a - The first input.
  4143. * @param {Node} b - The second input.
  4144. * @returns {OperatorNode}
  4145. */
  4146. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4147. /**
  4148. * Performs bitwise NOT on a node.
  4149. *
  4150. * @tsl
  4151. * @function
  4152. * @param {Node} a - The first input.
  4153. * @param {Node} b - The second input.
  4154. * @returns {OperatorNode}
  4155. */
  4156. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 1 ).setName( 'bitNot' );
  4157. /**
  4158. * Performs bitwise OR on two nodes.
  4159. *
  4160. * @tsl
  4161. * @function
  4162. * @param {Node} a - The first input.
  4163. * @param {Node} b - The second input.
  4164. * @returns {OperatorNode}
  4165. */
  4166. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4167. /**
  4168. * Performs bitwise XOR on two nodes.
  4169. *
  4170. * @tsl
  4171. * @function
  4172. * @param {Node} a - The first input.
  4173. * @param {Node} b - The second input.
  4174. * @returns {OperatorNode}
  4175. */
  4176. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4177. /**
  4178. * Shifts a node to the left.
  4179. *
  4180. * @tsl
  4181. * @function
  4182. * @param {Node} a - The node to shift.
  4183. * @param {Node} b - The value to shift.
  4184. * @returns {OperatorNode}
  4185. */
  4186. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4187. /**
  4188. * Shifts a node to the right.
  4189. *
  4190. * @tsl
  4191. * @function
  4192. * @param {Node} a - The node to shift.
  4193. * @param {Node} b - The value to shift.
  4194. * @returns {OperatorNode}
  4195. */
  4196. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4197. /**
  4198. * Increments a node by 1.
  4199. *
  4200. * @tsl
  4201. * @function
  4202. * @param {Node} a - The node to increment.
  4203. * @returns {OperatorNode}
  4204. */
  4205. const incrementBefore = Fn( ( [ a ] ) => {
  4206. a.addAssign( 1 );
  4207. return a;
  4208. } );
  4209. /**
  4210. * Decrements a node by 1.
  4211. *
  4212. * @tsl
  4213. * @function
  4214. * @param {Node} a - The node to decrement.
  4215. * @returns {OperatorNode}
  4216. */
  4217. const decrementBefore = Fn( ( [ a ] ) => {
  4218. a.subAssign( 1 );
  4219. return a;
  4220. } );
  4221. /**
  4222. * Increments a node by 1 and returns the previous value.
  4223. *
  4224. * @tsl
  4225. * @function
  4226. * @param {Node} a - The node to increment.
  4227. * @returns {OperatorNode}
  4228. */
  4229. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4230. const temp = int( a ).toConst();
  4231. a.addAssign( 1 );
  4232. return temp;
  4233. } );
  4234. /**
  4235. * Decrements a node by 1 and returns the previous value.
  4236. *
  4237. * @tsl
  4238. * @function
  4239. * @param {Node} a - The node to decrement.
  4240. * @returns {OperatorNode}
  4241. */
  4242. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4243. const temp = int( a ).toConst();
  4244. a.subAssign( 1 );
  4245. return temp;
  4246. } );
  4247. addMethodChaining( 'add', add );
  4248. addMethodChaining( 'sub', sub );
  4249. addMethodChaining( 'mul', mul );
  4250. addMethodChaining( 'div', div );
  4251. addMethodChaining( 'mod', mod );
  4252. addMethodChaining( 'equal', equal );
  4253. addMethodChaining( 'notEqual', notEqual );
  4254. addMethodChaining( 'lessThan', lessThan );
  4255. addMethodChaining( 'greaterThan', greaterThan );
  4256. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4257. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4258. addMethodChaining( 'and', and );
  4259. addMethodChaining( 'or', or );
  4260. addMethodChaining( 'not', not );
  4261. addMethodChaining( 'xor', xor );
  4262. addMethodChaining( 'bitAnd', bitAnd );
  4263. addMethodChaining( 'bitNot', bitNot );
  4264. addMethodChaining( 'bitOr', bitOr );
  4265. addMethodChaining( 'bitXor', bitXor );
  4266. addMethodChaining( 'shiftLeft', shiftLeft );
  4267. addMethodChaining( 'shiftRight', shiftRight );
  4268. addMethodChaining( 'incrementBefore', incrementBefore );
  4269. addMethodChaining( 'decrementBefore', decrementBefore );
  4270. addMethodChaining( 'increment', increment );
  4271. addMethodChaining( 'decrement', decrement );
  4272. /**
  4273. * @tsl
  4274. * @function
  4275. * @deprecated since r175. Use {@link mod} instead.
  4276. *
  4277. * @param {Node} a - The first input.
  4278. * @param {Node} b - The second input.
  4279. * @returns {OperatorNode}
  4280. */
  4281. const modInt = ( a, b ) => { // @deprecated, r175
  4282. warn( 'TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4283. return mod( int( a ), int( b ) );
  4284. };
  4285. addMethodChaining( 'modInt', modInt );
  4286. /**
  4287. * This node represents a variety of mathematical methods available in shaders.
  4288. * They are divided into three categories:
  4289. *
  4290. * - Methods with one input like `sin`, `cos` or `normalize`.
  4291. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4292. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4293. *
  4294. * @augments TempNode
  4295. */
  4296. class MathNode extends TempNode {
  4297. static get type() {
  4298. return 'MathNode';
  4299. }
  4300. /**
  4301. * Constructs a new math node.
  4302. *
  4303. * @param {string} method - The method name.
  4304. * @param {Node} aNode - The first input.
  4305. * @param {?Node} [bNode=null] - The second input.
  4306. * @param {?Node} [cNode=null] - The third input.
  4307. */
  4308. constructor( method, aNode, bNode = null, cNode = null ) {
  4309. super();
  4310. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4311. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4312. let finalOp = new MathNode( method, aNode, bNode );
  4313. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4314. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4315. }
  4316. aNode = finalOp;
  4317. bNode = arguments[ arguments.length - 1 ];
  4318. cNode = null;
  4319. }
  4320. /**
  4321. * The method name.
  4322. *
  4323. * @type {string}
  4324. */
  4325. this.method = method;
  4326. /**
  4327. * The first input.
  4328. *
  4329. * @type {Node}
  4330. */
  4331. this.aNode = aNode;
  4332. /**
  4333. * The second input.
  4334. *
  4335. * @type {?Node}
  4336. * @default null
  4337. */
  4338. this.bNode = bNode;
  4339. /**
  4340. * The third input.
  4341. *
  4342. * @type {?Node}
  4343. * @default null
  4344. */
  4345. this.cNode = cNode;
  4346. /**
  4347. * This flag can be used for type testing.
  4348. *
  4349. * @type {boolean}
  4350. * @readonly
  4351. * @default true
  4352. */
  4353. this.isMathNode = true;
  4354. }
  4355. /**
  4356. * The input type is inferred from the node types of the input nodes.
  4357. *
  4358. * @param {NodeBuilder} builder - The current node builder.
  4359. * @return {string} The input type.
  4360. */
  4361. getInputType( builder ) {
  4362. const aType = this.aNode.getNodeType( builder );
  4363. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4364. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4365. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4366. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4367. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4368. if ( aLen > bLen && aLen > cLen ) {
  4369. return aType;
  4370. } else if ( bLen > cLen ) {
  4371. return bType;
  4372. } else if ( cLen > aLen ) {
  4373. return cType;
  4374. }
  4375. return aType;
  4376. }
  4377. /**
  4378. * The selected method as well as the input type determine the node type of this node.
  4379. *
  4380. * @param {NodeBuilder} builder - The current node builder.
  4381. * @return {string} The node type.
  4382. */
  4383. getNodeType( builder ) {
  4384. const method = this.method;
  4385. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4386. return 'float';
  4387. } else if ( method === MathNode.CROSS ) {
  4388. return 'vec3';
  4389. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4390. return 'bool';
  4391. } else if ( method === MathNode.EQUALS ) {
  4392. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4393. } else {
  4394. return this.getInputType( builder );
  4395. }
  4396. }
  4397. setup( builder ) {
  4398. const { aNode, bNode, method } = this;
  4399. let outputNode = null;
  4400. if ( method === MathNode.ONE_MINUS ) {
  4401. outputNode = sub( 1.0, aNode );
  4402. } else if ( method === MathNode.RECIPROCAL ) {
  4403. outputNode = div( 1.0, aNode );
  4404. } else if ( method === MathNode.DIFFERENCE ) {
  4405. outputNode = abs( sub( aNode, bNode ) );
  4406. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4407. // dir can be either a direction vector or a normal vector
  4408. // upper-left 3x3 of matrix is assumed to be orthogonal
  4409. let tA = aNode;
  4410. let tB = bNode;
  4411. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4412. tB = vec4( vec3( tB ), 0.0 );
  4413. } else {
  4414. tA = vec4( vec3( tA ), 0.0 );
  4415. }
  4416. const mulNode = mul( tA, tB ).xyz;
  4417. outputNode = normalize( mulNode );
  4418. }
  4419. if ( outputNode !== null ) {
  4420. return outputNode;
  4421. } else {
  4422. return super.setup( builder );
  4423. }
  4424. }
  4425. generate( builder, output ) {
  4426. const properties = builder.getNodeProperties( this );
  4427. if ( properties.outputNode ) {
  4428. return super.generate( builder, output );
  4429. }
  4430. let method = this.method;
  4431. const type = this.getNodeType( builder );
  4432. const inputType = this.getInputType( builder );
  4433. const a = this.aNode;
  4434. const b = this.bNode;
  4435. const c = this.cNode;
  4436. const coordinateSystem = builder.renderer.coordinateSystem;
  4437. if ( method === MathNode.NEGATE ) {
  4438. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4439. } else {
  4440. const params = [];
  4441. if ( method === MathNode.CROSS ) {
  4442. params.push(
  4443. a.build( builder, type ),
  4444. b.build( builder, type )
  4445. );
  4446. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4447. params.push(
  4448. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4449. b.build( builder, inputType )
  4450. );
  4451. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4452. params.push(
  4453. a.build( builder, inputType ),
  4454. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4455. );
  4456. } else if ( method === MathNode.REFRACT ) {
  4457. params.push(
  4458. a.build( builder, inputType ),
  4459. b.build( builder, inputType ),
  4460. c.build( builder, 'float' )
  4461. );
  4462. } else if ( method === MathNode.MIX ) {
  4463. params.push(
  4464. a.build( builder, inputType ),
  4465. b.build( builder, inputType ),
  4466. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4467. );
  4468. } else {
  4469. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4470. method = 'atan2';
  4471. }
  4472. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4473. warn( `TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4474. method = '/*' + method + '*/';
  4475. }
  4476. params.push( a.build( builder, inputType ) );
  4477. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4478. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4479. }
  4480. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4481. }
  4482. }
  4483. serialize( data ) {
  4484. super.serialize( data );
  4485. data.method = this.method;
  4486. }
  4487. deserialize( data ) {
  4488. super.deserialize( data );
  4489. this.method = data.method;
  4490. }
  4491. }
  4492. // 1 input
  4493. MathNode.ALL = 'all';
  4494. MathNode.ANY = 'any';
  4495. MathNode.RADIANS = 'radians';
  4496. MathNode.DEGREES = 'degrees';
  4497. MathNode.EXP = 'exp';
  4498. MathNode.EXP2 = 'exp2';
  4499. MathNode.LOG = 'log';
  4500. MathNode.LOG2 = 'log2';
  4501. MathNode.SQRT = 'sqrt';
  4502. MathNode.INVERSE_SQRT = 'inversesqrt';
  4503. MathNode.FLOOR = 'floor';
  4504. MathNode.CEIL = 'ceil';
  4505. MathNode.NORMALIZE = 'normalize';
  4506. MathNode.FRACT = 'fract';
  4507. MathNode.SIN = 'sin';
  4508. MathNode.COS = 'cos';
  4509. MathNode.TAN = 'tan';
  4510. MathNode.ASIN = 'asin';
  4511. MathNode.ACOS = 'acos';
  4512. MathNode.ATAN = 'atan';
  4513. MathNode.ABS = 'abs';
  4514. MathNode.SIGN = 'sign';
  4515. MathNode.LENGTH = 'length';
  4516. MathNode.NEGATE = 'negate';
  4517. MathNode.ONE_MINUS = 'oneMinus';
  4518. MathNode.DFDX = 'dFdx';
  4519. MathNode.DFDY = 'dFdy';
  4520. MathNode.ROUND = 'round';
  4521. MathNode.RECIPROCAL = 'reciprocal';
  4522. MathNode.TRUNC = 'trunc';
  4523. MathNode.FWIDTH = 'fwidth';
  4524. MathNode.TRANSPOSE = 'transpose';
  4525. MathNode.DETERMINANT = 'determinant';
  4526. MathNode.INVERSE = 'inverse';
  4527. // 2 inputs
  4528. MathNode.EQUALS = 'equals';
  4529. MathNode.MIN = 'min';
  4530. MathNode.MAX = 'max';
  4531. MathNode.STEP = 'step';
  4532. MathNode.REFLECT = 'reflect';
  4533. MathNode.DISTANCE = 'distance';
  4534. MathNode.DIFFERENCE = 'difference';
  4535. MathNode.DOT = 'dot';
  4536. MathNode.CROSS = 'cross';
  4537. MathNode.POW = 'pow';
  4538. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4539. // 3 inputs
  4540. MathNode.MIX = 'mix';
  4541. MathNode.CLAMP = 'clamp';
  4542. MathNode.REFRACT = 'refract';
  4543. MathNode.SMOOTHSTEP = 'smoothstep';
  4544. MathNode.FACEFORWARD = 'faceforward';
  4545. // 1 inputs
  4546. /**
  4547. * A small value used to handle floating-point precision errors.
  4548. *
  4549. * @tsl
  4550. * @type {Node<float>}
  4551. */
  4552. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4553. /**
  4554. * Represents infinity.
  4555. *
  4556. * @tsl
  4557. * @type {Node<float>}
  4558. */
  4559. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4560. /**
  4561. * Represents PI.
  4562. *
  4563. * @tsl
  4564. * @type {Node<float>}
  4565. */
  4566. const PI = /*@__PURE__*/ float( Math.PI );
  4567. /**
  4568. * Represents PI * 2. Please use the non-deprecated version `TWO_PI`.
  4569. *
  4570. * @tsl
  4571. * @deprecated
  4572. * @type {Node<float>}
  4573. */
  4574. const PI2 = /*@__PURE__*/ float( Math.PI * 2 ); // @deprecated r181
  4575. /**
  4576. * Represents PI * 2.
  4577. *
  4578. * @tsl
  4579. * @type {Node<float>}
  4580. */
  4581. const TWO_PI = /*@__PURE__*/ float( Math.PI * 2 );
  4582. /**
  4583. * Represents PI / 2.
  4584. *
  4585. * @tsl
  4586. * @type {Node<float>}
  4587. */
  4588. const HALF_PI = /*@__PURE__*/ float( Math.PI * 0.5 );
  4589. /**
  4590. * Returns `true` if all components of `x` are `true`.
  4591. *
  4592. * @tsl
  4593. * @function
  4594. * @param {Node | number} x - The parameter.
  4595. * @returns {Node<bool>}
  4596. */
  4597. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4598. /**
  4599. * Returns `true` if any components of `x` are `true`.
  4600. *
  4601. * @tsl
  4602. * @function
  4603. * @param {Node | number} x - The parameter.
  4604. * @returns {Node<bool>}
  4605. */
  4606. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4607. /**
  4608. * Converts a quantity in degrees to radians.
  4609. *
  4610. * @tsl
  4611. * @function
  4612. * @param {Node | number} x - The input in degrees.
  4613. * @returns {Node}
  4614. */
  4615. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4616. /**
  4617. * Convert a quantity in radians to degrees.
  4618. *
  4619. * @tsl
  4620. * @function
  4621. * @param {Node | number} x - The input in radians.
  4622. * @returns {Node}
  4623. */
  4624. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4625. /**
  4626. * Returns the natural exponentiation of the parameter.
  4627. *
  4628. * @tsl
  4629. * @function
  4630. * @param {Node | number} x - The parameter.
  4631. * @returns {Node}
  4632. */
  4633. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4634. /**
  4635. * Returns 2 raised to the power of the parameter.
  4636. *
  4637. * @tsl
  4638. * @function
  4639. * @param {Node | number} x - The parameter.
  4640. * @returns {Node}
  4641. */
  4642. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4643. /**
  4644. * Returns the natural logarithm of the parameter.
  4645. *
  4646. * @tsl
  4647. * @function
  4648. * @param {Node | number} x - The parameter.
  4649. * @returns {Node}
  4650. */
  4651. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4652. /**
  4653. * Returns the base 2 logarithm of the parameter.
  4654. *
  4655. * @tsl
  4656. * @function
  4657. * @param {Node | number} x - The parameter.
  4658. * @returns {Node}
  4659. */
  4660. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4661. /**
  4662. * Returns the square root of the parameter.
  4663. *
  4664. * @tsl
  4665. * @function
  4666. * @param {Node | number} x - The parameter.
  4667. * @returns {Node}
  4668. */
  4669. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4670. /**
  4671. * Returns the inverse of the square root of the parameter.
  4672. *
  4673. * @tsl
  4674. * @function
  4675. * @param {Node | number} x - The parameter.
  4676. * @returns {Node}
  4677. */
  4678. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4679. /**
  4680. * Finds the nearest integer less than or equal to the parameter.
  4681. *
  4682. * @tsl
  4683. * @function
  4684. * @param {Node | number} x - The parameter.
  4685. * @returns {Node}
  4686. */
  4687. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4688. /**
  4689. * Finds the nearest integer that is greater than or equal to the parameter.
  4690. *
  4691. * @tsl
  4692. * @function
  4693. * @param {Node | number} x - The parameter.
  4694. * @returns {Node}
  4695. */
  4696. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4697. /**
  4698. * Calculates the unit vector in the same direction as the original vector.
  4699. *
  4700. * @tsl
  4701. * @function
  4702. * @param {Node} x - The input vector.
  4703. * @returns {Node}
  4704. */
  4705. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4706. /**
  4707. * Computes the fractional part of the parameter.
  4708. *
  4709. * @tsl
  4710. * @function
  4711. * @param {Node | number} x - The parameter.
  4712. * @returns {Node}
  4713. */
  4714. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4715. /**
  4716. * Returns the sine of the parameter.
  4717. *
  4718. * @tsl
  4719. * @function
  4720. * @param {Node | number} x - The parameter.
  4721. * @returns {Node}
  4722. */
  4723. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4724. /**
  4725. * Returns the cosine of the parameter.
  4726. *
  4727. * @tsl
  4728. * @function
  4729. * @param {Node | number} x - The parameter.
  4730. * @returns {Node}
  4731. */
  4732. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4733. /**
  4734. * Returns the tangent of the parameter.
  4735. *
  4736. * @tsl
  4737. * @function
  4738. * @param {Node | number} x - The parameter.
  4739. * @returns {Node}
  4740. */
  4741. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4742. /**
  4743. * Returns the arcsine of the parameter.
  4744. *
  4745. * @tsl
  4746. * @function
  4747. * @param {Node | number} x - The parameter.
  4748. * @returns {Node}
  4749. */
  4750. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4751. /**
  4752. * Returns the arccosine of the parameter.
  4753. *
  4754. * @tsl
  4755. * @function
  4756. * @param {Node | number} x - The parameter.
  4757. * @returns {Node}
  4758. */
  4759. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4760. /**
  4761. * Returns the arc-tangent of the parameter.
  4762. * If two parameters are provided, the result is `atan2(y/x)`.
  4763. *
  4764. * @tsl
  4765. * @function
  4766. * @param {Node | number} y - The y parameter.
  4767. * @param {?(Node | number)} x - The x parameter.
  4768. * @returns {Node}
  4769. */
  4770. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4771. /**
  4772. * Returns the absolute value of the parameter.
  4773. *
  4774. * @tsl
  4775. * @function
  4776. * @param {Node | number} x - The parameter.
  4777. * @returns {Node}
  4778. */
  4779. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4780. /**
  4781. * Extracts the sign of the parameter.
  4782. *
  4783. * @tsl
  4784. * @function
  4785. * @param {Node | number} x - The parameter.
  4786. * @returns {Node}
  4787. */
  4788. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4789. /**
  4790. * Calculates the length of a vector.
  4791. *
  4792. * @tsl
  4793. * @function
  4794. * @param {Node} x - The parameter.
  4795. * @returns {Node<float>}
  4796. */
  4797. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4798. /**
  4799. * Negates the value of the parameter (-x).
  4800. *
  4801. * @tsl
  4802. * @function
  4803. * @param {Node | number} x - The parameter.
  4804. * @returns {Node}
  4805. */
  4806. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4807. /**
  4808. * Return `1` minus the parameter.
  4809. *
  4810. * @tsl
  4811. * @function
  4812. * @param {Node | number} x - The parameter.
  4813. * @returns {Node}
  4814. */
  4815. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4816. /**
  4817. * Returns the partial derivative of the parameter with respect to x.
  4818. *
  4819. * @tsl
  4820. * @function
  4821. * @param {Node | number} x - The parameter.
  4822. * @returns {Node}
  4823. */
  4824. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4825. /**
  4826. * Returns the partial derivative of the parameter with respect to y.
  4827. *
  4828. * @tsl
  4829. * @function
  4830. * @param {Node | number} x - The parameter.
  4831. * @returns {Node}
  4832. */
  4833. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4834. /**
  4835. * Rounds the parameter to the nearest integer.
  4836. *
  4837. * @tsl
  4838. * @function
  4839. * @param {Node | number} x - The parameter.
  4840. * @returns {Node}
  4841. */
  4842. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4843. /**
  4844. * Returns the reciprocal of the parameter `(1/x)`.
  4845. *
  4846. * @tsl
  4847. * @function
  4848. * @param {Node | number} x - The parameter.
  4849. * @returns {Node}
  4850. */
  4851. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4852. /**
  4853. * Truncates the parameter, removing the fractional part.
  4854. *
  4855. * @tsl
  4856. * @function
  4857. * @param {Node | number} x - The parameter.
  4858. * @returns {Node}
  4859. */
  4860. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4861. /**
  4862. * Returns the sum of the absolute derivatives in x and y.
  4863. *
  4864. * @tsl
  4865. * @function
  4866. * @param {Node | number} x - The parameter.
  4867. * @returns {Node}
  4868. */
  4869. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4870. /**
  4871. * Returns the transpose of a matrix.
  4872. *
  4873. * @tsl
  4874. * @function
  4875. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4876. * @returns {Node}
  4877. */
  4878. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4879. /**
  4880. * Returns the determinant of a matrix.
  4881. *
  4882. * @tsl
  4883. * @function
  4884. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4885. * @returns {Node<float>}
  4886. */
  4887. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4888. /**
  4889. * Returns the inverse of a matrix.
  4890. *
  4891. * @tsl
  4892. * @function
  4893. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4894. * @returns {Node<mat2|mat3|mat4>}
  4895. */
  4896. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4897. // 2 inputs
  4898. /**
  4899. * Returns `true` if `x` equals `y`.
  4900. *
  4901. * @tsl
  4902. * @function
  4903. * @param {Node | number} x - The first parameter.
  4904. * @param {Node | number} y - The second parameter.
  4905. * @deprecated since r175. Use {@link equal} instead.
  4906. * @returns {Node<bool>}
  4907. */
  4908. const equals = ( x, y ) => { // @deprecated, r172
  4909. warn( 'TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4910. return equal( x, y );
  4911. };
  4912. /**
  4913. * Returns the least of the given values.
  4914. *
  4915. * @tsl
  4916. * @function
  4917. * @param {...(Node | number)} values - The values to compare.
  4918. * @returns {Node}
  4919. */
  4920. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4921. /**
  4922. * Returns the greatest of the given values.
  4923. *
  4924. * @tsl
  4925. * @function
  4926. * @param {...(Node | number)} values - The values to compare.
  4927. * @returns {Node}
  4928. */
  4929. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4930. /**
  4931. * Generate a step function by comparing two values.
  4932. *
  4933. * @tsl
  4934. * @function
  4935. * @param {Node | number} x - The y parameter.
  4936. * @param {Node | number} y - The x parameter.
  4937. * @returns {Node}
  4938. */
  4939. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4940. /**
  4941. * Calculates the reflection direction for an incident vector.
  4942. *
  4943. * @tsl
  4944. * @function
  4945. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4946. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4947. * @returns {Node<vec2|vec3|vec4>}
  4948. */
  4949. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4950. /**
  4951. * Calculates the distance between two points.
  4952. *
  4953. * @tsl
  4954. * @function
  4955. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4956. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4957. * @returns {Node<float>}
  4958. */
  4959. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4960. /**
  4961. * Calculates the absolute difference between two values.
  4962. *
  4963. * @tsl
  4964. * @function
  4965. * @param {Node | number} x - The first parameter.
  4966. * @param {Node | number} y - The second parameter.
  4967. * @returns {Node}
  4968. */
  4969. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4970. /**
  4971. * Calculates the dot product of two vectors.
  4972. *
  4973. * @tsl
  4974. * @function
  4975. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4976. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4977. * @returns {Node<float>}
  4978. */
  4979. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4980. /**
  4981. * Calculates the cross product of two vectors.
  4982. *
  4983. * @tsl
  4984. * @function
  4985. * @param {Node<vec2|vec3>} x - The first vector.
  4986. * @param {Node<vec2|vec3>} y - The second vector.
  4987. * @returns {Node<float|vec3>}
  4988. */
  4989. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4990. /**
  4991. * Return the value of the first parameter raised to the power of the second one.
  4992. *
  4993. * @tsl
  4994. * @function
  4995. * @param {Node | number} x - The first parameter.
  4996. * @param {Node | number} y - The second parameter.
  4997. * @returns {Node}
  4998. */
  4999. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  5000. /**
  5001. * Returns the square of the parameter.
  5002. *
  5003. * @tsl
  5004. * @function
  5005. * @param {Node | number} x - The first parameter.
  5006. * @returns {Node}
  5007. */
  5008. const pow2 = ( x ) => mul( x, x );
  5009. /**
  5010. * Returns the cube of the parameter.
  5011. *
  5012. * @tsl
  5013. * @function
  5014. * @param {Node | number} x - The first parameter.
  5015. * @returns {Node}
  5016. */
  5017. const pow3 = ( x ) => mul( x, x, x );
  5018. /**
  5019. * Returns the fourth power of the parameter.
  5020. *
  5021. * @tsl
  5022. * @function
  5023. * @param {Node | number} x - The first parameter.
  5024. * @returns {Node}
  5025. */
  5026. const pow4 = ( x ) => mul( x, x, x, x );
  5027. /**
  5028. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5029. *
  5030. * @tsl
  5031. * @function
  5032. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5033. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5034. * @returns {Node}
  5035. */
  5036. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5037. /**
  5038. * Returns the cube root of a number.
  5039. *
  5040. * @tsl
  5041. * @function
  5042. * @param {Node | number} a - The first parameter.
  5043. * @returns {Node}
  5044. */
  5045. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5046. /**
  5047. * Calculate the squared length of a vector.
  5048. *
  5049. * @tsl
  5050. * @function
  5051. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5052. * @returns {Node<float>}
  5053. */
  5054. const lengthSq = ( a ) => dot( a, a );
  5055. /**
  5056. * Linearly interpolates between two values.
  5057. *
  5058. * @tsl
  5059. * @function
  5060. * @param {Node | number} a - The first parameter.
  5061. * @param {Node | number} b - The second parameter.
  5062. * @param {Node | number} t - The interpolation value.
  5063. * @returns {Node}
  5064. */
  5065. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5066. /**
  5067. * Constrains a value to lie between two further values.
  5068. *
  5069. * @tsl
  5070. * @function
  5071. * @param {Node | number} value - The value to constrain.
  5072. * @param {Node | number} [low=0] - The lower bound.
  5073. * @param {Node | number} [high=1] - The upper bound.
  5074. * @returns {Node}
  5075. */
  5076. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5077. /**
  5078. * Constrains a value between `0` and `1`.
  5079. *
  5080. * @tsl
  5081. * @function
  5082. * @param {Node | number} value - The value to constrain.
  5083. * @returns {Node}
  5084. */
  5085. const saturate = ( value ) => clamp( value );
  5086. /**
  5087. * Calculates the refraction direction for an incident vector.
  5088. *
  5089. * @tsl
  5090. * @function
  5091. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5092. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5093. * @param {Node<float>} eta - The ratio of indices of refraction.
  5094. * @returns {Node<vec2|vec3|vec4>}
  5095. */
  5096. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5097. /**
  5098. * Performs a Hermite interpolation between two values.
  5099. *
  5100. * @tsl
  5101. * @function
  5102. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5103. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5104. * @param {Node | number} x - The source value for interpolation.
  5105. * @returns {Node}
  5106. */
  5107. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5108. /**
  5109. * Returns a vector pointing in the same direction as another.
  5110. *
  5111. * @tsl
  5112. * @function
  5113. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5114. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5115. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5116. * @returns {Node<vec2|vec3|vec4>}
  5117. */
  5118. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5119. /**
  5120. * Returns a random value for the given uv.
  5121. *
  5122. * @tsl
  5123. * @function
  5124. * @param {Node<vec2>} uv - The uv node.
  5125. * @returns {Node<float>}
  5126. */
  5127. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5128. const a = 12.9898, b = 78.233, c = 43758.5453;
  5129. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5130. return fract( sin( sn ).mul( c ) );
  5131. } );
  5132. /**
  5133. * Alias for `mix()` with a different parameter order.
  5134. *
  5135. * @tsl
  5136. * @function
  5137. * @param {Node | number} t - The interpolation value.
  5138. * @param {Node | number} e1 - The first parameter.
  5139. * @param {Node | number} e2 - The second parameter.
  5140. * @returns {Node}
  5141. */
  5142. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5143. /**
  5144. * Alias for `smoothstep()` with a different parameter order.
  5145. *
  5146. * @tsl
  5147. * @function
  5148. * @param {Node | number} x - The source value for interpolation.
  5149. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5150. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5151. * @returns {Node}
  5152. */
  5153. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5154. /**
  5155. * Alias for `step()` with a different parameter order.
  5156. *
  5157. * @tsl
  5158. * @function
  5159. * @param {Node | number} x - The source value for interpolation.
  5160. * @param {Node | number} edge - The edge value.
  5161. * @returns {Node}
  5162. */
  5163. const stepElement = ( x, edge ) => step( edge, x );
  5164. /**
  5165. * Returns the arc-tangent of the quotient of its parameters.
  5166. *
  5167. * @tsl
  5168. * @function
  5169. * @deprecated since r172. Use {@link atan} instead.
  5170. *
  5171. * @param {Node | number} y - The y parameter.
  5172. * @param {Node | number} x - The x parameter.
  5173. * @returns {Node}
  5174. */
  5175. const atan2 = ( y, x ) => { // @deprecated, r172
  5176. warn( 'TSL: "atan2" is overloaded. Use "atan" instead.' );
  5177. return atan( y, x );
  5178. };
  5179. // GLSL alias function
  5180. const faceforward = faceForward;
  5181. const inversesqrt = inverseSqrt;
  5182. // Method chaining
  5183. addMethodChaining( 'all', all );
  5184. addMethodChaining( 'any', any );
  5185. addMethodChaining( 'equals', equals );
  5186. addMethodChaining( 'radians', radians );
  5187. addMethodChaining( 'degrees', degrees );
  5188. addMethodChaining( 'exp', exp );
  5189. addMethodChaining( 'exp2', exp2 );
  5190. addMethodChaining( 'log', log );
  5191. addMethodChaining( 'log2', log2 );
  5192. addMethodChaining( 'sqrt', sqrt );
  5193. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5194. addMethodChaining( 'floor', floor );
  5195. addMethodChaining( 'ceil', ceil );
  5196. addMethodChaining( 'normalize', normalize );
  5197. addMethodChaining( 'fract', fract );
  5198. addMethodChaining( 'sin', sin );
  5199. addMethodChaining( 'cos', cos );
  5200. addMethodChaining( 'tan', tan );
  5201. addMethodChaining( 'asin', asin );
  5202. addMethodChaining( 'acos', acos );
  5203. addMethodChaining( 'atan', atan );
  5204. addMethodChaining( 'abs', abs );
  5205. addMethodChaining( 'sign', sign );
  5206. addMethodChaining( 'length', length );
  5207. addMethodChaining( 'lengthSq', lengthSq );
  5208. addMethodChaining( 'negate', negate );
  5209. addMethodChaining( 'oneMinus', oneMinus );
  5210. addMethodChaining( 'dFdx', dFdx );
  5211. addMethodChaining( 'dFdy', dFdy );
  5212. addMethodChaining( 'round', round );
  5213. addMethodChaining( 'reciprocal', reciprocal );
  5214. addMethodChaining( 'trunc', trunc );
  5215. addMethodChaining( 'fwidth', fwidth );
  5216. addMethodChaining( 'atan2', atan2 );
  5217. addMethodChaining( 'min', min$1 );
  5218. addMethodChaining( 'max', max$1 );
  5219. addMethodChaining( 'step', stepElement );
  5220. addMethodChaining( 'reflect', reflect );
  5221. addMethodChaining( 'distance', distance );
  5222. addMethodChaining( 'dot', dot );
  5223. addMethodChaining( 'cross', cross );
  5224. addMethodChaining( 'pow', pow );
  5225. addMethodChaining( 'pow2', pow2 );
  5226. addMethodChaining( 'pow3', pow3 );
  5227. addMethodChaining( 'pow4', pow4 );
  5228. addMethodChaining( 'transformDirection', transformDirection );
  5229. addMethodChaining( 'mix', mixElement );
  5230. addMethodChaining( 'clamp', clamp );
  5231. addMethodChaining( 'refract', refract );
  5232. addMethodChaining( 'smoothstep', smoothstepElement );
  5233. addMethodChaining( 'faceForward', faceForward );
  5234. addMethodChaining( 'difference', difference );
  5235. addMethodChaining( 'saturate', saturate );
  5236. addMethodChaining( 'cbrt', cbrt );
  5237. addMethodChaining( 'transpose', transpose );
  5238. addMethodChaining( 'determinant', determinant );
  5239. addMethodChaining( 'inverse', inverse );
  5240. addMethodChaining( 'rand', rand );
  5241. /**
  5242. * Represents a logical `if/else` statement. Can be used as an alternative
  5243. * to the `If()`/`Else()` syntax.
  5244. *
  5245. * The corresponding TSL `select()` looks like so:
  5246. * ```js
  5247. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5248. * ```
  5249. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5250. * determine the outcome of the entire statement.
  5251. *
  5252. * @augments Node
  5253. */
  5254. class ConditionalNode extends Node {
  5255. static get type() {
  5256. return 'ConditionalNode';
  5257. }
  5258. /**
  5259. * Constructs a new conditional node.
  5260. *
  5261. * @param {Node} condNode - The node that defines the condition.
  5262. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5263. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5264. */
  5265. constructor( condNode, ifNode, elseNode = null ) {
  5266. super();
  5267. /**
  5268. * The node that defines the condition.
  5269. *
  5270. * @type {Node}
  5271. */
  5272. this.condNode = condNode;
  5273. /**
  5274. * The node that is evaluate when the condition ends up `true`.
  5275. *
  5276. * @type {Node}
  5277. */
  5278. this.ifNode = ifNode;
  5279. /**
  5280. * The node that is evaluate when the condition ends up `false`.
  5281. *
  5282. * @type {?Node}
  5283. * @default null
  5284. */
  5285. this.elseNode = elseNode;
  5286. }
  5287. /**
  5288. * This method is overwritten since the node type is inferred from the if/else
  5289. * nodes.
  5290. *
  5291. * @param {NodeBuilder} builder - The current node builder.
  5292. * @return {string} The node type.
  5293. */
  5294. getNodeType( builder ) {
  5295. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5296. if ( ifNode === undefined ) {
  5297. // fallback setup
  5298. builder.flowBuildStage( this, 'setup' );
  5299. return this.getNodeType( builder );
  5300. }
  5301. const ifType = ifNode.getNodeType( builder );
  5302. if ( elseNode !== null ) {
  5303. const elseType = elseNode.getNodeType( builder );
  5304. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5305. return elseType;
  5306. }
  5307. }
  5308. return ifType;
  5309. }
  5310. setup( builder ) {
  5311. const condNode = this.condNode.cache();
  5312. const ifNode = this.ifNode.cache();
  5313. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  5314. //
  5315. const currentNodeBlock = builder.context.nodeBlock;
  5316. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5317. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5318. //
  5319. const isUniformFlow = builder.context.uniformFlow;
  5320. const properties = builder.getNodeProperties( this );
  5321. properties.condNode = condNode;
  5322. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5323. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5324. }
  5325. generate( builder, output ) {
  5326. const type = this.getNodeType( builder );
  5327. const nodeData = builder.getDataFromNode( this );
  5328. if ( nodeData.nodeProperty !== undefined ) {
  5329. return nodeData.nodeProperty;
  5330. }
  5331. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5332. const functionNode = builder.currentFunctionNode;
  5333. const needsOutput = output !== 'void';
  5334. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5335. nodeData.nodeProperty = nodeProperty;
  5336. const nodeSnippet = condNode.build( builder, 'bool' );
  5337. const isUniformFlow = builder.context.uniformFlow;
  5338. if ( isUniformFlow && elseNode !== null ) {
  5339. const ifSnippet = ifNode.build( builder, type );
  5340. const elseSnippet = elseNode.build( builder, type );
  5341. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5342. // TODO: If node property already exists return something else
  5343. return builder.format( mathSnippet, type, output );
  5344. }
  5345. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5346. let ifSnippet = ifNode.build( builder, type );
  5347. if ( ifSnippet ) {
  5348. if ( needsOutput ) {
  5349. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5350. } else {
  5351. ifSnippet = 'return ' + ifSnippet + ';';
  5352. if ( functionNode === null ) {
  5353. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5354. ifSnippet = '// ' + ifSnippet;
  5355. }
  5356. }
  5357. }
  5358. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5359. if ( elseNode !== null ) {
  5360. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5361. let elseSnippet = elseNode.build( builder, type );
  5362. if ( elseSnippet ) {
  5363. if ( needsOutput ) {
  5364. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5365. } else {
  5366. elseSnippet = 'return ' + elseSnippet + ';';
  5367. if ( functionNode === null ) {
  5368. warn( 'TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5369. elseSnippet = '// ' + elseSnippet;
  5370. }
  5371. }
  5372. }
  5373. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5374. } else {
  5375. builder.addFlowCode( '\n\n' );
  5376. }
  5377. return builder.format( nodeProperty, type, output );
  5378. }
  5379. }
  5380. /**
  5381. * TSL function for creating a conditional node.
  5382. *
  5383. * @tsl
  5384. * @function
  5385. * @param {Node} condNode - The node that defines the condition.
  5386. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5387. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5388. * @returns {ConditionalNode}
  5389. */
  5390. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5391. addMethodChaining( 'select', select );
  5392. /**
  5393. * This node can be used as a context management component for another node.
  5394. * {@link NodeBuilder} performs its node building process in a specific context and
  5395. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5396. *
  5397. * ```js
  5398. *node.context( { getUV: () => customCoord } );
  5399. *```
  5400. * @augments Node
  5401. */
  5402. class ContextNode extends Node {
  5403. static get type() {
  5404. return 'ContextNode';
  5405. }
  5406. /**
  5407. * Constructs a new context node.
  5408. *
  5409. * @param {Node} node - The node whose context should be modified.
  5410. * @param {Object} [value={}] - The modified context data.
  5411. */
  5412. constructor( node, value = {} ) {
  5413. super();
  5414. /**
  5415. * This flag can be used for type testing.
  5416. *
  5417. * @type {boolean}
  5418. * @readonly
  5419. * @default true
  5420. */
  5421. this.isContextNode = true;
  5422. /**
  5423. * The node whose context should be modified.
  5424. *
  5425. * @type {Node}
  5426. */
  5427. this.node = node;
  5428. /**
  5429. * The modified context data.
  5430. *
  5431. * @type {Object}
  5432. * @default {}
  5433. */
  5434. this.value = value;
  5435. }
  5436. /**
  5437. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5438. *
  5439. * @return {Node} A reference to {@link ContextNode#node}.
  5440. */
  5441. getScope() {
  5442. return this.node.getScope();
  5443. }
  5444. /**
  5445. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5446. *
  5447. * @param {NodeBuilder} builder - The current node builder.
  5448. * @return {string} The node type.
  5449. */
  5450. getNodeType( builder ) {
  5451. return this.node.getNodeType( builder );
  5452. }
  5453. /**
  5454. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5455. *
  5456. * @param {NodeBuilder} builder - The current node builder.
  5457. * @param {string} name - The member name.
  5458. * @returns {string} The member type.
  5459. */
  5460. getMemberType( builder, name ) {
  5461. return this.node.getMemberType( builder, name );
  5462. }
  5463. analyze( builder ) {
  5464. const previousContext = builder.getContext();
  5465. builder.setContext( { ...builder.context, ...this.value } );
  5466. this.node.build( builder );
  5467. builder.setContext( previousContext );
  5468. }
  5469. setup( builder ) {
  5470. const previousContext = builder.getContext();
  5471. builder.setContext( { ...builder.context, ...this.value } );
  5472. this.node.build( builder );
  5473. builder.setContext( previousContext );
  5474. }
  5475. generate( builder, output ) {
  5476. const previousContext = builder.getContext();
  5477. builder.setContext( { ...builder.context, ...this.value } );
  5478. const snippet = this.node.build( builder, output );
  5479. builder.setContext( previousContext );
  5480. return snippet;
  5481. }
  5482. }
  5483. /**
  5484. * TSL function for creating a context node.
  5485. *
  5486. * @tsl
  5487. * @function
  5488. * @param {Node} node - The node whose context should be modified.
  5489. * @param {Object} [value={}] - The modified context data.
  5490. * @returns {ContextNode}
  5491. */
  5492. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5493. /**
  5494. * TSL function for defining a uniformFlow context value for a given node.
  5495. *
  5496. * @tsl
  5497. * @function
  5498. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5499. * @returns {ContextNode}
  5500. */
  5501. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5502. /**
  5503. * TSL function for defining a name for the context value for a given node.
  5504. *
  5505. * @tsl
  5506. * @function
  5507. * @param {Node} node - The node whose context should be modified.
  5508. * @param {string} name - The name to set.
  5509. * @returns {ContextNode}
  5510. */
  5511. const setName = ( node, name ) => context( node, { nodeName: name } );
  5512. /**
  5513. * TSL function for defining a label context value for a given node.
  5514. *
  5515. * @tsl
  5516. * @function
  5517. * @deprecated
  5518. * @param {Node} node - The node whose context should be modified.
  5519. * @param {string} name - The name/label to set.
  5520. * @returns {ContextNode}
  5521. */
  5522. function label( node, name ) {
  5523. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5524. return setName( node, name );
  5525. }
  5526. addMethodChaining( 'context', context );
  5527. addMethodChaining( 'label', label );
  5528. addMethodChaining( 'uniformFlow', uniformFlow );
  5529. addMethodChaining( 'setName', setName );
  5530. /**
  5531. * Class for representing shader variables as nodes. Variables are created from
  5532. * existing nodes like the following:
  5533. *
  5534. * ```js
  5535. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5536. * ```
  5537. *
  5538. * @augments Node
  5539. */
  5540. class VarNode extends Node {
  5541. static get type() {
  5542. return 'VarNode';
  5543. }
  5544. /**
  5545. * Constructs a new variable node.
  5546. *
  5547. * @param {Node} node - The node for which a variable should be created.
  5548. * @param {?string} [name=null] - The name of the variable in the shader.
  5549. * @param {boolean} [readOnly=false] - The read-only flag.
  5550. */
  5551. constructor( node, name = null, readOnly = false ) {
  5552. super();
  5553. /**
  5554. * The node for which a variable should be created.
  5555. *
  5556. * @type {Node}
  5557. */
  5558. this.node = node;
  5559. /**
  5560. * The name of the variable in the shader. If no name is defined,
  5561. * the node system auto-generates one.
  5562. *
  5563. * @type {?string}
  5564. * @default null
  5565. */
  5566. this.name = name;
  5567. /**
  5568. * `VarNode` sets this property to `true` by default.
  5569. *
  5570. * @type {boolean}
  5571. * @default true
  5572. */
  5573. this.global = true;
  5574. /**
  5575. * This flag can be used for type testing.
  5576. *
  5577. * @type {boolean}
  5578. * @readonly
  5579. * @default true
  5580. */
  5581. this.isVarNode = true;
  5582. /**
  5583. *
  5584. * The read-only flag.
  5585. *
  5586. * @type {boolean}
  5587. * @default false
  5588. */
  5589. this.readOnly = readOnly;
  5590. /**
  5591. *
  5592. * Add this flag to the node system to indicate that this node require parents.
  5593. *
  5594. * @type {boolean}
  5595. * @default true
  5596. */
  5597. this.parents = true;
  5598. /**
  5599. * This flag is used to indicate that this node is used for intent.
  5600. *
  5601. * @type {boolean}
  5602. * @default false
  5603. */
  5604. this.intent = false;
  5605. }
  5606. /**
  5607. * Sets the intent flag for this node.
  5608. *
  5609. * This flag is used to indicate that this node is used for intent
  5610. * and should not be built directly. Instead, it is used to indicate that
  5611. * the node should be treated as a variable intent.
  5612. *
  5613. * It's useful for assigning variables without needing creating a new variable node.
  5614. *
  5615. * @param {boolean} value - The value to set for the intent flag.
  5616. * @returns {VarNode} This node.
  5617. */
  5618. setIntent( value ) {
  5619. this.intent = value;
  5620. return this;
  5621. }
  5622. /**
  5623. * Returns the intent flag of this node.
  5624. *
  5625. * @return {boolean} The intent flag.
  5626. */
  5627. getIntent() {
  5628. return this.intent;
  5629. }
  5630. getMemberType( builder, name ) {
  5631. return this.node.getMemberType( builder, name );
  5632. }
  5633. getElementType( builder ) {
  5634. return this.node.getElementType( builder );
  5635. }
  5636. getNodeType( builder ) {
  5637. return this.node.getNodeType( builder );
  5638. }
  5639. getArrayCount( builder ) {
  5640. return this.node.getArrayCount( builder );
  5641. }
  5642. build( ...params ) {
  5643. if ( this.intent === true ) {
  5644. const builder = params[ 0 ];
  5645. const properties = builder.getNodeProperties( this );
  5646. if ( properties.assign !== true ) {
  5647. return this.node.build( ...params );
  5648. }
  5649. }
  5650. return super.build( ...params );
  5651. }
  5652. generate( builder ) {
  5653. const { node, name, readOnly } = this;
  5654. const { renderer } = builder;
  5655. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5656. let isDeterministic = false;
  5657. let shouldTreatAsReadOnly = false;
  5658. if ( readOnly ) {
  5659. isDeterministic = builder.isDeterministic( node );
  5660. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5661. }
  5662. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5663. const snippet = node.build( builder, vectorType );
  5664. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5665. const propertyName = builder.getPropertyName( nodeVar );
  5666. let declarationPrefix = propertyName;
  5667. if ( shouldTreatAsReadOnly ) {
  5668. if ( isWebGPUBackend ) {
  5669. declarationPrefix = isDeterministic
  5670. ? `const ${ propertyName }`
  5671. : `let ${ propertyName }`;
  5672. } else {
  5673. const count = node.getArrayCount( builder );
  5674. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5675. }
  5676. }
  5677. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5678. return propertyName;
  5679. }
  5680. }
  5681. /**
  5682. * TSL function for creating a var node.
  5683. *
  5684. * @tsl
  5685. * @function
  5686. * @param {Node} node - The node for which a variable should be created.
  5687. * @param {?string} name - The name of the variable in the shader.
  5688. * @returns {VarNode}
  5689. */
  5690. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5691. /**
  5692. * TSL function for creating a var node.
  5693. *
  5694. * @tsl
  5695. * @function
  5696. * @param {Node} node - The node for which a variable should be created.
  5697. * @param {?string} name - The name of the variable in the shader.
  5698. * @returns {VarNode}
  5699. */
  5700. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5701. /**
  5702. * TSL function for creating a const node.
  5703. *
  5704. * @tsl
  5705. * @function
  5706. * @param {Node} node - The node for which a constant should be created.
  5707. * @param {?string} name - The name of the constant in the shader.
  5708. * @returns {VarNode}
  5709. */
  5710. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5711. //
  5712. //
  5713. /**
  5714. * TSL function for creating a var intent node.
  5715. *
  5716. * @tsl
  5717. * @function
  5718. * @param {Node} node - The node for which a variable should be created.
  5719. * @param {?string} name - The name of the variable in the shader.
  5720. * @returns {VarNode}
  5721. */
  5722. const VarIntent = ( node ) => {
  5723. if ( getCurrentStack() === null ) {
  5724. return node;
  5725. }
  5726. return createVar( node ).setIntent( true ).toStack();
  5727. };
  5728. // Method chaining
  5729. addMethodChaining( 'toVar', Var );
  5730. addMethodChaining( 'toConst', Const );
  5731. addMethodChaining( 'toVarIntent', VarIntent );
  5732. /**
  5733. * This node is used to build a sub-build in the node system.
  5734. *
  5735. * @augments Node
  5736. * @param {Node} node - The node to be built in the sub-build.
  5737. * @param {string} name - The name of the sub-build.
  5738. * @param {?string} [nodeType=null] - The type of the node, if known.
  5739. */
  5740. class SubBuildNode extends Node {
  5741. static get type() {
  5742. return 'SubBuild';
  5743. }
  5744. constructor( node, name, nodeType = null ) {
  5745. super( nodeType );
  5746. /**
  5747. * The node to be built in the sub-build.
  5748. *
  5749. * @type {Node}
  5750. */
  5751. this.node = node;
  5752. /**
  5753. * The name of the sub-build.
  5754. *
  5755. * @type {string}
  5756. */
  5757. this.name = name;
  5758. /**
  5759. * This flag can be used for type testing.
  5760. *
  5761. * @type {boolean}
  5762. * @readonly
  5763. * @default true
  5764. */
  5765. this.isSubBuildNode = true;
  5766. }
  5767. getNodeType( builder ) {
  5768. if ( this.nodeType !== null ) return this.nodeType;
  5769. builder.addSubBuild( this.name );
  5770. const nodeType = this.node.getNodeType( builder );
  5771. builder.removeSubBuild();
  5772. return nodeType;
  5773. }
  5774. build( builder, ...params ) {
  5775. builder.addSubBuild( this.name );
  5776. const data = this.node.build( builder, ...params );
  5777. builder.removeSubBuild();
  5778. return data;
  5779. }
  5780. }
  5781. /**
  5782. * Creates a new sub-build node.
  5783. *
  5784. * @tsl
  5785. * @function
  5786. * @param {Node} node - The node to be built in the sub-build.
  5787. * @param {string} name - The name of the sub-build.
  5788. * @param {?string} [type=null] - The type of the node, if known.
  5789. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5790. */
  5791. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5792. /**
  5793. * Class for representing shader varyings as nodes. Varyings are create from
  5794. * existing nodes like the following:
  5795. *
  5796. * ```js
  5797. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5798. * ```
  5799. *
  5800. * @augments Node
  5801. */
  5802. class VaryingNode extends Node {
  5803. static get type() {
  5804. return 'VaryingNode';
  5805. }
  5806. /**
  5807. * Constructs a new varying node.
  5808. *
  5809. * @param {Node} node - The node for which a varying should be created.
  5810. * @param {?string} name - The name of the varying in the shader.
  5811. */
  5812. constructor( node, name = null ) {
  5813. super();
  5814. /**
  5815. * The node for which a varying should be created.
  5816. *
  5817. * @type {Node}
  5818. */
  5819. this.node = node;
  5820. /**
  5821. * The name of the varying in the shader. If no name is defined,
  5822. * the node system auto-generates one.
  5823. *
  5824. * @type {?string}
  5825. * @default null
  5826. */
  5827. this.name = name;
  5828. /**
  5829. * This flag can be used for type testing.
  5830. *
  5831. * @type {boolean}
  5832. * @readonly
  5833. * @default true
  5834. */
  5835. this.isVaryingNode = true;
  5836. /**
  5837. * The interpolation type of the varying data.
  5838. *
  5839. * @type {?string}
  5840. * @default null
  5841. */
  5842. this.interpolationType = null;
  5843. /**
  5844. * The interpolation sampling type of varying data.
  5845. *
  5846. * @type {?string}
  5847. * @default null
  5848. */
  5849. this.interpolationSampling = null;
  5850. /**
  5851. * This flag is used for global cache.
  5852. *
  5853. * @type {boolean}
  5854. * @default true
  5855. */
  5856. this.global = true;
  5857. }
  5858. /**
  5859. * Defines the interpolation type of the varying.
  5860. *
  5861. * @param {string} type - The interpolation type.
  5862. * @param {?string} sampling - The interpolation sampling type
  5863. * @return {VaryingNode} A reference to this node.
  5864. */
  5865. setInterpolation( type, sampling = null ) {
  5866. this.interpolationType = type;
  5867. this.interpolationSampling = sampling;
  5868. return this;
  5869. }
  5870. getHash( builder ) {
  5871. return this.name || super.getHash( builder );
  5872. }
  5873. getNodeType( builder ) {
  5874. // VaryingNode is auto type
  5875. return this.node.getNodeType( builder );
  5876. }
  5877. /**
  5878. * This method performs the setup of a varying node with the current node builder.
  5879. *
  5880. * @param {NodeBuilder} builder - The current node builder.
  5881. * @return {NodeVarying} The node varying from the node builder.
  5882. */
  5883. setupVarying( builder ) {
  5884. const properties = builder.getNodeProperties( this );
  5885. let varying = properties.varying;
  5886. if ( varying === undefined ) {
  5887. const name = this.name;
  5888. const type = this.getNodeType( builder );
  5889. const interpolationType = this.interpolationType;
  5890. const interpolationSampling = this.interpolationSampling;
  5891. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5892. properties.node = subBuild( this.node, 'VERTEX' );
  5893. }
  5894. // this property can be used to check if the varying can be optimized for a variable
  5895. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5896. return varying;
  5897. }
  5898. setup( builder ) {
  5899. this.setupVarying( builder );
  5900. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5901. }
  5902. analyze( builder ) {
  5903. this.setupVarying( builder );
  5904. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5905. }
  5906. generate( builder ) {
  5907. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5908. const properties = builder.getNodeProperties( this );
  5909. const varying = this.setupVarying( builder );
  5910. if ( properties[ propertyKey ] === undefined ) {
  5911. const type = this.getNodeType( builder );
  5912. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5913. // force node run in vertex stage
  5914. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5915. properties[ propertyKey ] = propertyName;
  5916. }
  5917. return builder.getPropertyName( varying );
  5918. }
  5919. }
  5920. /**
  5921. * TSL function for creating a varying node.
  5922. *
  5923. * @tsl
  5924. * @function
  5925. * @param {Node} node - The node for which a varying should be created.
  5926. * @param {?string} name - The name of the varying in the shader.
  5927. * @returns {VaryingNode}
  5928. */
  5929. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5930. /**
  5931. * Computes a node in the vertex stage.
  5932. *
  5933. * @tsl
  5934. * @function
  5935. * @param {Node} node - The node which should be executed in the vertex stage.
  5936. * @returns {VaryingNode}
  5937. */
  5938. const vertexStage = ( node ) => varying( node );
  5939. addMethodChaining( 'toVarying', varying );
  5940. addMethodChaining( 'toVertexStage', vertexStage );
  5941. // Deprecated
  5942. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5943. warn( 'TSL: .varying() has been renamed to .toVarying().' );
  5944. return varying( ...params );
  5945. } );
  5946. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5947. warn( 'TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5948. return varying( ...params );
  5949. } );
  5950. /**
  5951. * Converts the given color value from sRGB to linear-sRGB color space.
  5952. *
  5953. * @tsl
  5954. * @function
  5955. * @param {Node<vec3>} color - The sRGB color.
  5956. * @return {Node<vec3>} The linear-sRGB color.
  5957. */
  5958. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5959. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5960. const b = color.mul( 0.0773993808 );
  5961. const factor = color.lessThanEqual( 0.04045 );
  5962. const rgbResult = mix( a, b, factor );
  5963. return rgbResult;
  5964. } ).setLayout( {
  5965. name: 'sRGBTransferEOTF',
  5966. type: 'vec3',
  5967. inputs: [
  5968. { name: 'color', type: 'vec3' }
  5969. ]
  5970. } );
  5971. /**
  5972. * Converts the given color value from linear-sRGB to sRGB color space.
  5973. *
  5974. * @tsl
  5975. * @function
  5976. * @param {Node<vec3>} color - The linear-sRGB color.
  5977. * @return {Node<vec3>} The sRGB color.
  5978. */
  5979. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5980. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5981. const b = color.mul( 12.92 );
  5982. const factor = color.lessThanEqual( 0.0031308 );
  5983. const rgbResult = mix( a, b, factor );
  5984. return rgbResult;
  5985. } ).setLayout( {
  5986. name: 'sRGBTransferOETF',
  5987. type: 'vec3',
  5988. inputs: [
  5989. { name: 'color', type: 'vec3' }
  5990. ]
  5991. } );
  5992. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5993. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5994. /**
  5995. * This node represents a color space conversion. Meaning it converts
  5996. * a color value from a source to a target color space.
  5997. *
  5998. * @augments TempNode
  5999. */
  6000. class ColorSpaceNode extends TempNode {
  6001. static get type() {
  6002. return 'ColorSpaceNode';
  6003. }
  6004. /**
  6005. * Constructs a new color space node.
  6006. *
  6007. * @param {Node} colorNode - Represents the color to convert.
  6008. * @param {string} source - The source color space.
  6009. * @param {string} target - The target color space.
  6010. */
  6011. constructor( colorNode, source, target ) {
  6012. super( 'vec4' );
  6013. /**
  6014. * Represents the color to convert.
  6015. *
  6016. * @type {Node}
  6017. */
  6018. this.colorNode = colorNode;
  6019. /**
  6020. * The source color space.
  6021. *
  6022. * @type {string}
  6023. */
  6024. this.source = source;
  6025. /**
  6026. * The target color space.
  6027. *
  6028. * @type {string}
  6029. */
  6030. this.target = target;
  6031. }
  6032. /**
  6033. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6034. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6035. * color management and renderer.
  6036. *
  6037. * @param {NodeBuilder} builder - The current node builder.
  6038. * @param {string} colorSpace - The color space to resolve.
  6039. * @return {string} The resolved color space.
  6040. */
  6041. resolveColorSpace( builder, colorSpace ) {
  6042. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6043. return ColorManagement.workingColorSpace;
  6044. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6045. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6046. }
  6047. return colorSpace;
  6048. }
  6049. setup( builder ) {
  6050. const { colorNode } = this;
  6051. const source = this.resolveColorSpace( builder, this.source );
  6052. const target = this.resolveColorSpace( builder, this.target );
  6053. let outputNode = colorNode;
  6054. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6055. return outputNode;
  6056. }
  6057. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6058. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6059. }
  6060. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6061. outputNode = vec4(
  6062. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6063. outputNode.a
  6064. );
  6065. }
  6066. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6067. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6068. }
  6069. return outputNode;
  6070. }
  6071. }
  6072. /**
  6073. * TSL function for converting a given color node from the current working color space to the given color space.
  6074. *
  6075. * @tsl
  6076. * @function
  6077. * @param {Node} node - Represents the node to convert.
  6078. * @param {string} targetColorSpace - The target color space.
  6079. * @returns {ColorSpaceNode}
  6080. */
  6081. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6082. /**
  6083. * TSL function for converting a given color node from the given color space to the current working color space.
  6084. *
  6085. * @tsl
  6086. * @function
  6087. * @param {Node} node - Represents the node to convert.
  6088. * @param {string} sourceColorSpace - The source color space.
  6089. * @returns {ColorSpaceNode}
  6090. */
  6091. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6092. /**
  6093. * TSL function for converting a given color node from one color space to another one.
  6094. *
  6095. * @tsl
  6096. * @function
  6097. * @param {Node} node - Represents the node to convert.
  6098. * @param {string} sourceColorSpace - The source color space.
  6099. * @param {string} targetColorSpace - The target color space.
  6100. * @returns {ColorSpaceNode}
  6101. */
  6102. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6103. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6104. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6105. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6106. /**
  6107. * This class is only relevant if the referenced property is array-like.
  6108. * In this case, `ReferenceElementNode` allows to refer to a specific
  6109. * element inside the data structure via an index.
  6110. *
  6111. * @augments ArrayElementNode
  6112. */
  6113. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6114. static get type() {
  6115. return 'ReferenceElementNode';
  6116. }
  6117. /**
  6118. * Constructs a new reference element node.
  6119. *
  6120. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6121. * @param {Node} indexNode - The index node that defines the element access.
  6122. */
  6123. constructor( referenceNode, indexNode ) {
  6124. super( referenceNode, indexNode );
  6125. /**
  6126. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6127. * property references to the current node.
  6128. *
  6129. * @type {?ReferenceBaseNode}
  6130. * @default null
  6131. */
  6132. this.referenceNode = referenceNode;
  6133. /**
  6134. * This flag can be used for type testing.
  6135. *
  6136. * @type {boolean}
  6137. * @readonly
  6138. * @default true
  6139. */
  6140. this.isReferenceElementNode = true;
  6141. }
  6142. /**
  6143. * This method is overwritten since the node type is inferred from
  6144. * the uniform type of the reference node.
  6145. *
  6146. * @return {string} The node type.
  6147. */
  6148. getNodeType() {
  6149. return this.referenceNode.uniformType;
  6150. }
  6151. generate( builder ) {
  6152. const snippet = super.generate( builder );
  6153. const arrayType = this.referenceNode.getNodeType();
  6154. const elementType = this.getNodeType();
  6155. return builder.format( snippet, arrayType, elementType );
  6156. }
  6157. };
  6158. /**
  6159. * Base class for nodes which establishes a reference to a property of another object.
  6160. * In this way, the value of the node is automatically linked to the value of
  6161. * referenced object. Reference nodes internally represent the linked value
  6162. * as a uniform.
  6163. *
  6164. * @augments Node
  6165. */
  6166. class ReferenceBaseNode extends Node {
  6167. static get type() {
  6168. return 'ReferenceBaseNode';
  6169. }
  6170. /**
  6171. * Constructs a new reference base node.
  6172. *
  6173. * @param {string} property - The name of the property the node refers to.
  6174. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6175. * @param {?Object} [object=null] - The object the property belongs to.
  6176. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6177. */
  6178. constructor( property, uniformType, object = null, count = null ) {
  6179. super();
  6180. /**
  6181. * The name of the property the node refers to.
  6182. *
  6183. * @type {string}
  6184. */
  6185. this.property = property;
  6186. /**
  6187. * The uniform type that should be used to represent the property value.
  6188. *
  6189. * @type {string}
  6190. */
  6191. this.uniformType = uniformType;
  6192. /**
  6193. * The object the property belongs to.
  6194. *
  6195. * @type {?Object}
  6196. * @default null
  6197. */
  6198. this.object = object;
  6199. /**
  6200. * When the linked property is an array, this parameter defines its length.
  6201. *
  6202. * @type {?number}
  6203. * @default null
  6204. */
  6205. this.count = count;
  6206. /**
  6207. * The property name might have dots so nested properties can be referred.
  6208. * The hierarchy of the names is stored inside this array.
  6209. *
  6210. * @type {Array<string>}
  6211. */
  6212. this.properties = property.split( '.' );
  6213. /**
  6214. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6215. * since the final reference might be updated from calling code.
  6216. *
  6217. * @type {?Object}
  6218. * @default null
  6219. */
  6220. this.reference = object;
  6221. /**
  6222. * The uniform node that holds the value of the reference node.
  6223. *
  6224. * @type {UniformNode}
  6225. * @default null
  6226. */
  6227. this.node = null;
  6228. /**
  6229. * The uniform group of the internal uniform.
  6230. *
  6231. * @type {UniformGroupNode}
  6232. * @default null
  6233. */
  6234. this.group = null;
  6235. /**
  6236. * Overwritten since reference nodes are updated per object.
  6237. *
  6238. * @type {string}
  6239. * @default 'object'
  6240. */
  6241. this.updateType = NodeUpdateType.OBJECT;
  6242. }
  6243. /**
  6244. * Sets the uniform group for this reference node.
  6245. *
  6246. * @param {UniformGroupNode} group - The uniform group to set.
  6247. * @return {ReferenceBaseNode} A reference to this node.
  6248. */
  6249. setGroup( group ) {
  6250. this.group = group;
  6251. return this;
  6252. }
  6253. /**
  6254. * When the referred property is array-like, this method can be used
  6255. * to access elements via an index node.
  6256. *
  6257. * @param {IndexNode} indexNode - indexNode.
  6258. * @return {ReferenceElementNode} A reference to an element.
  6259. */
  6260. element( indexNode ) {
  6261. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6262. }
  6263. /**
  6264. * Sets the node type which automatically defines the internal
  6265. * uniform type.
  6266. *
  6267. * @param {string} uniformType - The type to set.
  6268. */
  6269. setNodeType( uniformType ) {
  6270. const node = uniform( null, uniformType );
  6271. if ( this.group !== null ) {
  6272. node.setGroup( this.group );
  6273. }
  6274. this.node = node;
  6275. }
  6276. /**
  6277. * This method is overwritten since the node type is inferred from
  6278. * the type of the reference node.
  6279. *
  6280. * @param {NodeBuilder} builder - The current node builder.
  6281. * @return {string} The node type.
  6282. */
  6283. getNodeType( builder ) {
  6284. if ( this.node === null ) {
  6285. this.updateReference( builder );
  6286. this.updateValue();
  6287. }
  6288. return this.node.getNodeType( builder );
  6289. }
  6290. /**
  6291. * Returns the property value from the given referred object.
  6292. *
  6293. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6294. * @return {any} The value.
  6295. */
  6296. getValueFromReference( object = this.reference ) {
  6297. const { properties } = this;
  6298. let value = object[ properties[ 0 ] ];
  6299. for ( let i = 1; i < properties.length; i ++ ) {
  6300. value = value[ properties[ i ] ];
  6301. }
  6302. return value;
  6303. }
  6304. /**
  6305. * Allows to update the reference based on the given state. The state is only
  6306. * evaluated {@link ReferenceBaseNode#object} is not set.
  6307. *
  6308. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6309. * @return {Object} The updated reference.
  6310. */
  6311. updateReference( state ) {
  6312. this.reference = this.object !== null ? this.object : state.object;
  6313. return this.reference;
  6314. }
  6315. /**
  6316. * The output of the reference node is the internal uniform node.
  6317. *
  6318. * @return {UniformNode} The output node.
  6319. */
  6320. setup() {
  6321. this.updateValue();
  6322. return this.node;
  6323. }
  6324. /**
  6325. * Overwritten to update the internal uniform value.
  6326. *
  6327. * @param {NodeFrame} frame - A reference to the current node frame.
  6328. */
  6329. update( /*frame*/ ) {
  6330. this.updateValue();
  6331. }
  6332. /**
  6333. * Retrieves the value from the referred object property and uses it
  6334. * to updated the internal uniform.
  6335. */
  6336. updateValue() {
  6337. if ( this.node === null ) this.setNodeType( this.uniformType );
  6338. const value = this.getValueFromReference();
  6339. if ( Array.isArray( value ) ) {
  6340. this.node.array = value;
  6341. } else {
  6342. this.node.value = value;
  6343. }
  6344. }
  6345. }
  6346. /**
  6347. * TSL function for creating a reference base node.
  6348. *
  6349. * @tsl
  6350. * @function
  6351. * @param {string} name - The name of the property the node refers to.
  6352. * @param {string} type - The uniform type that should be used to represent the property value.
  6353. * @param {Object} object - The object the property belongs to.
  6354. * @returns {ReferenceBaseNode}
  6355. */
  6356. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6357. /**
  6358. * This node is a special type of reference node which is intended
  6359. * for linking renderer properties with node values.
  6360. * ```js
  6361. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6362. * ```
  6363. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6364. * automatically be updated.
  6365. *
  6366. * @augments ReferenceBaseNode
  6367. */
  6368. class RendererReferenceNode extends ReferenceBaseNode {
  6369. static get type() {
  6370. return 'RendererReferenceNode';
  6371. }
  6372. /**
  6373. * Constructs a new renderer reference node.
  6374. *
  6375. * @param {string} property - The name of the property the node refers to.
  6376. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6377. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6378. * the node refers to the renderer of the current state.
  6379. */
  6380. constructor( property, inputType, renderer = null ) {
  6381. super( property, inputType, renderer );
  6382. /**
  6383. * The renderer the property belongs to. When no renderer is set,
  6384. * the node refers to the renderer of the current state.
  6385. *
  6386. * @type {?Renderer}
  6387. * @default null
  6388. */
  6389. this.renderer = renderer;
  6390. this.setGroup( renderGroup );
  6391. }
  6392. /**
  6393. * Updates the reference based on the given state. The state is only evaluated
  6394. * {@link RendererReferenceNode#renderer} is not set.
  6395. *
  6396. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6397. * @return {Object} The updated reference.
  6398. */
  6399. updateReference( state ) {
  6400. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6401. return this.reference;
  6402. }
  6403. }
  6404. /**
  6405. * TSL function for creating a renderer reference node.
  6406. *
  6407. * @tsl
  6408. * @function
  6409. * @param {string} name - The name of the property the node refers to.
  6410. * @param {string} type - The uniform type that should be used to represent the property value.
  6411. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6412. * the node refers to the renderer of the current state.
  6413. * @returns {RendererReferenceNode}
  6414. */
  6415. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6416. /**
  6417. * This node represents a tone mapping operation.
  6418. *
  6419. * @augments TempNode
  6420. */
  6421. class ToneMappingNode extends TempNode {
  6422. static get type() {
  6423. return 'ToneMappingNode';
  6424. }
  6425. /**
  6426. * Constructs a new tone mapping node.
  6427. *
  6428. * @param {number} toneMapping - The tone mapping type.
  6429. * @param {Node} exposureNode - The tone mapping exposure.
  6430. * @param {Node} [colorNode=null] - The color node to process.
  6431. */
  6432. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6433. super( 'vec3' );
  6434. /**
  6435. * The tone mapping type.
  6436. *
  6437. * @type {number}
  6438. */
  6439. this.toneMapping = toneMapping;
  6440. /**
  6441. * The tone mapping exposure.
  6442. *
  6443. * @type {Node}
  6444. * @default null
  6445. */
  6446. this.exposureNode = exposureNode;
  6447. /**
  6448. * Represents the color to process.
  6449. *
  6450. * @type {?Node}
  6451. * @default null
  6452. */
  6453. this.colorNode = colorNode;
  6454. }
  6455. /**
  6456. * Overwrites the default `customCacheKey()` implementation by including the tone
  6457. * mapping type into the cache key.
  6458. *
  6459. * @return {number} The hash.
  6460. */
  6461. customCacheKey() {
  6462. return hash$1( this.toneMapping );
  6463. }
  6464. setup( builder ) {
  6465. const colorNode = this.colorNode || builder.context.color;
  6466. const toneMapping = this.toneMapping;
  6467. if ( toneMapping === NoToneMapping ) return colorNode;
  6468. let outputNode = null;
  6469. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6470. if ( toneMappingFn !== null ) {
  6471. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6472. } else {
  6473. error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6474. outputNode = colorNode;
  6475. }
  6476. return outputNode;
  6477. }
  6478. }
  6479. /**
  6480. * TSL function for creating a tone mapping node.
  6481. *
  6482. * @tsl
  6483. * @function
  6484. * @param {number} mapping - The tone mapping type.
  6485. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6486. * @param {Node<vec3> | Color} color - The color node to process.
  6487. * @returns {ToneMappingNode<vec3>}
  6488. */
  6489. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6490. /**
  6491. * TSL object that represents the global tone mapping exposure of the renderer.
  6492. *
  6493. * @tsl
  6494. * @type {RendererReferenceNode<vec3>}
  6495. */
  6496. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6497. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6498. /**
  6499. * In earlier `three.js` versions it was only possible to define attribute data
  6500. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6501. * on the node level.
  6502. * ```js
  6503. * const geometry = new THREE.PlaneGeometry();
  6504. * const positionAttribute = geometry.getAttribute( 'position' );
  6505. *
  6506. * const colors = [];
  6507. * for ( let i = 0; i < position.count; i ++ ) {
  6508. * colors.push( 1, 0, 0 );
  6509. * }
  6510. *
  6511. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6512. * ```
  6513. * This new approach is especially interesting when geometry data are generated via
  6514. * compute shaders. The below line converts a storage buffer into an attribute node.
  6515. * ```js
  6516. * material.positionNode = positionBuffer.toAttribute();
  6517. * ```
  6518. * @augments InputNode
  6519. */
  6520. class BufferAttributeNode extends InputNode {
  6521. static get type() {
  6522. return 'BufferAttributeNode';
  6523. }
  6524. /**
  6525. * Constructs a new buffer attribute node.
  6526. *
  6527. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6528. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6529. * @param {number} [bufferStride=0] - The buffer stride.
  6530. * @param {number} [bufferOffset=0] - The buffer offset.
  6531. */
  6532. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6533. super( value, bufferType );
  6534. /**
  6535. * This flag can be used for type testing.
  6536. *
  6537. * @type {boolean}
  6538. * @readonly
  6539. * @default true
  6540. */
  6541. this.isBufferNode = true;
  6542. /**
  6543. * The buffer type (e.g. `'vec3'`).
  6544. *
  6545. * @type {?string}
  6546. * @default null
  6547. */
  6548. this.bufferType = bufferType;
  6549. /**
  6550. * The buffer stride.
  6551. *
  6552. * @type {number}
  6553. * @default 0
  6554. */
  6555. this.bufferStride = bufferStride;
  6556. /**
  6557. * The buffer offset.
  6558. *
  6559. * @type {number}
  6560. * @default 0
  6561. */
  6562. this.bufferOffset = bufferOffset;
  6563. /**
  6564. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6565. * if you are planning to update the attribute data per frame.
  6566. *
  6567. * @type {number}
  6568. * @default StaticDrawUsage
  6569. */
  6570. this.usage = StaticDrawUsage;
  6571. /**
  6572. * Whether the attribute is instanced or not.
  6573. *
  6574. * @type {boolean}
  6575. * @default false
  6576. */
  6577. this.instanced = false;
  6578. /**
  6579. * A reference to the buffer attribute.
  6580. *
  6581. * @type {?BufferAttribute}
  6582. * @default null
  6583. */
  6584. this.attribute = null;
  6585. /**
  6586. * `BufferAttributeNode` sets this property to `true` by default.
  6587. *
  6588. * @type {boolean}
  6589. * @default true
  6590. */
  6591. this.global = true;
  6592. if ( value && value.isBufferAttribute === true ) {
  6593. this.attribute = value;
  6594. this.usage = value.usage;
  6595. this.instanced = value.isInstancedBufferAttribute;
  6596. }
  6597. }
  6598. /**
  6599. * This method is overwritten since the attribute data might be shared
  6600. * and thus the hash should be shared as well.
  6601. *
  6602. * @param {NodeBuilder} builder - The current node builder.
  6603. * @return {string} The hash.
  6604. */
  6605. getHash( builder ) {
  6606. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6607. let bufferData = builder.globalCache.getData( this.value );
  6608. if ( bufferData === undefined ) {
  6609. bufferData = {
  6610. node: this
  6611. };
  6612. builder.globalCache.setData( this.value, bufferData );
  6613. }
  6614. return bufferData.node.uuid;
  6615. }
  6616. return this.uuid;
  6617. }
  6618. /**
  6619. * This method is overwritten since the node type is inferred from
  6620. * the buffer attribute.
  6621. *
  6622. * @param {NodeBuilder} builder - The current node builder.
  6623. * @return {string} The node type.
  6624. */
  6625. getNodeType( builder ) {
  6626. if ( this.bufferType === null ) {
  6627. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6628. }
  6629. return this.bufferType;
  6630. }
  6631. /**
  6632. * Depending on which value was passed to the node, `setup()` behaves
  6633. * differently. If no instance of `BufferAttribute` was passed, the method
  6634. * creates an internal attribute and configures it respectively.
  6635. *
  6636. * @param {NodeBuilder} builder - The current node builder.
  6637. */
  6638. setup( builder ) {
  6639. if ( this.attribute !== null ) return;
  6640. const type = this.getNodeType( builder );
  6641. const array = this.value;
  6642. const itemSize = builder.getTypeLength( type );
  6643. const stride = this.bufferStride || itemSize;
  6644. const offset = this.bufferOffset;
  6645. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6646. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6647. buffer.setUsage( this.usage );
  6648. this.attribute = bufferAttribute;
  6649. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6650. }
  6651. /**
  6652. * Generates the code snippet of the buffer attribute node.
  6653. *
  6654. * @param {NodeBuilder} builder - The current node builder.
  6655. * @return {string} The generated code snippet.
  6656. */
  6657. generate( builder ) {
  6658. const nodeType = this.getNodeType( builder );
  6659. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6660. const propertyName = builder.getPropertyName( nodeAttribute );
  6661. let output = null;
  6662. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6663. this.name = propertyName;
  6664. output = propertyName;
  6665. } else {
  6666. const nodeVarying = varying( this );
  6667. output = nodeVarying.build( builder, nodeType );
  6668. }
  6669. return output;
  6670. }
  6671. /**
  6672. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6673. *
  6674. * @param {NodeBuilder} builder - The current node builder.
  6675. * @return {string} The input type.
  6676. */
  6677. getInputType( /*builder*/ ) {
  6678. return 'bufferAttribute';
  6679. }
  6680. /**
  6681. * Sets the `usage` property to the given value.
  6682. *
  6683. * @param {number} value - The usage to set.
  6684. * @return {BufferAttributeNode} A reference to this node.
  6685. */
  6686. setUsage( value ) {
  6687. this.usage = value;
  6688. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6689. this.attribute.usage = value;
  6690. }
  6691. return this;
  6692. }
  6693. /**
  6694. * Sets the `instanced` property to the given value.
  6695. *
  6696. * @param {boolean} value - The value to set.
  6697. * @return {BufferAttributeNode} A reference to this node.
  6698. */
  6699. setInstanced( value ) {
  6700. this.instanced = value;
  6701. return this;
  6702. }
  6703. }
  6704. /**
  6705. * TSL function for creating a buffer attribute node.
  6706. *
  6707. * @tsl
  6708. * @function
  6709. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6710. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6711. * @param {number} [stride=0] - The buffer stride.
  6712. * @param {number} [offset=0] - The buffer offset.
  6713. * @returns {BufferAttributeNode}
  6714. */
  6715. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6716. /**
  6717. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6718. * Use this function if attribute data are updated per frame.
  6719. *
  6720. * @tsl
  6721. * @function
  6722. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6723. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6724. * @param {number} [stride=0] - The buffer stride.
  6725. * @param {number} [offset=0] - The buffer offset.
  6726. * @returns {BufferAttributeNode}
  6727. */
  6728. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6729. /**
  6730. * TSL function for creating a buffer attribute node but with enabled instancing
  6731. *
  6732. * @tsl
  6733. * @function
  6734. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6735. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6736. * @param {number} [stride=0] - The buffer stride.
  6737. * @param {number} [offset=0] - The buffer offset.
  6738. * @returns {BufferAttributeNode}
  6739. */
  6740. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6741. /**
  6742. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6743. *
  6744. * @tsl
  6745. * @function
  6746. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6747. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6748. * @param {number} [stride=0] - The buffer stride.
  6749. * @param {number} [offset=0] - The buffer offset.
  6750. * @returns {BufferAttributeNode}
  6751. */
  6752. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6753. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6754. /**
  6755. * TODO
  6756. *
  6757. * @augments Node
  6758. */
  6759. class ComputeNode extends Node {
  6760. static get type() {
  6761. return 'ComputeNode';
  6762. }
  6763. /**
  6764. * Constructs a new compute node.
  6765. *
  6766. * @param {Node} computeNode - TODO
  6767. * @param {Array<number>} workgroupSize - TODO.
  6768. */
  6769. constructor( computeNode, workgroupSize ) {
  6770. super( 'void' );
  6771. /**
  6772. * This flag can be used for type testing.
  6773. *
  6774. * @type {boolean}
  6775. * @readonly
  6776. * @default true
  6777. */
  6778. this.isComputeNode = true;
  6779. /**
  6780. * TODO
  6781. *
  6782. * @type {Node}
  6783. */
  6784. this.computeNode = computeNode;
  6785. /**
  6786. * TODO
  6787. *
  6788. * @type {Array<number>}
  6789. * @default [ 64 ]
  6790. */
  6791. this.workgroupSize = workgroupSize;
  6792. /**
  6793. * TODO
  6794. *
  6795. * @type {number}
  6796. */
  6797. this.count = null;
  6798. /**
  6799. * TODO
  6800. *
  6801. * @type {number}
  6802. */
  6803. this.version = 1;
  6804. /**
  6805. * The name or label of the uniform.
  6806. *
  6807. * @type {string}
  6808. * @default ''
  6809. */
  6810. this.name = '';
  6811. /**
  6812. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6813. * is executed once per object by default.
  6814. *
  6815. * @type {string}
  6816. * @default 'object'
  6817. */
  6818. this.updateBeforeType = NodeUpdateType.OBJECT;
  6819. /**
  6820. * TODO
  6821. *
  6822. * @type {?Function}
  6823. */
  6824. this.onInitFunction = null;
  6825. }
  6826. setCount( count ) {
  6827. this.count = count;
  6828. return this;
  6829. }
  6830. getCount() {
  6831. return this.count;
  6832. }
  6833. /**
  6834. * Executes the `dispose` event for this node.
  6835. */
  6836. dispose() {
  6837. this.dispatchEvent( { type: 'dispose' } );
  6838. }
  6839. /**
  6840. * Sets the {@link ComputeNode#name} property.
  6841. *
  6842. * @param {string} name - The name of the uniform.
  6843. * @return {ComputeNode} A reference to this node.
  6844. */
  6845. setName( name ) {
  6846. this.name = name;
  6847. return this;
  6848. }
  6849. /**
  6850. * Sets the {@link ComputeNode#name} property.
  6851. *
  6852. * @deprecated
  6853. * @param {string} name - The name of the uniform.
  6854. * @return {ComputeNode} A reference to this node.
  6855. */
  6856. label( name ) {
  6857. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6858. return this.setName( name );
  6859. }
  6860. /**
  6861. * TODO
  6862. *
  6863. * @param {Function} callback - TODO.
  6864. * @return {ComputeNode} A reference to this node.
  6865. */
  6866. onInit( callback ) {
  6867. this.onInitFunction = callback;
  6868. return this;
  6869. }
  6870. /**
  6871. * The method execute the compute for this node.
  6872. *
  6873. * @param {NodeFrame} frame - A reference to the current node frame.
  6874. */
  6875. updateBefore( { renderer } ) {
  6876. renderer.compute( this );
  6877. }
  6878. setup( builder ) {
  6879. const result = this.computeNode.build( builder );
  6880. if ( result ) {
  6881. const properties = builder.getNodeProperties( this );
  6882. properties.outputComputeNode = result.outputNode;
  6883. result.outputNode = null;
  6884. }
  6885. return result;
  6886. }
  6887. generate( builder, output ) {
  6888. const { shaderStage } = builder;
  6889. if ( shaderStage === 'compute' ) {
  6890. const snippet = this.computeNode.build( builder, 'void' );
  6891. if ( snippet !== '' ) {
  6892. builder.addLineFlowCode( snippet, this );
  6893. }
  6894. } else {
  6895. const properties = builder.getNodeProperties( this );
  6896. const outputComputeNode = properties.outputComputeNode;
  6897. if ( outputComputeNode ) {
  6898. return outputComputeNode.build( builder, output );
  6899. }
  6900. }
  6901. }
  6902. }
  6903. /**
  6904. * TSL function for creating a compute kernel node.
  6905. *
  6906. * @tsl
  6907. * @function
  6908. * @param {Node} node - TODO
  6909. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6910. * @returns {AtomicFunctionNode}
  6911. */
  6912. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6913. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6914. error( 'TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6915. }
  6916. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6917. const val = workgroupSize[ i ];
  6918. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6919. error( `TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6920. }
  6921. }
  6922. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6923. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6924. //
  6925. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6926. };
  6927. /**
  6928. * TSL function for creating a compute node.
  6929. *
  6930. * @tsl
  6931. * @function
  6932. * @param {Node} node - TODO
  6933. * @param {number} count - TODO.
  6934. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6935. * @returns {AtomicFunctionNode}
  6936. */
  6937. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  6938. addMethodChaining( 'compute', compute );
  6939. addMethodChaining( 'computeKernel', computeKernel );
  6940. /**
  6941. * This node can be used as a cache management component for another node.
  6942. * Caching is in general used by default in {@link NodeBuilder} but this node
  6943. * allows the usage of a shared parent cache during the build process.
  6944. *
  6945. * @augments Node
  6946. */
  6947. class CacheNode extends Node {
  6948. static get type() {
  6949. return 'CacheNode';
  6950. }
  6951. /**
  6952. * Constructs a new cache node.
  6953. *
  6954. * @param {Node} node - The node that should be cached.
  6955. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6956. */
  6957. constructor( node, parent = true ) {
  6958. super();
  6959. /**
  6960. * The node that should be cached.
  6961. *
  6962. * @type {Node}
  6963. */
  6964. this.node = node;
  6965. /**
  6966. * Whether this node refers to a shared parent cache or not.
  6967. *
  6968. * @type {boolean}
  6969. * @default true
  6970. */
  6971. this.parent = parent;
  6972. /**
  6973. * This flag can be used for type testing.
  6974. *
  6975. * @type {boolean}
  6976. * @readonly
  6977. * @default true
  6978. */
  6979. this.isCacheNode = true;
  6980. }
  6981. getNodeType( builder ) {
  6982. const previousCache = builder.getCache();
  6983. const cache = builder.getCacheFromNode( this, this.parent );
  6984. builder.setCache( cache );
  6985. const nodeType = this.node.getNodeType( builder );
  6986. builder.setCache( previousCache );
  6987. return nodeType;
  6988. }
  6989. build( builder, ...params ) {
  6990. const previousCache = builder.getCache();
  6991. const cache = builder.getCacheFromNode( this, this.parent );
  6992. builder.setCache( cache );
  6993. const data = this.node.build( builder, ...params );
  6994. builder.setCache( previousCache );
  6995. return data;
  6996. }
  6997. }
  6998. /**
  6999. * TSL function for creating a cache node.
  7000. *
  7001. * @tsl
  7002. * @function
  7003. * @param {Node} node - The node that should be cached.
  7004. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  7005. * @returns {CacheNode}
  7006. */
  7007. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  7008. addMethodChaining( 'cache', cache );
  7009. /**
  7010. * The class generates the code of a given node but returns another node in the output.
  7011. * This can be used to call a method or node that does not return a value, i.e.
  7012. * type `void` on an input where returning a value is required. Example:
  7013. *
  7014. * ```js
  7015. * material.colorNode = myColor.bypass( runVoidFn() )
  7016. *```
  7017. *
  7018. * @augments Node
  7019. */
  7020. class BypassNode extends Node {
  7021. static get type() {
  7022. return 'BypassNode';
  7023. }
  7024. /**
  7025. * Constructs a new bypass node.
  7026. *
  7027. * @param {Node} outputNode - The output node.
  7028. * @param {Node} callNode - The call node.
  7029. */
  7030. constructor( outputNode, callNode ) {
  7031. super();
  7032. /**
  7033. * This flag can be used for type testing.
  7034. *
  7035. * @type {boolean}
  7036. * @readonly
  7037. * @default true
  7038. */
  7039. this.isBypassNode = true;
  7040. /**
  7041. * The output node.
  7042. *
  7043. * @type {Node}
  7044. */
  7045. this.outputNode = outputNode;
  7046. /**
  7047. * The call node.
  7048. *
  7049. * @type {Node}
  7050. */
  7051. this.callNode = callNode;
  7052. }
  7053. getNodeType( builder ) {
  7054. return this.outputNode.getNodeType( builder );
  7055. }
  7056. generate( builder ) {
  7057. const snippet = this.callNode.build( builder, 'void' );
  7058. if ( snippet !== '' ) {
  7059. builder.addLineFlowCode( snippet, this );
  7060. }
  7061. return this.outputNode.build( builder );
  7062. }
  7063. }
  7064. /**
  7065. * TSL function for creating a bypass node.
  7066. *
  7067. * @tsl
  7068. * @function
  7069. * @param {Node} outputNode - The output node.
  7070. * @param {Node} callNode - The call node.
  7071. * @returns {BypassNode}
  7072. */
  7073. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7074. addMethodChaining( 'bypass', bypass );
  7075. /**
  7076. * This node allows to remap a node value from one range into another. E.g a value of
  7077. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7078. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7079. *
  7080. * @augments Node
  7081. */
  7082. class RemapNode extends Node {
  7083. static get type() {
  7084. return 'RemapNode';
  7085. }
  7086. /**
  7087. * Constructs a new remap node.
  7088. *
  7089. * @param {Node} node - The node that should be remapped.
  7090. * @param {Node} inLowNode - The source or current lower bound of the range.
  7091. * @param {Node} inHighNode - The source or current upper bound of the range.
  7092. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7093. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7094. */
  7095. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7096. super();
  7097. /**
  7098. * The node that should be remapped.
  7099. *
  7100. * @type {Node}
  7101. */
  7102. this.node = node;
  7103. /**
  7104. * The source or current lower bound of the range.
  7105. *
  7106. * @type {Node}
  7107. */
  7108. this.inLowNode = inLowNode;
  7109. /**
  7110. * The source or current upper bound of the range.
  7111. *
  7112. * @type {Node}
  7113. */
  7114. this.inHighNode = inHighNode;
  7115. /**
  7116. * The target lower bound of the range.
  7117. *
  7118. * @type {Node}
  7119. * @default float(0)
  7120. */
  7121. this.outLowNode = outLowNode;
  7122. /**
  7123. * The target upper bound of the range.
  7124. *
  7125. * @type {Node}
  7126. * @default float(1)
  7127. */
  7128. this.outHighNode = outHighNode;
  7129. /**
  7130. * Whether the node value should be clamped before
  7131. * remapping it to the target range.
  7132. *
  7133. * @type {boolean}
  7134. * @default true
  7135. */
  7136. this.doClamp = true;
  7137. }
  7138. setup() {
  7139. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7140. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7141. if ( doClamp === true ) t = t.clamp();
  7142. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7143. }
  7144. }
  7145. /**
  7146. * TSL function for creating a remap node.
  7147. *
  7148. * @tsl
  7149. * @function
  7150. * @param {Node} node - The node that should be remapped.
  7151. * @param {Node} inLowNode - The source or current lower bound of the range.
  7152. * @param {Node} inHighNode - The source or current upper bound of the range.
  7153. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7154. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7155. * @returns {RemapNode}
  7156. */
  7157. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7158. /**
  7159. * TSL function for creating a remap node, but with enabled clamping.
  7160. *
  7161. * @tsl
  7162. * @function
  7163. * @param {Node} node - The node that should be remapped.
  7164. * @param {Node} inLowNode - The source or current lower bound of the range.
  7165. * @param {Node} inHighNode - The source or current upper bound of the range.
  7166. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7167. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7168. * @returns {RemapNode}
  7169. */
  7170. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7171. addMethodChaining( 'remap', remap );
  7172. addMethodChaining( 'remapClamp', remapClamp );
  7173. /**
  7174. * This class can be used to implement basic expressions in shader code.
  7175. * Basic examples for that are `return`, `continue` or `discard` statements.
  7176. *
  7177. * @augments Node
  7178. */
  7179. class ExpressionNode extends Node {
  7180. static get type() {
  7181. return 'ExpressionNode';
  7182. }
  7183. /**
  7184. * Constructs a new expression node.
  7185. *
  7186. * @param {string} [snippet=''] - The native code snippet.
  7187. * @param {string} [nodeType='void'] - The node type.
  7188. */
  7189. constructor( snippet = '', nodeType = 'void' ) {
  7190. super( nodeType );
  7191. /**
  7192. * The native code snippet.
  7193. *
  7194. * @type {string}
  7195. * @default ''
  7196. */
  7197. this.snippet = snippet;
  7198. }
  7199. generate( builder, output ) {
  7200. const type = this.getNodeType( builder );
  7201. const snippet = this.snippet;
  7202. if ( type === 'void' ) {
  7203. builder.addLineFlowCode( snippet, this );
  7204. } else {
  7205. return builder.format( snippet, type, output );
  7206. }
  7207. }
  7208. }
  7209. /**
  7210. * TSL function for creating an expression node.
  7211. *
  7212. * @tsl
  7213. * @function
  7214. * @param {string} [snippet] - The native code snippet.
  7215. * @param {?string} [nodeType='void'] - The node type.
  7216. * @returns {ExpressionNode}
  7217. */
  7218. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7219. /**
  7220. * Represents a `discard` shader operation in TSL.
  7221. *
  7222. * @tsl
  7223. * @function
  7224. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7225. * @return {Node} The `discard` expression.
  7226. */
  7227. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7228. /**
  7229. * Represents a `return` shader operation in TSL.
  7230. *
  7231. * @tsl
  7232. * @function
  7233. * @return {ExpressionNode} The `return` expression.
  7234. */
  7235. const Return = () => expression( 'return' ).toStack();
  7236. addMethodChaining( 'discard', Discard );
  7237. /**
  7238. * Normally, tone mapping and color conversion happens automatically
  7239. * before outputting pixel too the default (screen) framebuffer. In certain
  7240. * post processing setups this happens to late because certain effects
  7241. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7242. * to apply tone mapping and color space conversion at an arbitrary point
  7243. * in the effect chain.
  7244. *
  7245. * When applying tone mapping and color space conversion manually with this node,
  7246. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7247. *
  7248. * ```js
  7249. * const postProcessing = new PostProcessing( renderer );
  7250. * postProcessing.outputColorTransform = false;
  7251. *
  7252. * const scenePass = pass( scene, camera );
  7253. * const outputPass = renderOutput( scenePass );
  7254. *
  7255. * postProcessing.outputNode = outputPass;
  7256. * ```
  7257. *
  7258. * @augments TempNode
  7259. */
  7260. class RenderOutputNode extends TempNode {
  7261. static get type() {
  7262. return 'RenderOutputNode';
  7263. }
  7264. /**
  7265. * Constructs a new render output node.
  7266. *
  7267. * @param {Node} colorNode - The color node to process.
  7268. * @param {?number} toneMapping - The tone mapping type.
  7269. * @param {?string} outputColorSpace - The output color space.
  7270. */
  7271. constructor( colorNode, toneMapping, outputColorSpace ) {
  7272. super( 'vec4' );
  7273. /**
  7274. * The color node to process.
  7275. *
  7276. * @type {Node}
  7277. */
  7278. this.colorNode = colorNode;
  7279. /**
  7280. * The tone mapping type.
  7281. *
  7282. * @type {?number}
  7283. */
  7284. this.toneMapping = toneMapping;
  7285. /**
  7286. * The output color space.
  7287. *
  7288. * @type {?string}
  7289. */
  7290. this.outputColorSpace = outputColorSpace;
  7291. /**
  7292. * This flag can be used for type testing.
  7293. *
  7294. * @type {boolean}
  7295. * @readonly
  7296. * @default true
  7297. */
  7298. this.isRenderOutputNode = true;
  7299. }
  7300. setup( { context } ) {
  7301. let outputNode = this.colorNode || context.color;
  7302. // tone mapping
  7303. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  7304. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7305. if ( toneMapping !== NoToneMapping ) {
  7306. outputNode = outputNode.toneMapping( toneMapping );
  7307. }
  7308. // working to output color space
  7309. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7310. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7311. }
  7312. return outputNode;
  7313. }
  7314. }
  7315. /**
  7316. * TSL function for creating a posterize node.
  7317. *
  7318. * @tsl
  7319. * @function
  7320. * @param {Node} color - The color node to process.
  7321. * @param {?number} [toneMapping=null] - The tone mapping type.
  7322. * @param {?string} [outputColorSpace=null] - The output color space.
  7323. * @returns {RenderOutputNode}
  7324. */
  7325. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7326. addMethodChaining( 'renderOutput', renderOutput );
  7327. class DebugNode extends TempNode {
  7328. static get type() {
  7329. return 'DebugNode';
  7330. }
  7331. constructor( node, callback = null ) {
  7332. super();
  7333. this.node = node;
  7334. this.callback = callback;
  7335. }
  7336. getNodeType( builder ) {
  7337. return this.node.getNodeType( builder );
  7338. }
  7339. setup( builder ) {
  7340. return this.node.build( builder );
  7341. }
  7342. analyze( builder ) {
  7343. return this.node.build( builder );
  7344. }
  7345. generate( builder ) {
  7346. const callback = this.callback;
  7347. const snippet = this.node.build( builder );
  7348. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7349. const border = '-'.repeat( title.length );
  7350. let code = '';
  7351. code += '// #' + title + '#\n';
  7352. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7353. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7354. code += '// #' + border + '#\n';
  7355. if ( callback !== null ) {
  7356. callback( builder, code );
  7357. } else {
  7358. log$1( code );
  7359. }
  7360. return snippet;
  7361. }
  7362. }
  7363. /**
  7364. * TSL function for creating a debug node.
  7365. *
  7366. * @tsl
  7367. * @function
  7368. * @param {Node} node - The node to debug.
  7369. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7370. * @returns {DebugNode}
  7371. */
  7372. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7373. addMethodChaining( 'debug', debug );
  7374. function addNodeElement( name/*, nodeElement*/ ) {
  7375. warn( 'TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7376. }
  7377. /**
  7378. * Base class for representing shader attributes as nodes.
  7379. *
  7380. * @augments Node
  7381. */
  7382. class AttributeNode extends Node {
  7383. static get type() {
  7384. return 'AttributeNode';
  7385. }
  7386. /**
  7387. * Constructs a new attribute node.
  7388. *
  7389. * @param {string} attributeName - The name of the attribute.
  7390. * @param {?string} nodeType - The node type.
  7391. */
  7392. constructor( attributeName, nodeType = null ) {
  7393. super( nodeType );
  7394. /**
  7395. * `AttributeNode` sets this property to `true` by default.
  7396. *
  7397. * @type {boolean}
  7398. * @default true
  7399. */
  7400. this.global = true;
  7401. this._attributeName = attributeName;
  7402. }
  7403. getHash( builder ) {
  7404. return this.getAttributeName( builder );
  7405. }
  7406. getNodeType( builder ) {
  7407. let nodeType = this.nodeType;
  7408. if ( nodeType === null ) {
  7409. const attributeName = this.getAttributeName( builder );
  7410. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7411. const attribute = builder.geometry.getAttribute( attributeName );
  7412. nodeType = builder.getTypeFromAttribute( attribute );
  7413. } else {
  7414. nodeType = 'float';
  7415. }
  7416. }
  7417. return nodeType;
  7418. }
  7419. /**
  7420. * Sets the attribute name to the given value. The method can be
  7421. * overwritten in derived classes if the final name must be computed
  7422. * analytically.
  7423. *
  7424. * @param {string} attributeName - The name of the attribute.
  7425. * @return {AttributeNode} A reference to this node.
  7426. */
  7427. setAttributeName( attributeName ) {
  7428. this._attributeName = attributeName;
  7429. return this;
  7430. }
  7431. /**
  7432. * Returns the attribute name of this node. The method can be
  7433. * overwritten in derived classes if the final name must be computed
  7434. * analytically.
  7435. *
  7436. * @param {NodeBuilder} builder - The current node builder.
  7437. * @return {string} The attribute name.
  7438. */
  7439. getAttributeName( /*builder*/ ) {
  7440. return this._attributeName;
  7441. }
  7442. generate( builder ) {
  7443. const attributeName = this.getAttributeName( builder );
  7444. const nodeType = this.getNodeType( builder );
  7445. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7446. if ( geometryAttribute === true ) {
  7447. const attribute = builder.geometry.getAttribute( attributeName );
  7448. const attributeType = builder.getTypeFromAttribute( attribute );
  7449. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7450. if ( builder.shaderStage === 'vertex' ) {
  7451. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7452. } else {
  7453. const nodeVarying = varying( this );
  7454. return nodeVarying.build( builder, nodeType );
  7455. }
  7456. } else {
  7457. warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7458. return builder.generateConst( nodeType );
  7459. }
  7460. }
  7461. serialize( data ) {
  7462. super.serialize( data );
  7463. data.global = this.global;
  7464. data._attributeName = this._attributeName;
  7465. }
  7466. deserialize( data ) {
  7467. super.deserialize( data );
  7468. this.global = data.global;
  7469. this._attributeName = data._attributeName;
  7470. }
  7471. }
  7472. /**
  7473. * TSL function for creating an attribute node.
  7474. *
  7475. * @tsl
  7476. * @function
  7477. * @param {string} name - The name of the attribute.
  7478. * @param {?string} [nodeType=null] - The node type.
  7479. * @returns {AttributeNode}
  7480. */
  7481. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7482. /**
  7483. * TSL function for creating an uv attribute node with the given index.
  7484. *
  7485. * @tsl
  7486. * @function
  7487. * @param {number} [index=0] - The uv index.
  7488. * @return {AttributeNode<vec2>} The uv attribute node.
  7489. */
  7490. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7491. /**
  7492. * A node that represents the dimensions of a texture. The texture size is
  7493. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7494. * or `textureSize()`.
  7495. *
  7496. * @augments Node
  7497. */
  7498. class TextureSizeNode extends Node {
  7499. static get type() {
  7500. return 'TextureSizeNode';
  7501. }
  7502. /**
  7503. * Constructs a new texture size node.
  7504. *
  7505. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7506. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7507. */
  7508. constructor( textureNode, levelNode = null ) {
  7509. super( 'uvec2' );
  7510. /**
  7511. * This flag can be used for type testing.
  7512. *
  7513. * @type {boolean}
  7514. * @readonly
  7515. * @default true
  7516. */
  7517. this.isTextureSizeNode = true;
  7518. /**
  7519. * A texture node which size should be retrieved.
  7520. *
  7521. * @type {TextureNode}
  7522. */
  7523. this.textureNode = textureNode;
  7524. /**
  7525. * A level node which defines the requested mip.
  7526. *
  7527. * @type {Node<int>}
  7528. * @default null
  7529. */
  7530. this.levelNode = levelNode;
  7531. }
  7532. generate( builder, output ) {
  7533. const textureProperty = this.textureNode.build( builder, 'property' );
  7534. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7535. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7536. }
  7537. }
  7538. /**
  7539. * TSL function for creating a texture size node.
  7540. *
  7541. * @tsl
  7542. * @function
  7543. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7544. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7545. * @returns {TextureSizeNode}
  7546. */
  7547. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7548. /**
  7549. * A special type of uniform node that computes the
  7550. * maximum mipmap level for a given texture node.
  7551. *
  7552. * ```js
  7553. * const level = maxMipLevel( textureNode );
  7554. * ```
  7555. *
  7556. * @augments UniformNode
  7557. */
  7558. class MaxMipLevelNode extends UniformNode {
  7559. static get type() {
  7560. return 'MaxMipLevelNode';
  7561. }
  7562. /**
  7563. * Constructs a new max mip level node.
  7564. *
  7565. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7566. */
  7567. constructor( textureNode ) {
  7568. super( 0 );
  7569. /**
  7570. * The texture node to compute the max mip level for.
  7571. *
  7572. * @private
  7573. * @type {TextureNode}
  7574. */
  7575. this._textureNode = textureNode;
  7576. /**
  7577. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7578. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7579. *
  7580. * @type {string}
  7581. * @default 'frame'
  7582. */
  7583. this.updateType = NodeUpdateType.FRAME;
  7584. }
  7585. /**
  7586. * The texture node to compute the max mip level for.
  7587. *
  7588. * @readonly
  7589. * @type {TextureNode}
  7590. */
  7591. get textureNode() {
  7592. return this._textureNode;
  7593. }
  7594. /**
  7595. * The texture.
  7596. *
  7597. * @readonly
  7598. * @type {Texture}
  7599. */
  7600. get texture() {
  7601. return this._textureNode.value;
  7602. }
  7603. update() {
  7604. const texture = this.texture;
  7605. const images = texture.images;
  7606. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7607. if ( image && image.width !== undefined ) {
  7608. const { width, height } = image;
  7609. this.value = Math.log2( Math.max( width, height ) );
  7610. }
  7611. }
  7612. }
  7613. /**
  7614. * TSL function for creating a max mip level node.
  7615. *
  7616. * @tsl
  7617. * @function
  7618. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7619. * @returns {MaxMipLevelNode}
  7620. */
  7621. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7622. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7623. /**
  7624. * This type of uniform node represents a 2D texture.
  7625. *
  7626. * @augments UniformNode
  7627. */
  7628. class TextureNode extends UniformNode {
  7629. static get type() {
  7630. return 'TextureNode';
  7631. }
  7632. /**
  7633. * Constructs a new texture node.
  7634. *
  7635. * @param {Texture} [value=EmptyTexture] - The texture.
  7636. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7637. * @param {?Node<int>} [levelNode=null] - The level node.
  7638. * @param {?Node<float>} [biasNode=null] - The bias node.
  7639. */
  7640. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7641. super( value );
  7642. /**
  7643. * This flag can be used for type testing.
  7644. *
  7645. * @type {boolean}
  7646. * @readonly
  7647. * @default true
  7648. */
  7649. this.isTextureNode = true;
  7650. /**
  7651. * Represents the texture coordinates.
  7652. *
  7653. * @type {?Node<vec2|vec3>}
  7654. * @default null
  7655. */
  7656. this.uvNode = uvNode;
  7657. /**
  7658. * Represents the mip level that should be selected.
  7659. *
  7660. * @type {?Node<int>}
  7661. * @default null
  7662. */
  7663. this.levelNode = levelNode;
  7664. /**
  7665. * Represents the bias to be applied during level-of-detail computation.
  7666. *
  7667. * @type {?Node<float>}
  7668. * @default null
  7669. */
  7670. this.biasNode = biasNode;
  7671. /**
  7672. * Represents a reference value a texture sample is compared to.
  7673. *
  7674. * @type {?Node<float>}
  7675. * @default null
  7676. */
  7677. this.compareNode = null;
  7678. /**
  7679. * When using texture arrays, the depth node defines the layer to select.
  7680. *
  7681. * @type {?Node<int>}
  7682. * @default null
  7683. */
  7684. this.depthNode = null;
  7685. /**
  7686. * When defined, a texture is sampled using explicit gradients.
  7687. *
  7688. * @type {?Array<Node<vec2>>}
  7689. * @default null
  7690. */
  7691. this.gradNode = null;
  7692. /**
  7693. * Represents the optional texel offset applied to the unnormalized texture
  7694. * coordinate before sampling the texture.
  7695. *
  7696. * @type {?Node<ivec2|ivec3>}
  7697. * @default null
  7698. */
  7699. this.offsetNode = null;
  7700. /**
  7701. * Whether texture values should be sampled or fetched.
  7702. *
  7703. * @type {boolean}
  7704. * @default true
  7705. */
  7706. this.sampler = true;
  7707. /**
  7708. * Whether the uv transformation matrix should be
  7709. * automatically updated or not. Use `setUpdateMatrix()`
  7710. * if you want to change the value of the property.
  7711. *
  7712. * @type {boolean}
  7713. * @default false
  7714. */
  7715. this.updateMatrix = false;
  7716. /**
  7717. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7718. * sets the value to `frame` when the uv transformation matrix should
  7719. * automatically be updated.
  7720. *
  7721. * @type {string}
  7722. * @default 'none'
  7723. */
  7724. this.updateType = NodeUpdateType.NONE;
  7725. /**
  7726. * The reference node.
  7727. *
  7728. * @type {?Node}
  7729. * @default null
  7730. */
  7731. this.referenceNode = null;
  7732. /**
  7733. * The texture value is stored in a private property.
  7734. *
  7735. * @private
  7736. * @type {Texture}
  7737. */
  7738. this._value = value;
  7739. /**
  7740. * The uniform node that represents the uv transformation matrix.
  7741. *
  7742. * @private
  7743. * @type {?UniformNode<mat3>}
  7744. */
  7745. this._matrixUniform = null;
  7746. this.setUpdateMatrix( uvNode === null );
  7747. }
  7748. set value( value ) {
  7749. if ( this.referenceNode ) {
  7750. this.referenceNode.value = value;
  7751. } else {
  7752. this._value = value;
  7753. }
  7754. }
  7755. /**
  7756. * The texture value.
  7757. *
  7758. * @type {Texture}
  7759. */
  7760. get value() {
  7761. return this.referenceNode ? this.referenceNode.value : this._value;
  7762. }
  7763. /**
  7764. * Overwritten since the uniform hash is defined by the texture's UUID.
  7765. *
  7766. * @param {NodeBuilder} builder - The current node builder.
  7767. * @return {string} The uniform hash.
  7768. */
  7769. getUniformHash( /*builder*/ ) {
  7770. return this.value.uuid;
  7771. }
  7772. /**
  7773. * Overwritten since the node type is inferred from the texture type.
  7774. *
  7775. * @param {NodeBuilder} builder - The current node builder.
  7776. * @return {string} The node type.
  7777. */
  7778. getNodeType( /*builder*/ ) {
  7779. if ( this.value.isDepthTexture === true ) return 'float';
  7780. if ( this.value.type === UnsignedIntType ) {
  7781. return 'uvec4';
  7782. } else if ( this.value.type === IntType ) {
  7783. return 'ivec4';
  7784. }
  7785. return 'vec4';
  7786. }
  7787. /**
  7788. * Overwrites the default implementation to return a fixed value `'texture'`.
  7789. *
  7790. * @param {NodeBuilder} builder - The current node builder.
  7791. * @return {string} The input type.
  7792. */
  7793. getInputType( /*builder*/ ) {
  7794. return 'texture';
  7795. }
  7796. /**
  7797. * Returns a default uvs based on the current texture's channel.
  7798. *
  7799. * @return {AttributeNode<vec2>} The default uvs.
  7800. */
  7801. getDefaultUV() {
  7802. return uv$1( this.value.channel );
  7803. }
  7804. /**
  7805. * Overwritten to always return the texture reference of the node.
  7806. *
  7807. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7808. * @return {Texture} The texture reference.
  7809. */
  7810. updateReference( /*state*/ ) {
  7811. return this.value;
  7812. }
  7813. /**
  7814. * Transforms the given uv node with the texture transformation matrix.
  7815. *
  7816. * @param {Node} uvNode - The uv node to transform.
  7817. * @return {Node} The transformed uv node.
  7818. */
  7819. getTransformedUV( uvNode ) {
  7820. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7821. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7822. }
  7823. /**
  7824. * Defines whether the uv transformation matrix should automatically be updated or not.
  7825. *
  7826. * @param {boolean} value - The update toggle.
  7827. * @return {TextureNode} A reference to this node.
  7828. */
  7829. setUpdateMatrix( value ) {
  7830. this.updateMatrix = value;
  7831. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7832. return this;
  7833. }
  7834. /**
  7835. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7836. * to modify the uv node for correct sampling.
  7837. *
  7838. * @param {NodeBuilder} builder - The current node builder.
  7839. * @param {Node} uvNode - The uv node to setup.
  7840. * @return {Node} The updated uv node.
  7841. */
  7842. setupUV( builder, uvNode ) {
  7843. const texture = this.value;
  7844. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7845. if ( this.sampler ) {
  7846. uvNode = uvNode.flipY();
  7847. } else {
  7848. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7849. }
  7850. }
  7851. return uvNode;
  7852. }
  7853. /**
  7854. * Setups texture node by preparing the internal nodes for code generation.
  7855. *
  7856. * @param {NodeBuilder} builder - The current node builder.
  7857. */
  7858. setup( builder ) {
  7859. const properties = builder.getNodeProperties( this );
  7860. properties.referenceNode = this.referenceNode;
  7861. //
  7862. const texture = this.value;
  7863. if ( ! texture || texture.isTexture !== true ) {
  7864. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7865. }
  7866. //
  7867. let uvNode = this.uvNode;
  7868. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7869. uvNode = builder.context.getUV( this, builder );
  7870. }
  7871. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7872. if ( this.updateMatrix === true ) {
  7873. uvNode = this.getTransformedUV( uvNode );
  7874. }
  7875. uvNode = this.setupUV( builder, uvNode );
  7876. //
  7877. let levelNode = this.levelNode;
  7878. if ( levelNode === null && builder.context.getTextureLevel ) {
  7879. levelNode = builder.context.getTextureLevel( this );
  7880. }
  7881. //
  7882. properties.uvNode = uvNode;
  7883. properties.levelNode = levelNode;
  7884. properties.biasNode = this.biasNode;
  7885. properties.compareNode = this.compareNode;
  7886. properties.gradNode = this.gradNode;
  7887. properties.depthNode = this.depthNode;
  7888. properties.offsetNode = this.offsetNode;
  7889. }
  7890. /**
  7891. * Generates the uv code snippet.
  7892. *
  7893. * @param {NodeBuilder} builder - The current node builder.
  7894. * @param {Node} uvNode - The uv node to generate code for.
  7895. * @return {string} The generated code snippet.
  7896. */
  7897. generateUV( builder, uvNode ) {
  7898. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7899. }
  7900. /**
  7901. * Generates the offset code snippet.
  7902. *
  7903. * @param {NodeBuilder} builder - The current node builder.
  7904. * @param {Node} offsetNode - The offset node to generate code for.
  7905. * @return {string} The generated code snippet.
  7906. */
  7907. generateOffset( builder, offsetNode ) {
  7908. return offsetNode.build( builder, 'ivec2' );
  7909. }
  7910. /**
  7911. * Generates the snippet for the texture sampling.
  7912. *
  7913. * @param {NodeBuilder} builder - The current node builder.
  7914. * @param {string} textureProperty - The texture property.
  7915. * @param {string} uvSnippet - The uv snippet.
  7916. * @param {?string} levelSnippet - The level snippet.
  7917. * @param {?string} biasSnippet - The bias snippet.
  7918. * @param {?string} depthSnippet - The depth snippet.
  7919. * @param {?string} compareSnippet - The compare snippet.
  7920. * @param {?Array<string>} gradSnippet - The grad snippet.
  7921. * @param {?string} offsetSnippet - The offset snippet.
  7922. * @return {string} The generated code snippet.
  7923. */
  7924. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  7925. const texture = this.value;
  7926. let snippet;
  7927. if ( biasSnippet ) {
  7928. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  7929. } else if ( gradSnippet ) {
  7930. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  7931. } else if ( compareSnippet ) {
  7932. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  7933. } else if ( this.sampler === false ) {
  7934. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  7935. } else if ( levelSnippet ) {
  7936. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  7937. } else {
  7938. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  7939. }
  7940. return snippet;
  7941. }
  7942. /**
  7943. * Generates the code snippet of the texture node.
  7944. *
  7945. * @param {NodeBuilder} builder - The current node builder.
  7946. * @param {string} output - The current output.
  7947. * @return {string} The generated code snippet.
  7948. */
  7949. generate( builder, output ) {
  7950. const texture = this.value;
  7951. const properties = builder.getNodeProperties( this );
  7952. const textureProperty = super.generate( builder, 'property' );
  7953. if ( /^sampler/.test( output ) ) {
  7954. return textureProperty + '_sampler';
  7955. } else if ( builder.isReference( output ) ) {
  7956. return textureProperty;
  7957. } else {
  7958. const nodeData = builder.getDataFromNode( this );
  7959. let propertyName = nodeData.propertyName;
  7960. if ( propertyName === undefined ) {
  7961. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  7962. const uvSnippet = this.generateUV( builder, uvNode );
  7963. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7964. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7965. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7966. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7967. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7968. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  7969. const nodeVar = builder.getVarFromNode( this );
  7970. propertyName = builder.getPropertyName( nodeVar );
  7971. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  7972. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7973. nodeData.snippet = snippet;
  7974. nodeData.propertyName = propertyName;
  7975. }
  7976. let snippet = propertyName;
  7977. const nodeType = this.getNodeType( builder );
  7978. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7979. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7980. }
  7981. return builder.format( snippet, nodeType, output );
  7982. }
  7983. }
  7984. /**
  7985. * Sets the sampler value.
  7986. *
  7987. * @param {boolean} value - The sampler value to set.
  7988. * @return {TextureNode} A reference to this texture node.
  7989. */
  7990. setSampler( value ) {
  7991. this.sampler = value;
  7992. return this;
  7993. }
  7994. /**
  7995. * Returns the sampler value.
  7996. *
  7997. * @return {boolean} The sampler value.
  7998. */
  7999. getSampler() {
  8000. return this.sampler;
  8001. }
  8002. // @TODO: Move to TSL
  8003. /**
  8004. * @function
  8005. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  8006. *
  8007. * @param {Node} uvNode - The uv node.
  8008. * @return {TextureNode} A texture node representing the texture sample.
  8009. */
  8010. uv( uvNode ) { // @deprecated, r172
  8011. warn( 'TextureNode: .uv() has been renamed. Use .sample() instead.' );
  8012. return this.sample( uvNode );
  8013. }
  8014. /**
  8015. * Samples the texture with the given uv node.
  8016. *
  8017. * @param {Node} uvNode - The uv node.
  8018. * @return {TextureNode} A texture node representing the texture sample.
  8019. */
  8020. sample( uvNode ) {
  8021. const textureNode = this.clone();
  8022. textureNode.uvNode = nodeObject( uvNode );
  8023. textureNode.referenceNode = this.getBase();
  8024. return nodeObject( textureNode );
  8025. }
  8026. /**
  8027. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8028. *
  8029. * @param {Node<uvec2>} uvNode - The uv node.
  8030. * @returns {TextureNode} A texture node representing the texture load.
  8031. */
  8032. load( uvNode ) {
  8033. return this.sample( uvNode ).setSampler( false );
  8034. }
  8035. /**
  8036. * Samples a blurred version of the texture by defining an internal bias.
  8037. *
  8038. * @param {Node<float>} amountNode - How blurred the texture should be.
  8039. * @return {TextureNode} A texture node representing the texture sample.
  8040. */
  8041. blur( amountNode ) {
  8042. const textureNode = this.clone();
  8043. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8044. textureNode.referenceNode = this.getBase();
  8045. const map = textureNode.value;
  8046. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8047. warn( 'TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8048. textureNode.biasNode = null;
  8049. }
  8050. return nodeObject( textureNode );
  8051. }
  8052. /**
  8053. * Samples a specific mip of the texture.
  8054. *
  8055. * @param {Node<int>} levelNode - The mip level to sample.
  8056. * @return {TextureNode} A texture node representing the texture sample.
  8057. */
  8058. level( levelNode ) {
  8059. const textureNode = this.clone();
  8060. textureNode.levelNode = nodeObject( levelNode );
  8061. textureNode.referenceNode = this.getBase();
  8062. return nodeObject( textureNode );
  8063. }
  8064. /**
  8065. * Returns the texture size of the requested level.
  8066. *
  8067. * @param {Node<int>} levelNode - The level to compute the size for.
  8068. * @return {TextureSizeNode} The texture size.
  8069. */
  8070. size( levelNode ) {
  8071. return textureSize( this, levelNode );
  8072. }
  8073. /**
  8074. * Samples the texture with the given bias.
  8075. *
  8076. * @param {Node<float>} biasNode - The bias node.
  8077. * @return {TextureNode} A texture node representing the texture sample.
  8078. */
  8079. bias( biasNode ) {
  8080. const textureNode = this.clone();
  8081. textureNode.biasNode = nodeObject( biasNode );
  8082. textureNode.referenceNode = this.getBase();
  8083. return nodeObject( textureNode );
  8084. }
  8085. /**
  8086. * Returns the base texture of this node.
  8087. * @return {TextureNode} The base texture node.
  8088. */
  8089. getBase() {
  8090. return this.referenceNode ? this.referenceNode.getBase() : this;
  8091. }
  8092. /**
  8093. * Samples the texture by executing a compare operation.
  8094. *
  8095. * @param {Node<float>} compareNode - The node that defines the compare value.
  8096. * @return {TextureNode} A texture node representing the texture sample.
  8097. */
  8098. compare( compareNode ) {
  8099. const textureNode = this.clone();
  8100. textureNode.compareNode = nodeObject( compareNode );
  8101. textureNode.referenceNode = this.getBase();
  8102. return nodeObject( textureNode );
  8103. }
  8104. /**
  8105. * Samples the texture using an explicit gradient.
  8106. *
  8107. * @param {Node<vec2>} gradNodeX - The gradX node.
  8108. * @param {Node<vec2>} gradNodeY - The gradY node.
  8109. * @return {TextureNode} A texture node representing the texture sample.
  8110. */
  8111. grad( gradNodeX, gradNodeY ) {
  8112. const textureNode = this.clone();
  8113. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8114. textureNode.referenceNode = this.getBase();
  8115. return nodeObject( textureNode );
  8116. }
  8117. /**
  8118. * Samples the texture by defining a depth node.
  8119. *
  8120. * @param {Node<int>} depthNode - The depth node.
  8121. * @return {TextureNode} A texture node representing the texture sample.
  8122. */
  8123. depth( depthNode ) {
  8124. const textureNode = this.clone();
  8125. textureNode.depthNode = nodeObject( depthNode );
  8126. textureNode.referenceNode = this.getBase();
  8127. return nodeObject( textureNode );
  8128. }
  8129. /**
  8130. * Samples the texture by defining an offset node.
  8131. *
  8132. * @param {Node<ivec2>} offsetNode - The offset node.
  8133. * @return {TextureNode} A texture node representing the texture sample.
  8134. */
  8135. offset( offsetNode ) {
  8136. const textureNode = this.clone();
  8137. textureNode.offsetNode = nodeObject( offsetNode );
  8138. textureNode.referenceNode = this.getBase();
  8139. return nodeObject( textureNode );
  8140. }
  8141. // --
  8142. serialize( data ) {
  8143. super.serialize( data );
  8144. data.value = this.value.toJSON( data.meta ).uuid;
  8145. data.sampler = this.sampler;
  8146. data.updateMatrix = this.updateMatrix;
  8147. data.updateType = this.updateType;
  8148. }
  8149. deserialize( data ) {
  8150. super.deserialize( data );
  8151. this.value = data.meta.textures[ data.value ];
  8152. this.sampler = data.sampler;
  8153. this.updateMatrix = data.updateMatrix;
  8154. this.updateType = data.updateType;
  8155. }
  8156. /**
  8157. * The update is used to implement the update of the uv transformation matrix.
  8158. */
  8159. update() {
  8160. const texture = this.value;
  8161. const matrixUniform = this._matrixUniform;
  8162. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8163. if ( texture.matrixAutoUpdate === true ) {
  8164. texture.updateMatrix();
  8165. }
  8166. }
  8167. /**
  8168. * Clones the texture node.
  8169. *
  8170. * @return {TextureNode} The cloned texture node.
  8171. */
  8172. clone() {
  8173. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8174. newNode.sampler = this.sampler;
  8175. newNode.depthNode = this.depthNode;
  8176. newNode.compareNode = this.compareNode;
  8177. newNode.gradNode = this.gradNode;
  8178. newNode.offsetNode = this.offsetNode;
  8179. return newNode;
  8180. }
  8181. }
  8182. /**
  8183. * TSL function for creating a texture node.
  8184. *
  8185. * @tsl
  8186. * @function
  8187. * @param {?Texture} value - The texture.
  8188. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8189. * @param {?Node<int>} [levelNode=null] - The level node.
  8190. * @param {?Node<float>} [biasNode=null] - The bias node.
  8191. * @returns {TextureNode}
  8192. */
  8193. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8194. /**
  8195. * TSL function for creating a texture node or sample a texture node already existing.
  8196. *
  8197. * @tsl
  8198. * @function
  8199. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8200. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8201. * @param {?Node<int>} [levelNode=null] - The level node.
  8202. * @param {?Node<float>} [biasNode=null] - The bias node.
  8203. * @returns {TextureNode}
  8204. */
  8205. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8206. let textureNode;
  8207. if ( value && value.isTextureNode === true ) {
  8208. textureNode = nodeObject( value.clone() );
  8209. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8210. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8211. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8212. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8213. } else {
  8214. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8215. }
  8216. return textureNode;
  8217. };
  8218. /**
  8219. * TSL function for creating a uniform texture node.
  8220. *
  8221. * @tsl
  8222. * @function
  8223. * @param {?Texture} value - The texture.
  8224. * @returns {TextureNode}
  8225. */
  8226. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8227. /**
  8228. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8229. *
  8230. * @tsl
  8231. * @function
  8232. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8233. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8234. * @param {?Node<int>} [levelNode=null] - The level node.
  8235. * @param {?Node<float>} [biasNode=null] - The bias node.
  8236. * @returns {TextureNode}
  8237. */
  8238. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8239. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8240. /**
  8241. * Converts a texture or texture node to a sampler.
  8242. *
  8243. * @tsl
  8244. * @function
  8245. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8246. * @returns {Node}
  8247. */
  8248. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8249. /**
  8250. * Converts a texture or texture node to a sampler comparison.
  8251. *
  8252. * @tsl
  8253. * @function
  8254. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8255. * @returns {Node}
  8256. */
  8257. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8258. /**
  8259. * A special type of uniform node which represents array-like data
  8260. * as uniform buffers. The access usually happens via `element()`
  8261. * which returns an instance of {@link ArrayElementNode}. For example:
  8262. *
  8263. * ```js
  8264. * const bufferNode = buffer( array, 'mat4', count );
  8265. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8266. * ```
  8267. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8268. * since it handles more input types and automatically cares about buffer paddings.
  8269. *
  8270. * @augments UniformNode
  8271. */
  8272. class BufferNode extends UniformNode {
  8273. static get type() {
  8274. return 'BufferNode';
  8275. }
  8276. /**
  8277. * Constructs a new buffer node.
  8278. *
  8279. * @param {Array<number>} value - Array-like buffer data.
  8280. * @param {string} bufferType - The data type of the buffer.
  8281. * @param {number} [bufferCount=0] - The count of buffer elements.
  8282. */
  8283. constructor( value, bufferType, bufferCount = 0 ) {
  8284. super( value, bufferType );
  8285. /**
  8286. * This flag can be used for type testing.
  8287. *
  8288. * @type {boolean}
  8289. * @readonly
  8290. * @default true
  8291. */
  8292. this.isBufferNode = true;
  8293. /**
  8294. * The data type of the buffer.
  8295. *
  8296. * @type {string}
  8297. */
  8298. this.bufferType = bufferType;
  8299. /**
  8300. * The uniform node that holds the value of the reference node.
  8301. *
  8302. * @type {number}
  8303. * @default 0
  8304. */
  8305. this.bufferCount = bufferCount;
  8306. }
  8307. /**
  8308. * The data type of the buffer elements.
  8309. *
  8310. * @param {NodeBuilder} builder - The current node builder.
  8311. * @return {string} The element type.
  8312. */
  8313. getElementType( builder ) {
  8314. return this.getNodeType( builder );
  8315. }
  8316. /**
  8317. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8318. *
  8319. * @param {NodeBuilder} builder - The current node builder.
  8320. * @return {string} The input type.
  8321. */
  8322. getInputType( /*builder*/ ) {
  8323. return 'buffer';
  8324. }
  8325. }
  8326. /**
  8327. * TSL function for creating a buffer node.
  8328. *
  8329. * @tsl
  8330. * @function
  8331. * @param {Array<number>} value - Array-like buffer data.
  8332. * @param {string} type - The data type of a buffer element.
  8333. * @param {number} count - The count of buffer elements.
  8334. * @returns {BufferNode}
  8335. */
  8336. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8337. /**
  8338. * Represents the element access on uniform array nodes.
  8339. *
  8340. * @augments ArrayElementNode
  8341. */
  8342. class UniformArrayElementNode extends ArrayElementNode {
  8343. static get type() {
  8344. return 'UniformArrayElementNode';
  8345. }
  8346. /**
  8347. * Constructs a new buffer node.
  8348. *
  8349. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8350. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8351. */
  8352. constructor( uniformArrayNode, indexNode ) {
  8353. super( uniformArrayNode, indexNode );
  8354. /**
  8355. * This flag can be used for type testing.
  8356. *
  8357. * @type {boolean}
  8358. * @readonly
  8359. * @default true
  8360. */
  8361. this.isArrayBufferElementNode = true;
  8362. }
  8363. generate( builder ) {
  8364. const snippet = super.generate( builder );
  8365. const type = this.getNodeType();
  8366. const paddedType = this.node.getPaddedType();
  8367. return builder.format( snippet, paddedType, type );
  8368. }
  8369. }
  8370. /**
  8371. * Similar to {@link BufferNode} this module represents array-like data as
  8372. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8373. * data types in the array (e.g `three.js` primitives) and automatically
  8374. * manage buffer padding. It should be the first choice when working with
  8375. * uniforms buffers.
  8376. * ```js
  8377. * const tintColors = uniformArray( [
  8378. * new Color( 1, 0, 0 ),
  8379. * new Color( 0, 1, 0 ),
  8380. * new Color( 0, 0, 1 )
  8381. * ], 'color' );
  8382. *
  8383. * const redColor = tintColors.element( 0 );
  8384. *
  8385. * @augments BufferNode
  8386. */
  8387. class UniformArrayNode extends BufferNode {
  8388. static get type() {
  8389. return 'UniformArrayNode';
  8390. }
  8391. /**
  8392. * Constructs a new uniform array node.
  8393. *
  8394. * @param {Array<any>} value - Array holding the buffer data.
  8395. * @param {?string} [elementType=null] - The data type of a buffer element.
  8396. */
  8397. constructor( value, elementType = null ) {
  8398. super( null );
  8399. /**
  8400. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8401. * hold number primitives as well as three.js objects like vectors, matrices
  8402. * or colors.
  8403. *
  8404. * @type {Array<any>}
  8405. */
  8406. this.array = value;
  8407. /**
  8408. * The data type of an array element.
  8409. *
  8410. * @type {string}
  8411. */
  8412. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8413. /**
  8414. * The padded type. Uniform buffers must conform to a certain buffer layout
  8415. * so a separate type is computed to ensure correct buffer size.
  8416. *
  8417. * @type {string}
  8418. */
  8419. this.paddedType = this.getPaddedType();
  8420. /**
  8421. * Overwritten since uniform array nodes are updated per render.
  8422. *
  8423. * @type {string}
  8424. * @default 'render'
  8425. */
  8426. this.updateType = NodeUpdateType.RENDER;
  8427. /**
  8428. * This flag can be used for type testing.
  8429. *
  8430. * @type {boolean}
  8431. * @readonly
  8432. * @default true
  8433. */
  8434. this.isArrayBufferNode = true;
  8435. }
  8436. /**
  8437. * This method is overwritten since the node type is inferred from the
  8438. * {@link UniformArrayNode#paddedType}.
  8439. *
  8440. * @param {NodeBuilder} builder - The current node builder.
  8441. * @return {string} The node type.
  8442. */
  8443. getNodeType( /*builder*/ ) {
  8444. return this.paddedType;
  8445. }
  8446. /**
  8447. * The data type of the array elements.
  8448. *
  8449. * @param {NodeBuilder} builder - The current node builder.
  8450. * @return {string} The element type.
  8451. */
  8452. getElementType() {
  8453. return this.elementType;
  8454. }
  8455. /**
  8456. * Returns the padded type based on the element type.
  8457. *
  8458. * @return {string} The padded type.
  8459. */
  8460. getPaddedType() {
  8461. const elementType = this.elementType;
  8462. let paddedType = 'vec4';
  8463. if ( elementType === 'mat2' ) {
  8464. paddedType = 'mat2';
  8465. } else if ( /mat/.test( elementType ) === true ) {
  8466. paddedType = 'mat4';
  8467. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8468. paddedType = 'ivec4';
  8469. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8470. paddedType = 'uvec4';
  8471. }
  8472. return paddedType;
  8473. }
  8474. /**
  8475. * The update makes sure to correctly transfer the data from the (complex) objects
  8476. * in the array to the internal, correctly padded value buffer.
  8477. *
  8478. * @param {NodeFrame} frame - A reference to the current node frame.
  8479. */
  8480. update( /*frame*/ ) {
  8481. const { array, value } = this;
  8482. const elementType = this.elementType;
  8483. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8484. for ( let i = 0; i < array.length; i ++ ) {
  8485. const index = i * 4;
  8486. value[ index ] = array[ i ];
  8487. }
  8488. } else if ( elementType === 'color' ) {
  8489. for ( let i = 0; i < array.length; i ++ ) {
  8490. const index = i * 4;
  8491. const vector = array[ i ];
  8492. value[ index ] = vector.r;
  8493. value[ index + 1 ] = vector.g;
  8494. value[ index + 2 ] = vector.b || 0;
  8495. //value[ index + 3 ] = vector.a || 0;
  8496. }
  8497. } else if ( elementType === 'mat2' ) {
  8498. for ( let i = 0; i < array.length; i ++ ) {
  8499. const index = i * 4;
  8500. const matrix = array[ i ];
  8501. value[ index ] = matrix.elements[ 0 ];
  8502. value[ index + 1 ] = matrix.elements[ 1 ];
  8503. value[ index + 2 ] = matrix.elements[ 2 ];
  8504. value[ index + 3 ] = matrix.elements[ 3 ];
  8505. }
  8506. } else if ( elementType === 'mat3' ) {
  8507. for ( let i = 0; i < array.length; i ++ ) {
  8508. const index = i * 16;
  8509. const matrix = array[ i ];
  8510. value[ index ] = matrix.elements[ 0 ];
  8511. value[ index + 1 ] = matrix.elements[ 1 ];
  8512. value[ index + 2 ] = matrix.elements[ 2 ];
  8513. value[ index + 4 ] = matrix.elements[ 3 ];
  8514. value[ index + 5 ] = matrix.elements[ 4 ];
  8515. value[ index + 6 ] = matrix.elements[ 5 ];
  8516. value[ index + 8 ] = matrix.elements[ 6 ];
  8517. value[ index + 9 ] = matrix.elements[ 7 ];
  8518. value[ index + 10 ] = matrix.elements[ 8 ];
  8519. value[ index + 15 ] = 1;
  8520. }
  8521. } else if ( elementType === 'mat4' ) {
  8522. for ( let i = 0; i < array.length; i ++ ) {
  8523. const index = i * 16;
  8524. const matrix = array[ i ];
  8525. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8526. value[ index + i ] = matrix.elements[ i ];
  8527. }
  8528. }
  8529. } else {
  8530. for ( let i = 0; i < array.length; i ++ ) {
  8531. const index = i * 4;
  8532. const vector = array[ i ];
  8533. value[ index ] = vector.x;
  8534. value[ index + 1 ] = vector.y;
  8535. value[ index + 2 ] = vector.z || 0;
  8536. value[ index + 3 ] = vector.w || 0;
  8537. }
  8538. }
  8539. }
  8540. /**
  8541. * Implement the value buffer creation based on the array data.
  8542. *
  8543. * @param {NodeBuilder} builder - A reference to the current node builder.
  8544. * @return {null}
  8545. */
  8546. setup( builder ) {
  8547. const length = this.array.length;
  8548. const elementType = this.elementType;
  8549. let arrayType = Float32Array;
  8550. const paddedType = this.paddedType;
  8551. const paddedElementLength = builder.getTypeLength( paddedType );
  8552. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8553. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8554. this.value = new arrayType( length * paddedElementLength );
  8555. this.bufferCount = length;
  8556. this.bufferType = paddedType;
  8557. return super.setup( builder );
  8558. }
  8559. /**
  8560. * Overwrites the default `element()` method to provide element access
  8561. * based on {@link UniformArrayNode}.
  8562. *
  8563. * @param {IndexNode} indexNode - The index node.
  8564. * @return {UniformArrayElementNode}
  8565. */
  8566. element( indexNode ) {
  8567. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8568. }
  8569. }
  8570. /**
  8571. * TSL function for creating an uniform array node.
  8572. *
  8573. * @tsl
  8574. * @function
  8575. * @param {Array<any>} values - Array-like data.
  8576. * @param {?string} [nodeType] - The data type of the array elements.
  8577. * @returns {UniformArrayNode}
  8578. */
  8579. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8580. /**
  8581. * The node allows to set values for built-in shader variables. That is
  8582. * required for features like hardware-accelerated vertex clipping.
  8583. *
  8584. * @augments Node
  8585. */
  8586. class BuiltinNode extends Node {
  8587. /**
  8588. * Constructs a new builtin node.
  8589. *
  8590. * @param {string} name - The name of the built-in shader variable.
  8591. */
  8592. constructor( name ) {
  8593. super( 'float' );
  8594. /**
  8595. * The name of the built-in shader variable.
  8596. *
  8597. * @type {string}
  8598. */
  8599. this.name = name;
  8600. /**
  8601. * This flag can be used for type testing.
  8602. *
  8603. * @type {boolean}
  8604. * @readonly
  8605. * @default true
  8606. */
  8607. this.isBuiltinNode = true;
  8608. }
  8609. /**
  8610. * Generates the code snippet of the builtin node.
  8611. *
  8612. * @param {NodeBuilder} builder - The current node builder.
  8613. * @return {string} The generated code snippet.
  8614. */
  8615. generate( /* builder */ ) {
  8616. return this.name;
  8617. }
  8618. }
  8619. /**
  8620. * TSL function for creating a builtin node.
  8621. *
  8622. * @tsl
  8623. * @function
  8624. * @param {string} name - The name of the built-in shader variable.
  8625. * @returns {BuiltinNode}
  8626. */
  8627. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8628. let _screenSizeVec, _viewportVec;
  8629. /**
  8630. * This node provides a collection of screen related metrics.
  8631. * Depending on {@link ScreenNode#scope}, the nodes can represent
  8632. * resolution or viewport data as well as fragment or uv coordinates.
  8633. *
  8634. * @augments Node
  8635. */
  8636. class ScreenNode extends Node {
  8637. static get type() {
  8638. return 'ScreenNode';
  8639. }
  8640. /**
  8641. * Constructs a new screen node.
  8642. *
  8643. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  8644. */
  8645. constructor( scope ) {
  8646. super();
  8647. /**
  8648. * The node represents different metric depending on which scope is selected.
  8649. *
  8650. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  8651. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  8652. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  8653. * - `ScreenNode.UV`: Normalized coordinates.
  8654. * - `ScreenNode.DPR`: Device pixel ratio.
  8655. *
  8656. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  8657. */
  8658. this.scope = scope;
  8659. /**
  8660. * This output node.
  8661. *
  8662. * @type {?Node}
  8663. * @default null
  8664. */
  8665. this._output = null;
  8666. /**
  8667. * This flag can be used for type testing.
  8668. *
  8669. * @type {boolean}
  8670. * @readonly
  8671. * @default true
  8672. */
  8673. this.isViewportNode = true;
  8674. }
  8675. /**
  8676. * This method is overwritten since the node type depends on the selected scope.
  8677. *
  8678. * @return {('float'|'vec2'|'vec4')} The node type.
  8679. */
  8680. getNodeType() {
  8681. if ( this.scope === ScreenNode.DPR ) return 'float';
  8682. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  8683. else return 'vec2';
  8684. }
  8685. /**
  8686. * This method is overwritten since the node's update type depends on the selected scope.
  8687. *
  8688. * @return {NodeUpdateType} The update type.
  8689. */
  8690. getUpdateType() {
  8691. let updateType = NodeUpdateType.NONE;
  8692. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  8693. updateType = NodeUpdateType.RENDER;
  8694. }
  8695. this.updateType = updateType;
  8696. return updateType;
  8697. }
  8698. /**
  8699. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  8700. * from the current renderer.
  8701. *
  8702. * @param {NodeFrame} frame - A reference to the current node frame.
  8703. */
  8704. update( { renderer } ) {
  8705. const renderTarget = renderer.getRenderTarget();
  8706. if ( this.scope === ScreenNode.VIEWPORT ) {
  8707. if ( renderTarget !== null ) {
  8708. _viewportVec.copy( renderTarget.viewport );
  8709. } else {
  8710. renderer.getViewport( _viewportVec );
  8711. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  8712. }
  8713. } else if ( this.scope === ScreenNode.DPR ) {
  8714. this._output.value = renderer.getPixelRatio();
  8715. } else {
  8716. if ( renderTarget !== null ) {
  8717. _screenSizeVec.width = renderTarget.width;
  8718. _screenSizeVec.height = renderTarget.height;
  8719. } else {
  8720. renderer.getDrawingBufferSize( _screenSizeVec );
  8721. }
  8722. }
  8723. }
  8724. setup( /*builder*/ ) {
  8725. const scope = this.scope;
  8726. let output = null;
  8727. if ( scope === ScreenNode.SIZE ) {
  8728. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  8729. } else if ( scope === ScreenNode.VIEWPORT ) {
  8730. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  8731. } else if ( scope === ScreenNode.DPR ) {
  8732. output = uniform( 1 );
  8733. } else {
  8734. output = vec2( screenCoordinate.div( screenSize ) );
  8735. }
  8736. this._output = output;
  8737. return output;
  8738. }
  8739. generate( builder ) {
  8740. if ( this.scope === ScreenNode.COORDINATE ) {
  8741. let coord = builder.getFragCoord();
  8742. if ( builder.isFlipY() ) {
  8743. // follow webgpu standards
  8744. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  8745. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  8746. }
  8747. return coord;
  8748. }
  8749. return super.generate( builder );
  8750. }
  8751. }
  8752. ScreenNode.COORDINATE = 'coordinate';
  8753. ScreenNode.VIEWPORT = 'viewport';
  8754. ScreenNode.SIZE = 'size';
  8755. ScreenNode.UV = 'uv';
  8756. ScreenNode.DPR = 'dpr';
  8757. // Screen
  8758. /**
  8759. * TSL object that represents the current DPR.
  8760. *
  8761. * @tsl
  8762. * @type {ScreenNode<float>}
  8763. */
  8764. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  8765. /**
  8766. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  8767. *
  8768. * @tsl
  8769. * @type {ScreenNode<vec2>}
  8770. */
  8771. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  8772. /**
  8773. * TSL object that represents the screen resolution in physical pixel units.
  8774. *
  8775. * @tsl
  8776. * @type {ScreenNode<vec2>}
  8777. */
  8778. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  8779. /**
  8780. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  8781. *
  8782. * @tsl
  8783. * @type {ScreenNode<vec2>}
  8784. */
  8785. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  8786. // Viewport
  8787. /**
  8788. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  8789. *
  8790. * @tsl
  8791. * @type {ScreenNode<vec4>}
  8792. */
  8793. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  8794. /**
  8795. * TSL object that represents the viewport resolution in physical pixel units.
  8796. *
  8797. * @tsl
  8798. * @type {ScreenNode<vec2>}
  8799. */
  8800. const viewportSize = viewport.zw;
  8801. /**
  8802. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  8803. *
  8804. * @tsl
  8805. * @type {ScreenNode<vec2>}
  8806. */
  8807. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  8808. /**
  8809. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  8810. *
  8811. * @tsl
  8812. * @type {ScreenNode<vec2>}
  8813. */
  8814. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  8815. // Deprecated
  8816. /**
  8817. * @deprecated since r169. Use {@link screenSize} instead.
  8818. */
  8819. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  8820. warn( 'TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  8821. return screenSize;
  8822. }, 'vec2' ).once() )();
  8823. /**
  8824. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8825. *
  8826. * @tsl
  8827. * @type {UniformNode<uint>}
  8828. */
  8829. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8830. /**
  8831. * TSL object that represents the `near` value of the camera used for the current render.
  8832. *
  8833. * @tsl
  8834. * @type {UniformNode<float>}
  8835. */
  8836. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8837. /**
  8838. * TSL object that represents the `far` value of the camera used for the current render.
  8839. *
  8840. * @tsl
  8841. * @type {UniformNode<float>}
  8842. */
  8843. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8844. /**
  8845. * TSL object that represents the projection matrix of the camera used for the current render.
  8846. *
  8847. * @tsl
  8848. * @type {UniformNode<mat4>}
  8849. */
  8850. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8851. let cameraProjectionMatrix;
  8852. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8853. const matrices = [];
  8854. for ( const subCamera of camera.cameras ) {
  8855. matrices.push( subCamera.projectionMatrix );
  8856. }
  8857. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  8858. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  8859. } else {
  8860. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8861. }
  8862. return cameraProjectionMatrix;
  8863. } ).once() )();
  8864. /**
  8865. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8866. *
  8867. * @tsl
  8868. * @type {UniformNode<mat4>}
  8869. */
  8870. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8871. let cameraProjectionMatrixInverse;
  8872. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8873. const matrices = [];
  8874. for ( const subCamera of camera.cameras ) {
  8875. matrices.push( subCamera.projectionMatrixInverse );
  8876. }
  8877. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  8878. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  8879. } else {
  8880. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8881. }
  8882. return cameraProjectionMatrixInverse;
  8883. } ).once() )();
  8884. /**
  8885. * TSL object that represents the view matrix of the camera used for the current render.
  8886. *
  8887. * @tsl
  8888. * @type {UniformNode<mat4>}
  8889. */
  8890. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8891. let cameraViewMatrix;
  8892. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8893. const matrices = [];
  8894. for ( const subCamera of camera.cameras ) {
  8895. matrices.push( subCamera.matrixWorldInverse );
  8896. }
  8897. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  8898. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  8899. } else {
  8900. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8901. }
  8902. return cameraViewMatrix;
  8903. } ).once() )();
  8904. /**
  8905. * TSL object that represents the world matrix of the camera used for the current render.
  8906. *
  8907. * @tsl
  8908. * @type {UniformNode<mat4>}
  8909. */
  8910. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8911. let cameraWorldMatrix;
  8912. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8913. const matrices = [];
  8914. for ( const subCamera of camera.cameras ) {
  8915. matrices.push( subCamera.matrixWorld );
  8916. }
  8917. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  8918. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  8919. } else {
  8920. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8921. }
  8922. return cameraWorldMatrix;
  8923. } ).once() )();
  8924. /**
  8925. * TSL object that represents the normal matrix of the camera used for the current render.
  8926. *
  8927. * @tsl
  8928. * @type {UniformNode<mat3>}
  8929. */
  8930. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8931. let cameraNormalMatrix;
  8932. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8933. const matrices = [];
  8934. for ( const subCamera of camera.cameras ) {
  8935. matrices.push( subCamera.normalMatrix );
  8936. }
  8937. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  8938. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  8939. } else {
  8940. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8941. }
  8942. return cameraNormalMatrix;
  8943. } ).once() )();
  8944. /**
  8945. * TSL object that represents the position in world space of the camera used for the current render.
  8946. *
  8947. * @tsl
  8948. * @type {UniformNode<vec3>}
  8949. */
  8950. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8951. let cameraPosition;
  8952. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8953. const positions = [];
  8954. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  8955. positions.push( new Vector3() );
  8956. }
  8957. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  8958. const subCameras = camera.cameras;
  8959. const array = self.array;
  8960. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  8961. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  8962. }
  8963. } );
  8964. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  8965. } else {
  8966. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8967. }
  8968. return cameraPosition;
  8969. } ).once() )();
  8970. /**
  8971. * TSL object that represents the viewport of the camera used for the current render.
  8972. *
  8973. * @tsl
  8974. * @type {UniformNode<vec4>}
  8975. */
  8976. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8977. let cameraViewport;
  8978. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8979. const viewports = [];
  8980. for ( const subCamera of camera.cameras ) {
  8981. viewports.push( subCamera.viewport );
  8982. }
  8983. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  8984. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  8985. } else {
  8986. // Fallback for single camera
  8987. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  8988. }
  8989. return cameraViewport;
  8990. } ).once() )();
  8991. const _sphere = /*@__PURE__*/ new Sphere();
  8992. /**
  8993. * This node can be used to access transformation related metrics of 3D objects.
  8994. * Depending on the selected scope, a different metric is represented as a uniform
  8995. * in the shader. The following scopes are supported:
  8996. *
  8997. * - `POSITION`: The object's position in world space.
  8998. * - `VIEW_POSITION`: The object's position in view/camera space.
  8999. * - `DIRECTION`: The object's direction in world space.
  9000. * - `SCALE`: The object's scale in world space.
  9001. * - `WORLD_MATRIX`: The object's matrix in world space.
  9002. *
  9003. * @augments Node
  9004. */
  9005. class Object3DNode extends Node {
  9006. static get type() {
  9007. return 'Object3DNode';
  9008. }
  9009. /**
  9010. * Constructs a new object 3D node.
  9011. *
  9012. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9013. * @param {?Object3D} [object3d=null] - The 3D object.
  9014. */
  9015. constructor( scope, object3d = null ) {
  9016. super();
  9017. /**
  9018. * The node reports a different type of transformation depending on the scope.
  9019. *
  9020. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9021. */
  9022. this.scope = scope;
  9023. /**
  9024. * The 3D object.
  9025. *
  9026. * @type {?Object3D}
  9027. * @default null
  9028. */
  9029. this.object3d = object3d;
  9030. /**
  9031. * Overwritten since this type of node is updated per object.
  9032. *
  9033. * @type {string}
  9034. * @default 'object'
  9035. */
  9036. this.updateType = NodeUpdateType.OBJECT;
  9037. /**
  9038. * Holds the value of the node as a uniform.
  9039. *
  9040. * @type {UniformNode}
  9041. */
  9042. this.uniformNode = new UniformNode( null );
  9043. }
  9044. /**
  9045. * Overwritten since the node type is inferred from the scope.
  9046. *
  9047. * @return {('mat4'|'vec3'|'float')} The node type.
  9048. */
  9049. getNodeType() {
  9050. const scope = this.scope;
  9051. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9052. return 'mat4';
  9053. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9054. return 'vec3';
  9055. } else if ( scope === Object3DNode.RADIUS ) {
  9056. return 'float';
  9057. }
  9058. }
  9059. /**
  9060. * Updates the uniform value depending on the scope.
  9061. *
  9062. * @param {NodeFrame} frame - The current node frame.
  9063. */
  9064. update( frame ) {
  9065. const object = this.object3d;
  9066. const uniformNode = this.uniformNode;
  9067. const scope = this.scope;
  9068. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9069. uniformNode.value = object.matrixWorld;
  9070. } else if ( scope === Object3DNode.POSITION ) {
  9071. uniformNode.value = uniformNode.value || new Vector3();
  9072. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9073. } else if ( scope === Object3DNode.SCALE ) {
  9074. uniformNode.value = uniformNode.value || new Vector3();
  9075. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9076. } else if ( scope === Object3DNode.DIRECTION ) {
  9077. uniformNode.value = uniformNode.value || new Vector3();
  9078. object.getWorldDirection( uniformNode.value );
  9079. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9080. const camera = frame.camera;
  9081. uniformNode.value = uniformNode.value || new Vector3();
  9082. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9083. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9084. } else if ( scope === Object3DNode.RADIUS ) {
  9085. const geometry = frame.object.geometry;
  9086. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9087. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9088. uniformNode.value = _sphere.radius;
  9089. }
  9090. }
  9091. /**
  9092. * Generates the code snippet of the uniform node. The node type of the uniform
  9093. * node also depends on the selected scope.
  9094. *
  9095. * @param {NodeBuilder} builder - The current node builder.
  9096. * @return {string} The generated code snippet.
  9097. */
  9098. generate( builder ) {
  9099. const scope = this.scope;
  9100. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9101. this.uniformNode.nodeType = 'mat4';
  9102. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9103. this.uniformNode.nodeType = 'vec3';
  9104. } else if ( scope === Object3DNode.RADIUS ) {
  9105. this.uniformNode.nodeType = 'float';
  9106. }
  9107. return this.uniformNode.build( builder );
  9108. }
  9109. serialize( data ) {
  9110. super.serialize( data );
  9111. data.scope = this.scope;
  9112. }
  9113. deserialize( data ) {
  9114. super.deserialize( data );
  9115. this.scope = data.scope;
  9116. }
  9117. }
  9118. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9119. Object3DNode.POSITION = 'position';
  9120. Object3DNode.SCALE = 'scale';
  9121. Object3DNode.VIEW_POSITION = 'viewPosition';
  9122. Object3DNode.DIRECTION = 'direction';
  9123. Object3DNode.RADIUS = 'radius';
  9124. /**
  9125. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9126. *
  9127. * @tsl
  9128. * @function
  9129. * @param {?Object3D} [object3d] - The 3D object.
  9130. * @returns {Object3DNode<vec3>}
  9131. */
  9132. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9133. /**
  9134. * TSL function for creating an object 3D node that represents the object's world matrix.
  9135. *
  9136. * @tsl
  9137. * @function
  9138. * @param {?Object3D} [object3d] - The 3D object.
  9139. * @returns {Object3DNode<mat4>}
  9140. */
  9141. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9142. /**
  9143. * TSL function for creating an object 3D node that represents the object's position in world space.
  9144. *
  9145. * @tsl
  9146. * @function
  9147. * @param {?Object3D} [object3d] - The 3D object.
  9148. * @returns {Object3DNode<vec3>}
  9149. */
  9150. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9151. /**
  9152. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9153. *
  9154. * @tsl
  9155. * @function
  9156. * @param {?Object3D} [object3d] - The 3D object.
  9157. * @returns {Object3DNode<vec3>}
  9158. */
  9159. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9160. /**
  9161. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9162. *
  9163. * @tsl
  9164. * @function
  9165. * @param {?Object3D} [object3d] - The 3D object.
  9166. * @returns {Object3DNode<vec3>}
  9167. */
  9168. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9169. /**
  9170. * TSL function for creating an object 3D node that represents the object's radius.
  9171. *
  9172. * @tsl
  9173. * @function
  9174. * @param {?Object3D} [object3d] - The 3D object.
  9175. * @returns {Object3DNode<float>}
  9176. */
  9177. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9178. /**
  9179. * This type of node is a specialized version of `Object3DNode`
  9180. * with larger set of model related metrics. Unlike `Object3DNode`,
  9181. * `ModelNode` extracts the reference to the 3D object from the
  9182. * current node frame state.
  9183. *
  9184. * @augments Object3DNode
  9185. */
  9186. class ModelNode extends Object3DNode {
  9187. static get type() {
  9188. return 'ModelNode';
  9189. }
  9190. /**
  9191. * Constructs a new object model node.
  9192. *
  9193. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9194. */
  9195. constructor( scope ) {
  9196. super( scope );
  9197. }
  9198. /**
  9199. * Extracts the model reference from the frame state and then
  9200. * updates the uniform value depending on the scope.
  9201. *
  9202. * @param {NodeFrame} frame - The current node frame.
  9203. */
  9204. update( frame ) {
  9205. this.object3d = frame.object;
  9206. super.update( frame );
  9207. }
  9208. }
  9209. /**
  9210. * TSL object that represents the object's direction in world space.
  9211. *
  9212. * @tsl
  9213. * @type {ModelNode<vec3>}
  9214. */
  9215. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9216. /**
  9217. * TSL object that represents the object's world matrix.
  9218. *
  9219. * @tsl
  9220. * @type {ModelNode<mat4>}
  9221. */
  9222. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9223. /**
  9224. * TSL object that represents the object's position in world space.
  9225. *
  9226. * @tsl
  9227. * @type {ModelNode<vec3>}
  9228. */
  9229. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9230. /**
  9231. * TSL object that represents the object's scale in world space.
  9232. *
  9233. * @tsl
  9234. * @type {ModelNode<vec3>}
  9235. */
  9236. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9237. /**
  9238. * TSL object that represents the object's position in view/camera space.
  9239. *
  9240. * @tsl
  9241. * @type {ModelNode<vec3>}
  9242. */
  9243. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9244. /**
  9245. * TSL object that represents the object's radius.
  9246. *
  9247. * @tsl
  9248. * @type {ModelNode<float>}
  9249. */
  9250. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9251. /**
  9252. * TSL object that represents the object's normal matrix.
  9253. *
  9254. * @tsl
  9255. * @type {UniformNode<mat3>}
  9256. */
  9257. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9258. /**
  9259. * TSL object that represents the object's inverse world matrix.
  9260. *
  9261. * @tsl
  9262. * @type {UniformNode<mat4>}
  9263. */
  9264. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9265. /**
  9266. * TSL object that represents the object's model view matrix.
  9267. *
  9268. * @tsl
  9269. * @type {Node<mat4>}
  9270. */
  9271. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9272. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9273. } ).once() )().toVar( 'modelViewMatrix' );
  9274. // GPU Precision
  9275. /**
  9276. * TSL object that represents the object's model view in `mediump` precision.
  9277. *
  9278. * @tsl
  9279. * @type {Node<mat4>}
  9280. */
  9281. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9282. // CPU Precision
  9283. /**
  9284. * TSL object that represents the object's model view in `highp` precision
  9285. * which is achieved by computing the matrix in JS and not in the shader.
  9286. *
  9287. * @tsl
  9288. * @type {Node<mat4>}
  9289. */
  9290. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9291. builder.context.isHighPrecisionModelViewMatrix = true;
  9292. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9293. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9294. } );
  9295. } ).once() )().toVar( 'highpModelViewMatrix' );
  9296. /**
  9297. * TSL object that represents the object's model normal view in `highp` precision
  9298. * which is achieved by computing the matrix in JS and not in the shader.
  9299. *
  9300. * @tsl
  9301. * @type {Node<mat3>}
  9302. */
  9303. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9304. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9305. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9306. if ( isHighPrecisionModelViewMatrix !== true ) {
  9307. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9308. }
  9309. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9310. } );
  9311. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9312. /**
  9313. * TSL object that represents the position attribute of the current rendered object.
  9314. *
  9315. * @tsl
  9316. * @type {AttributeNode<vec3>}
  9317. */
  9318. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9319. /**
  9320. * TSL object that represents the vertex position in local space of the current rendered object.
  9321. *
  9322. * @tsl
  9323. * @type {AttributeNode<vec3>}
  9324. */
  9325. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9326. /**
  9327. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9328. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9329. *
  9330. * @tsl
  9331. * @type {AttributeNode<vec3>}
  9332. */
  9333. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9334. /**
  9335. * TSL object that represents the vertex position in world space of the current rendered object.
  9336. *
  9337. * @tsl
  9338. * @type {VaryingNode<vec3>}
  9339. */
  9340. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9341. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9342. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9343. /**
  9344. * TSL object that represents the position world direction of the current rendered object.
  9345. *
  9346. * @tsl
  9347. * @type {Node<vec3>}
  9348. */
  9349. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9350. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9351. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9352. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9353. /**
  9354. * TSL object that represents the vertex position in view space of the current rendered object.
  9355. *
  9356. * @tsl
  9357. * @type {VaryingNode<vec3>}
  9358. */
  9359. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9360. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9361. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9362. /**
  9363. * TSL object that represents the position view direction of the current rendered object.
  9364. *
  9365. * @tsl
  9366. * @type {VaryingNode<vec3>}
  9367. */
  9368. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  9369. /**
  9370. * This node can be used to evaluate whether a primitive is front or back facing.
  9371. *
  9372. * @augments Node
  9373. */
  9374. class FrontFacingNode extends Node {
  9375. static get type() {
  9376. return 'FrontFacingNode';
  9377. }
  9378. /**
  9379. * Constructs a new front facing node.
  9380. */
  9381. constructor() {
  9382. super( 'bool' );
  9383. /**
  9384. * This flag can be used for type testing.
  9385. *
  9386. * @type {boolean}
  9387. * @readonly
  9388. * @default true
  9389. */
  9390. this.isFrontFacingNode = true;
  9391. }
  9392. generate( builder ) {
  9393. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9394. //
  9395. const { material } = builder;
  9396. if ( material.side === BackSide ) {
  9397. return 'false';
  9398. }
  9399. return builder.getFrontFacing();
  9400. }
  9401. }
  9402. /**
  9403. * TSL object that represents whether a primitive is front or back facing
  9404. *
  9405. * @tsl
  9406. * @type {FrontFacingNode<bool>}
  9407. */
  9408. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9409. /**
  9410. * TSL object that represents the front facing status as a number instead of a bool.
  9411. * `1` means front facing, `-1` means back facing.
  9412. *
  9413. * @tsl
  9414. * @type {Node<float>}
  9415. */
  9416. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9417. /**
  9418. * Converts a direction vector to a face direction vector based on the material's side.
  9419. *
  9420. * If the material is set to `BackSide`, the direction is inverted.
  9421. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9422. *
  9423. * @tsl
  9424. * @param {Node<vec3>} direction - The direction vector to convert.
  9425. * @returns {Node<vec3>} The converted direction vector.
  9426. */
  9427. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9428. const side = material.side;
  9429. if ( side === BackSide ) {
  9430. direction = direction.mul( -1 );
  9431. } else if ( side === DoubleSide ) {
  9432. direction = direction.mul( faceDirection );
  9433. }
  9434. return direction;
  9435. } );
  9436. /**
  9437. * TSL object that represents the normal attribute of the current rendered object in local space.
  9438. *
  9439. * @tsl
  9440. * @type {Node<vec3>}
  9441. */
  9442. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9443. /**
  9444. * TSL object that represents the vertex normal of the current rendered object in local space.
  9445. *
  9446. * @tsl
  9447. * @type {Node<vec3>}
  9448. */
  9449. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9450. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9451. warn( 'TSL: Vertex attribute "normal" not found on geometry.' );
  9452. return vec3( 0, 1, 0 );
  9453. }
  9454. return normalGeometry;
  9455. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9456. /**
  9457. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9458. *
  9459. * @tsl
  9460. * @type {Node<vec3>}
  9461. */
  9462. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9463. /**
  9464. * TSL object that represents the vertex normal of the current rendered object in view space.
  9465. *
  9466. * @tsl
  9467. * @type {Node<vec3>}
  9468. */
  9469. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9470. let node;
  9471. if ( builder.material.flatShading === true ) {
  9472. node = normalFlat;
  9473. } else {
  9474. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9475. }
  9476. return node;
  9477. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9478. /**
  9479. * TSL object that represents the vertex normal of the current rendered object in world space.
  9480. *
  9481. * @tsl
  9482. * @type {Node<vec3>}
  9483. */
  9484. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9485. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9486. if ( builder.material.flatShading !== true ) {
  9487. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9488. }
  9489. return normal.normalize().toVar( 'normalWorldGeometry' );
  9490. }, 'vec3' ).once() )();
  9491. /**
  9492. * TSL object that represents the vertex normal of the current rendered object in view space.
  9493. *
  9494. * @tsl
  9495. * @type {Node<vec3>}
  9496. */
  9497. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9498. let node;
  9499. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9500. node = normalViewGeometry;
  9501. if ( material.flatShading !== true ) {
  9502. node = directionToFaceDirection( node );
  9503. }
  9504. } else {
  9505. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9506. node = context.setupNormal().context( { getUV: null } );
  9507. }
  9508. return node;
  9509. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9510. /**
  9511. * TSL object that represents the vertex normal of the current rendered object in world space.
  9512. *
  9513. * @tsl
  9514. * @type {Node<vec3>}
  9515. */
  9516. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9517. /**
  9518. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9519. *
  9520. * @tsl
  9521. * @type {Node<vec3>}
  9522. */
  9523. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9524. let node;
  9525. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9526. node = normalView;
  9527. } else {
  9528. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9529. node = context.setupClearcoatNormal().context( { getUV: null } );
  9530. }
  9531. return node;
  9532. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9533. /**
  9534. * Transforms the normal with the given matrix.
  9535. *
  9536. * @tsl
  9537. * @function
  9538. * @param {Node<vec3>} normal - The normal.
  9539. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9540. * @return {Node<vec3>} The transformed normal.
  9541. */
  9542. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9543. const m = mat3( matrix );
  9544. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9545. return m.mul( transformedNormal ).xyz;
  9546. } );
  9547. /**
  9548. * Transforms the given normal from local to view space.
  9549. *
  9550. * @tsl
  9551. * @function
  9552. * @param {Node<vec3>} normal - The normal.
  9553. * @param {NodeBuilder} builder - The current node builder.
  9554. * @return {Node<vec3>} The transformed normal.
  9555. */
  9556. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9557. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9558. if ( modelNormalViewMatrix !== null ) {
  9559. return modelNormalViewMatrix.transformDirection( normal );
  9560. }
  9561. //
  9562. const transformedNormal = modelNormalMatrix.mul( normal );
  9563. return cameraViewMatrix.transformDirection( transformedNormal );
  9564. } );
  9565. // Deprecated
  9566. /**
  9567. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9568. *
  9569. * @tsl
  9570. * @type {Node<vec3>}
  9571. * @deprecated since r178. Use `normalView` instead.
  9572. */
  9573. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9574. warn( 'TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9575. return normalView;
  9576. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9577. /**
  9578. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9579. *
  9580. * @tsl
  9581. * @type {Node<vec3>}
  9582. * @deprecated since r178. Use `normalWorld` instead.
  9583. */
  9584. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9585. warn( 'TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9586. return normalWorld;
  9587. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9588. /**
  9589. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9590. *
  9591. * @tsl
  9592. * @type {Node<vec3>}
  9593. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9594. */
  9595. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9596. warn( 'TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9597. return clearcoatNormalView;
  9598. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9599. const _e1$1 = /*@__PURE__*/ new Euler();
  9600. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9601. /**
  9602. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9603. *
  9604. * @tsl
  9605. * @type {UniformNode<float>}
  9606. */
  9607. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9608. /**
  9609. * TSL object that represents the intensity of environment maps of PBR materials.
  9610. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9611. *
  9612. * @tsl
  9613. * @type {Node<float>}
  9614. */
  9615. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9616. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9617. } );
  9618. /**
  9619. * TSL object that represents the rotation of environment maps.
  9620. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9621. * rotation of `scene.environment` instead.
  9622. *
  9623. * @tsl
  9624. * @type {Node<mat4>}
  9625. */
  9626. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9627. return frame.material;
  9628. } ).onObjectUpdate( function ( { material, scene } ) {
  9629. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9630. if ( rotation ) {
  9631. _e1$1.copy( rotation );
  9632. _m1$1.makeRotationFromEuler( _e1$1 );
  9633. } else {
  9634. _m1$1.identity();
  9635. }
  9636. return _m1$1;
  9637. } );
  9638. /**
  9639. * The reflect vector in view space.
  9640. *
  9641. * @tsl
  9642. * @type {Node<vec3>}
  9643. */
  9644. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9645. /**
  9646. * The refract vector in view space.
  9647. *
  9648. * @tsl
  9649. * @type {Node<vec3>}
  9650. */
  9651. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  9652. /**
  9653. * Used for sampling cube maps when using cube reflection mapping.
  9654. *
  9655. * @tsl
  9656. * @type {Node<vec3>}
  9657. */
  9658. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9659. /**
  9660. * Used for sampling cube maps when using cube refraction mapping.
  9661. *
  9662. * @tsl
  9663. * @type {Node<vec3>}
  9664. */
  9665. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9666. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  9667. /**
  9668. * This type of uniform node represents a cube texture.
  9669. *
  9670. * @augments TextureNode
  9671. */
  9672. class CubeTextureNode extends TextureNode {
  9673. static get type() {
  9674. return 'CubeTextureNode';
  9675. }
  9676. /**
  9677. * Constructs a new cube texture node.
  9678. *
  9679. * @param {CubeTexture} value - The cube texture.
  9680. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9681. * @param {?Node<int>} [levelNode=null] - The level node.
  9682. * @param {?Node<float>} [biasNode=null] - The bias node.
  9683. */
  9684. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  9685. super( value, uvNode, levelNode, biasNode );
  9686. /**
  9687. * This flag can be used for type testing.
  9688. *
  9689. * @type {boolean}
  9690. * @readonly
  9691. * @default true
  9692. */
  9693. this.isCubeTextureNode = true;
  9694. }
  9695. /**
  9696. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  9697. *
  9698. * @param {NodeBuilder} builder - The current node builder.
  9699. * @return {string} The input type.
  9700. */
  9701. getInputType( /*builder*/ ) {
  9702. return 'cubeTexture';
  9703. }
  9704. /**
  9705. * Returns a default uvs based on the mapping type of the cube texture.
  9706. *
  9707. * @return {Node<vec3>} The default uv attribute.
  9708. */
  9709. getDefaultUV() {
  9710. const texture = this.value;
  9711. if ( texture.mapping === CubeReflectionMapping ) {
  9712. return reflectVector;
  9713. } else if ( texture.mapping === CubeRefractionMapping ) {
  9714. return refractVector;
  9715. } else {
  9716. error( 'CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  9717. return vec3( 0, 0, 0 );
  9718. }
  9719. }
  9720. /**
  9721. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  9722. * for cube textures. The uv transformation matrix is not applied to cube textures.
  9723. *
  9724. * @param {boolean} value - The update toggle.
  9725. */
  9726. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  9727. /**
  9728. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  9729. * to modify the uv node for correct sampling.
  9730. *
  9731. * @param {NodeBuilder} builder - The current node builder.
  9732. * @param {Node} uvNode - The uv node to setup.
  9733. * @return {Node} The updated uv node.
  9734. */
  9735. setupUV( builder, uvNode ) {
  9736. const texture = this.value;
  9737. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  9738. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9739. }
  9740. return materialEnvRotation.mul( uvNode );
  9741. }
  9742. /**
  9743. * Generates the uv code snippet.
  9744. *
  9745. * @param {NodeBuilder} builder - The current node builder.
  9746. * @param {Node} cubeUV - The uv node to generate code for.
  9747. * @return {string} The generated code snippet.
  9748. */
  9749. generateUV( builder, cubeUV ) {
  9750. return cubeUV.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  9751. }
  9752. }
  9753. /**
  9754. * TSL function for creating a cube texture node.
  9755. *
  9756. * @tsl
  9757. * @function
  9758. * @param {CubeTexture} value - The cube texture.
  9759. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9760. * @param {?Node<int>} [levelNode=null] - The level node.
  9761. * @param {?Node<float>} [biasNode=null] - The bias node.
  9762. * @returns {CubeTextureNode}
  9763. */
  9764. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  9765. /**
  9766. * TSL function for creating a cube texture uniform node.
  9767. *
  9768. * @tsl
  9769. * @function
  9770. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  9771. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9772. * @param {?Node<int>} [levelNode=null] - The level node.
  9773. * @param {?Node<float>} [biasNode=null] - The bias node.
  9774. * @returns {CubeTextureNode}
  9775. */
  9776. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  9777. let textureNode;
  9778. if ( value && value.isCubeTextureNode === true ) {
  9779. textureNode = nodeObject( value.clone() );
  9780. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  9781. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9782. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9783. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9784. } else {
  9785. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  9786. }
  9787. return textureNode;
  9788. };
  9789. /**
  9790. * TSL function for creating a uniform cube texture node.
  9791. *
  9792. * @tsl
  9793. * @function
  9794. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  9795. * @returns {CubeTextureNode}
  9796. */
  9797. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  9798. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  9799. /**
  9800. * This class is only relevant if the referenced property is array-like.
  9801. * In this case, `ReferenceElementNode` allows to refer to a specific
  9802. * element inside the data structure via an index.
  9803. *
  9804. * @augments ArrayElementNode
  9805. */
  9806. class ReferenceElementNode extends ArrayElementNode {
  9807. static get type() {
  9808. return 'ReferenceElementNode';
  9809. }
  9810. /**
  9811. * Constructs a new reference element node.
  9812. *
  9813. * @param {?ReferenceNode} referenceNode - The reference node.
  9814. * @param {Node} indexNode - The index node that defines the element access.
  9815. */
  9816. constructor( referenceNode, indexNode ) {
  9817. super( referenceNode, indexNode );
  9818. /**
  9819. * Similar to {@link ReferenceNode#reference}, an additional
  9820. * property references to the current node.
  9821. *
  9822. * @type {?ReferenceNode}
  9823. * @default null
  9824. */
  9825. this.referenceNode = referenceNode;
  9826. /**
  9827. * This flag can be used for type testing.
  9828. *
  9829. * @type {boolean}
  9830. * @readonly
  9831. * @default true
  9832. */
  9833. this.isReferenceElementNode = true;
  9834. }
  9835. /**
  9836. * This method is overwritten since the node type is inferred from
  9837. * the uniform type of the reference node.
  9838. *
  9839. * @return {string} The node type.
  9840. */
  9841. getNodeType() {
  9842. return this.referenceNode.uniformType;
  9843. }
  9844. generate( builder ) {
  9845. const snippet = super.generate( builder );
  9846. const arrayType = this.referenceNode.getNodeType();
  9847. const elementType = this.getNodeType();
  9848. return builder.format( snippet, arrayType, elementType );
  9849. }
  9850. }
  9851. /**
  9852. * This type of node establishes a reference to a property of another object.
  9853. * In this way, the value of the node is automatically linked to the value of
  9854. * referenced object. Reference nodes internally represent the linked value
  9855. * as a uniform.
  9856. *
  9857. * @augments Node
  9858. */
  9859. class ReferenceNode extends Node {
  9860. static get type() {
  9861. return 'ReferenceNode';
  9862. }
  9863. /**
  9864. * Constructs a new reference node.
  9865. *
  9866. * @param {string} property - The name of the property the node refers to.
  9867. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  9868. * @param {?Object} [object=null] - The object the property belongs to.
  9869. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  9870. */
  9871. constructor( property, uniformType, object = null, count = null ) {
  9872. super();
  9873. /**
  9874. * The name of the property the node refers to.
  9875. *
  9876. * @type {string}
  9877. */
  9878. this.property = property;
  9879. /**
  9880. * The uniform type that should be used to represent the property value.
  9881. *
  9882. * @type {string}
  9883. */
  9884. this.uniformType = uniformType;
  9885. /**
  9886. * The object the property belongs to.
  9887. *
  9888. * @type {?Object}
  9889. * @default null
  9890. */
  9891. this.object = object;
  9892. /**
  9893. * When the linked property is an array, this parameter defines its length.
  9894. *
  9895. * @type {?number}
  9896. * @default null
  9897. */
  9898. this.count = count;
  9899. /**
  9900. * The property name might have dots so nested properties can be referred.
  9901. * The hierarchy of the names is stored inside this array.
  9902. *
  9903. * @type {Array<string>}
  9904. */
  9905. this.properties = property.split( '.' );
  9906. /**
  9907. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  9908. * since the final reference might be updated from calling code.
  9909. *
  9910. * @type {?Object}
  9911. * @default null
  9912. */
  9913. this.reference = object;
  9914. /**
  9915. * The uniform node that holds the value of the reference node.
  9916. *
  9917. * @type {UniformNode}
  9918. * @default null
  9919. */
  9920. this.node = null;
  9921. /**
  9922. * The uniform group of the internal uniform.
  9923. *
  9924. * @type {UniformGroupNode}
  9925. * @default null
  9926. */
  9927. this.group = null;
  9928. /**
  9929. * An optional label of the internal uniform node.
  9930. *
  9931. * @type {?string}
  9932. * @default null
  9933. */
  9934. this.name = null;
  9935. /**
  9936. * Overwritten since reference nodes are updated per object.
  9937. *
  9938. * @type {string}
  9939. * @default 'object'
  9940. */
  9941. this.updateType = NodeUpdateType.OBJECT;
  9942. }
  9943. /**
  9944. * When the referred property is array-like, this method can be used
  9945. * to access elements via an index node.
  9946. *
  9947. * @param {IndexNode} indexNode - indexNode.
  9948. * @return {ReferenceElementNode} A reference to an element.
  9949. */
  9950. element( indexNode ) {
  9951. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9952. }
  9953. /**
  9954. * Sets the uniform group for this reference node.
  9955. *
  9956. * @param {UniformGroupNode} group - The uniform group to set.
  9957. * @return {ReferenceNode} A reference to this node.
  9958. */
  9959. setGroup( group ) {
  9960. this.group = group;
  9961. return this;
  9962. }
  9963. /**
  9964. * Sets the name for the internal uniform.
  9965. *
  9966. * @param {string} name - The label to set.
  9967. * @return {ReferenceNode} A reference to this node.
  9968. */
  9969. setName( name ) {
  9970. this.name = name;
  9971. return this;
  9972. }
  9973. /**
  9974. * Sets the label for the internal uniform.
  9975. *
  9976. * @deprecated
  9977. * @param {string} name - The label to set.
  9978. * @return {ReferenceNode} A reference to this node.
  9979. */
  9980. label( name ) {
  9981. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  9982. return this.setName( name );
  9983. }
  9984. /**
  9985. * Sets the node type which automatically defines the internal
  9986. * uniform type.
  9987. *
  9988. * @param {string} uniformType - The type to set.
  9989. */
  9990. setNodeType( uniformType ) {
  9991. let node = null;
  9992. if ( this.count !== null ) {
  9993. node = buffer( null, uniformType, this.count );
  9994. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9995. node = uniformArray( null, uniformType );
  9996. } else if ( uniformType === 'texture' ) {
  9997. node = texture( null );
  9998. } else if ( uniformType === 'cubeTexture' ) {
  9999. node = cubeTexture( null );
  10000. } else {
  10001. node = uniform( null, uniformType );
  10002. }
  10003. if ( this.group !== null ) {
  10004. node.setGroup( this.group );
  10005. }
  10006. if ( this.name !== null ) node.setName( this.name );
  10007. this.node = node;
  10008. }
  10009. /**
  10010. * This method is overwritten since the node type is inferred from
  10011. * the type of the reference node.
  10012. *
  10013. * @param {NodeBuilder} builder - The current node builder.
  10014. * @return {string} The node type.
  10015. */
  10016. getNodeType( builder ) {
  10017. if ( this.node === null ) {
  10018. this.updateReference( builder );
  10019. this.updateValue();
  10020. }
  10021. return this.node.getNodeType( builder );
  10022. }
  10023. /**
  10024. * Returns the property value from the given referred object.
  10025. *
  10026. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10027. * @return {any} The value.
  10028. */
  10029. getValueFromReference( object = this.reference ) {
  10030. const { properties } = this;
  10031. let value = object[ properties[ 0 ] ];
  10032. for ( let i = 1; i < properties.length; i ++ ) {
  10033. value = value[ properties[ i ] ];
  10034. }
  10035. return value;
  10036. }
  10037. /**
  10038. * Allows to update the reference based on the given state. The state is only
  10039. * evaluated {@link ReferenceNode#object} is not set.
  10040. *
  10041. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10042. * @return {Object} The updated reference.
  10043. */
  10044. updateReference( state ) {
  10045. this.reference = this.object !== null ? this.object : state.object;
  10046. return this.reference;
  10047. }
  10048. /**
  10049. * The output of the reference node is the internal uniform node.
  10050. *
  10051. * @param {NodeBuilder} builder - The current node builder.
  10052. * @return {UniformNode} The output node.
  10053. */
  10054. setup( /* builder */ ) {
  10055. this.updateValue();
  10056. return this.node;
  10057. }
  10058. /**
  10059. * Overwritten to update the internal uniform value.
  10060. *
  10061. * @param {NodeFrame} frame - A reference to the current node frame.
  10062. */
  10063. update( /*frame*/ ) {
  10064. this.updateValue();
  10065. }
  10066. /**
  10067. * Retrieves the value from the referred object property and uses it
  10068. * to updated the internal uniform.
  10069. */
  10070. updateValue() {
  10071. if ( this.node === null ) this.setNodeType( this.uniformType );
  10072. const value = this.getValueFromReference();
  10073. if ( Array.isArray( value ) ) {
  10074. this.node.array = value;
  10075. } else {
  10076. this.node.value = value;
  10077. }
  10078. }
  10079. }
  10080. /**
  10081. * TSL function for creating a reference node.
  10082. *
  10083. * @tsl
  10084. * @function
  10085. * @param {string} name - The name of the property the node refers to.
  10086. * @param {string} type - The uniform type that should be used to represent the property value.
  10087. * @param {?Object} [object] - The object the property belongs to.
  10088. * @returns {ReferenceNode}
  10089. */
  10090. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10091. /**
  10092. * TSL function for creating a reference node. Use this function if you want need a reference
  10093. * to an array-like property that should be represented as a uniform buffer.
  10094. *
  10095. * @tsl
  10096. * @function
  10097. * @param {string} name - The name of the property the node refers to.
  10098. * @param {string} type - The uniform type that should be used to represent the property value.
  10099. * @param {number} count - The number of value inside the array-like object.
  10100. * @param {Object} object - An array-like object the property belongs to.
  10101. * @returns {ReferenceNode}
  10102. */
  10103. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10104. /**
  10105. * This node is a special type of reference node which is intended
  10106. * for linking material properties with node values.
  10107. * ```js
  10108. * const opacityNode = materialReference( 'opacity', 'float', material );
  10109. * ```
  10110. * When changing `material.opacity`, the node value of `opacityNode` will
  10111. * automatically be updated.
  10112. *
  10113. * @augments ReferenceNode
  10114. */
  10115. class MaterialReferenceNode extends ReferenceNode {
  10116. static get type() {
  10117. return 'MaterialReferenceNode';
  10118. }
  10119. /**
  10120. * Constructs a new material reference node.
  10121. *
  10122. * @param {string} property - The name of the property the node refers to.
  10123. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10124. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10125. * the node refers to the material of the current rendered object.
  10126. */
  10127. constructor( property, inputType, material = null ) {
  10128. super( property, inputType, material );
  10129. /**
  10130. * The material the property belongs to. When no material is set,
  10131. * the node refers to the material of the current rendered object.
  10132. *
  10133. * @type {?Material}
  10134. * @default null
  10135. */
  10136. this.material = material;
  10137. /**
  10138. * This flag can be used for type testing.
  10139. *
  10140. * @type {boolean}
  10141. * @readonly
  10142. * @default true
  10143. */
  10144. this.isMaterialReferenceNode = true;
  10145. }
  10146. /**
  10147. * Updates the reference based on the given state. The state is only evaluated
  10148. * {@link MaterialReferenceNode#material} is not set.
  10149. *
  10150. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10151. * @return {Object} The updated reference.
  10152. */
  10153. updateReference( state ) {
  10154. this.reference = this.material !== null ? this.material : state.material;
  10155. return this.reference;
  10156. }
  10157. }
  10158. /**
  10159. * TSL function for creating a material reference node.
  10160. *
  10161. * @tsl
  10162. * @function
  10163. * @param {string} name - The name of the property the node refers to.
  10164. * @param {string} type - The uniform type that should be used to represent the property value.
  10165. * @param {?Material} [material=null] - The material the property belongs to.
  10166. * When no material is set, the node refers to the material of the current rendered object.
  10167. * @returns {MaterialReferenceNode}
  10168. */
  10169. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10170. // Normal Mapping Without Precomputed Tangents
  10171. // http://www.thetenthplanet.de/archives/1180
  10172. const uv = uv$1();
  10173. const q0 = positionView.dFdx();
  10174. const q1 = positionView.dFdy();
  10175. const st0 = uv.dFdx();
  10176. const st1 = uv.dFdy();
  10177. const N = normalView;
  10178. const q1perp = q1.cross( N );
  10179. const q0perp = N.cross( q0 );
  10180. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10181. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10182. const det = T.dot( T ).max( B.dot( B ) );
  10183. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10184. /**
  10185. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10186. * Useful for normal mapping without precomputed tangents.
  10187. *
  10188. * Reference: http://www.thetenthplanet.de/archives/1180
  10189. *
  10190. * @tsl
  10191. * @type {Node<vec3>}
  10192. */
  10193. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10194. /**
  10195. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10196. * Complements the tangentViewFrame for constructing the tangent space basis.
  10197. *
  10198. * Reference: http://www.thetenthplanet.de/archives/1180
  10199. *
  10200. * @tsl
  10201. * @type {Node<vec3>}
  10202. */
  10203. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10204. /**
  10205. * TSL object that represents the tangent attribute of the current rendered object.
  10206. *
  10207. * @tsl
  10208. * @type {Node<vec4>}
  10209. */
  10210. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10211. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10212. builder.geometry.computeTangents();
  10213. }
  10214. return attribute( 'tangent', 'vec4' );
  10215. } )();
  10216. /**
  10217. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10218. *
  10219. * @tsl
  10220. * @type {Node<vec3>}
  10221. */
  10222. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10223. /**
  10224. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10225. *
  10226. * @tsl
  10227. * @type {Node<vec3>}
  10228. */
  10229. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10230. let node;
  10231. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10232. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10233. } else {
  10234. node = tangentViewFrame;
  10235. }
  10236. if ( material.flatShading !== true ) {
  10237. node = directionToFaceDirection( node );
  10238. }
  10239. return node;
  10240. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10241. /**
  10242. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10243. *
  10244. * @tsl
  10245. * @type {Node<vec3>}
  10246. */
  10247. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10248. /**
  10249. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10250. *
  10251. * @tsl
  10252. * @private
  10253. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10254. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10255. * @returns {Node<vec3>} The bitangent node.
  10256. */
  10257. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10258. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10259. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10260. bitangent = bitangent.toVarying( varyingName );
  10261. }
  10262. return bitangent;
  10263. } ).once( [ 'NORMAL' ] );
  10264. /**
  10265. * TSL object that represents the bitangent attribute of the current rendered object.
  10266. *
  10267. * @tsl
  10268. * @type {Node<vec3>}
  10269. */
  10270. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10271. /**
  10272. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10273. *
  10274. * @tsl
  10275. * @type {Node<vec3>}
  10276. */
  10277. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10278. /**
  10279. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10280. *
  10281. * @tsl
  10282. * @type {Node<vec3>}
  10283. */
  10284. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10285. let node;
  10286. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10287. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10288. } else {
  10289. node = bitangentViewFrame;
  10290. }
  10291. if ( material.flatShading !== true ) {
  10292. node = directionToFaceDirection( node );
  10293. }
  10294. return node;
  10295. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10296. /**
  10297. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10298. *
  10299. * @tsl
  10300. * @type {Node<vec3>}
  10301. */
  10302. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10303. /**
  10304. * TSL object that represents the TBN matrix in view space.
  10305. *
  10306. * @tsl
  10307. * @type {Node<mat3>}
  10308. */
  10309. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10310. /**
  10311. * TSL object that represents the parallax direction.
  10312. *
  10313. * @tsl
  10314. * @type {Node<mat3>}
  10315. */
  10316. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10317. /**
  10318. * TSL function for computing parallax uv coordinates.
  10319. *
  10320. * @tsl
  10321. * @function
  10322. * @param {Node<vec2>} uv - A uv node.
  10323. * @param {Node<vec2>} scale - A scale node.
  10324. * @returns {Node<vec2>} Parallax uv coordinates.
  10325. */
  10326. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10327. /**
  10328. * TSL function for computing bent normals.
  10329. *
  10330. * @tsl
  10331. * @function
  10332. * @returns {Node<vec3>} Bent normals.
  10333. */
  10334. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10335. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10336. let bentNormal = anisotropyB.cross( positionViewDirection );
  10337. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10338. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10339. return bentNormal;
  10340. } ).once() )();
  10341. /**
  10342. * This class can be used for applying normals maps to materials.
  10343. *
  10344. * ```js
  10345. * material.normalNode = normalMap( texture( normalTex ) );
  10346. * ```
  10347. *
  10348. * @augments TempNode
  10349. */
  10350. class NormalMapNode extends TempNode {
  10351. static get type() {
  10352. return 'NormalMapNode';
  10353. }
  10354. /**
  10355. * Constructs a new normal map node.
  10356. *
  10357. * @param {Node<vec3>} node - Represents the normal map data.
  10358. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10359. */
  10360. constructor( node, scaleNode = null ) {
  10361. super( 'vec3' );
  10362. /**
  10363. * Represents the normal map data.
  10364. *
  10365. * @type {Node<vec3>}
  10366. */
  10367. this.node = node;
  10368. /**
  10369. * Controls the intensity of the effect.
  10370. *
  10371. * @type {?Node<vec2>}
  10372. * @default null
  10373. */
  10374. this.scaleNode = scaleNode;
  10375. /**
  10376. * The normal map type.
  10377. *
  10378. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10379. * @default TangentSpaceNormalMap
  10380. */
  10381. this.normalMapType = TangentSpaceNormalMap;
  10382. }
  10383. setup( { material } ) {
  10384. const { normalMapType, scaleNode } = this;
  10385. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10386. if ( scaleNode !== null ) {
  10387. let scale = scaleNode;
  10388. if ( material.flatShading === true ) {
  10389. scale = directionToFaceDirection( scale );
  10390. }
  10391. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10392. }
  10393. let output = null;
  10394. if ( normalMapType === ObjectSpaceNormalMap ) {
  10395. output = transformNormalToView( normalMap );
  10396. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10397. output = TBNViewMatrix.mul( normalMap ).normalize();
  10398. } else {
  10399. error( `NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10400. output = normalView; // Fallback to default normal view
  10401. }
  10402. return output;
  10403. }
  10404. }
  10405. /**
  10406. * TSL function for creating a normal map node.
  10407. *
  10408. * @tsl
  10409. * @function
  10410. * @param {Node<vec3>} node - Represents the normal map data.
  10411. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10412. * @returns {NormalMapNode}
  10413. */
  10414. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10415. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10416. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10417. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10418. // It's used to preserve the same TextureNode instance
  10419. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10420. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10421. return vec2(
  10422. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10423. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10424. ).mul( bumpScale );
  10425. } );
  10426. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10427. const perturbNormalArb = Fn( ( inputs ) => {
  10428. const { surf_pos, surf_norm, dHdxy } = inputs;
  10429. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10430. const vSigmaX = surf_pos.dFdx().normalize();
  10431. const vSigmaY = surf_pos.dFdy().normalize();
  10432. const vN = surf_norm; // normalized
  10433. const R1 = vSigmaY.cross( vN );
  10434. const R2 = vN.cross( vSigmaX );
  10435. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10436. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10437. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10438. } );
  10439. /**
  10440. * This class can be used for applying bump maps to materials.
  10441. *
  10442. * ```js
  10443. * material.normalNode = bumpMap( texture( bumpTex ) );
  10444. * ```
  10445. *
  10446. * @augments TempNode
  10447. */
  10448. class BumpMapNode extends TempNode {
  10449. static get type() {
  10450. return 'BumpMapNode';
  10451. }
  10452. /**
  10453. * Constructs a new bump map node.
  10454. *
  10455. * @param {Node<float>} textureNode - Represents the bump map data.
  10456. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10457. */
  10458. constructor( textureNode, scaleNode = null ) {
  10459. super( 'vec3' );
  10460. /**
  10461. * Represents the bump map data.
  10462. *
  10463. * @type {Node<float>}
  10464. */
  10465. this.textureNode = textureNode;
  10466. /**
  10467. * Controls the intensity of the bump effect.
  10468. *
  10469. * @type {?Node<float>}
  10470. * @default null
  10471. */
  10472. this.scaleNode = scaleNode;
  10473. }
  10474. setup() {
  10475. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10476. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10477. return perturbNormalArb( {
  10478. surf_pos: positionView,
  10479. surf_norm: normalView,
  10480. dHdxy
  10481. } );
  10482. }
  10483. }
  10484. /**
  10485. * TSL function for creating a bump map node.
  10486. *
  10487. * @tsl
  10488. * @function
  10489. * @param {Node<float>} textureNode - Represents the bump map data.
  10490. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10491. * @returns {BumpMapNode}
  10492. */
  10493. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10494. const _propertyCache = new Map();
  10495. /**
  10496. * This class should simplify the node access to material properties.
  10497. * It internal uses reference nodes to make sure changes to material
  10498. * properties are automatically reflected to predefined TSL objects
  10499. * like e.g. `materialColor`.
  10500. *
  10501. * @augments Node
  10502. */
  10503. class MaterialNode extends Node {
  10504. static get type() {
  10505. return 'MaterialNode';
  10506. }
  10507. /**
  10508. * Constructs a new material node.
  10509. *
  10510. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10511. */
  10512. constructor( scope ) {
  10513. super();
  10514. /**
  10515. * The scope defines what material property is referred by the node.
  10516. *
  10517. * @type {string}
  10518. */
  10519. this.scope = scope;
  10520. }
  10521. /**
  10522. * Returns a cached reference node for the given property and type.
  10523. *
  10524. * @param {string} property - The name of the material property.
  10525. * @param {string} type - The uniform type of the property.
  10526. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10527. */
  10528. getCache( property, type ) {
  10529. let node = _propertyCache.get( property );
  10530. if ( node === undefined ) {
  10531. node = materialReference( property, type );
  10532. _propertyCache.set( property, node );
  10533. }
  10534. return node;
  10535. }
  10536. /**
  10537. * Returns a float-typed material reference node for the given property name.
  10538. *
  10539. * @param {string} property - The name of the material property.
  10540. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10541. */
  10542. getFloat( property ) {
  10543. return this.getCache( property, 'float' );
  10544. }
  10545. /**
  10546. * Returns a color-typed material reference node for the given property name.
  10547. *
  10548. * @param {string} property - The name of the material property.
  10549. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10550. */
  10551. getColor( property ) {
  10552. return this.getCache( property, 'color' );
  10553. }
  10554. /**
  10555. * Returns a texture-typed material reference node for the given property name.
  10556. *
  10557. * @param {string} property - The name of the material property.
  10558. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10559. */
  10560. getTexture( property ) {
  10561. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10562. }
  10563. /**
  10564. * The node setup is done depending on the selected scope. Multiple material properties
  10565. * might be grouped into a single node composition if they logically belong together.
  10566. *
  10567. * @param {NodeBuilder} builder - The current node builder.
  10568. * @return {Node} The node representing the selected scope.
  10569. */
  10570. setup( builder ) {
  10571. const material = builder.context.material;
  10572. const scope = this.scope;
  10573. let node = null;
  10574. if ( scope === MaterialNode.COLOR ) {
  10575. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10576. if ( material.map && material.map.isTexture === true ) {
  10577. node = colorNode.mul( this.getTexture( 'map' ) );
  10578. } else {
  10579. node = colorNode;
  10580. }
  10581. } else if ( scope === MaterialNode.OPACITY ) {
  10582. const opacityNode = this.getFloat( scope );
  10583. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10584. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10585. } else {
  10586. node = opacityNode;
  10587. }
  10588. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10589. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10590. node = this.getTexture( 'specular' ).r;
  10591. } else {
  10592. node = float( 1 );
  10593. }
  10594. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10595. const specularIntensityNode = this.getFloat( scope );
  10596. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10597. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10598. } else {
  10599. node = specularIntensityNode;
  10600. }
  10601. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10602. const specularColorNode = this.getColor( scope );
  10603. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10604. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10605. } else {
  10606. node = specularColorNode;
  10607. }
  10608. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10609. const roughnessNode = this.getFloat( scope );
  10610. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10611. node = roughnessNode.mul( this.getTexture( scope ).g );
  10612. } else {
  10613. node = roughnessNode;
  10614. }
  10615. } else if ( scope === MaterialNode.METALNESS ) {
  10616. const metalnessNode = this.getFloat( scope );
  10617. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10618. node = metalnessNode.mul( this.getTexture( scope ).b );
  10619. } else {
  10620. node = metalnessNode;
  10621. }
  10622. } else if ( scope === MaterialNode.EMISSIVE ) {
  10623. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10624. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10625. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10626. node = emissiveNode.mul( this.getTexture( scope ) );
  10627. } else {
  10628. node = emissiveNode;
  10629. }
  10630. } else if ( scope === MaterialNode.NORMAL ) {
  10631. if ( material.normalMap ) {
  10632. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10633. node.normalMapType = material.normalMapType;
  10634. } else if ( material.bumpMap ) {
  10635. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10636. } else {
  10637. node = normalView;
  10638. }
  10639. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10640. const clearcoatNode = this.getFloat( scope );
  10641. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10642. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10643. } else {
  10644. node = clearcoatNode;
  10645. }
  10646. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  10647. const clearcoatRoughnessNode = this.getFloat( scope );
  10648. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  10649. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  10650. } else {
  10651. node = clearcoatRoughnessNode;
  10652. }
  10653. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  10654. if ( material.clearcoatNormalMap ) {
  10655. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  10656. } else {
  10657. node = normalView;
  10658. }
  10659. } else if ( scope === MaterialNode.SHEEN ) {
  10660. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  10661. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  10662. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  10663. } else {
  10664. node = sheenNode;
  10665. }
  10666. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  10667. const sheenRoughnessNode = this.getFloat( scope );
  10668. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  10669. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  10670. } else {
  10671. node = sheenRoughnessNode;
  10672. }
  10673. node = node.clamp( 0.07, 1.0 );
  10674. } else if ( scope === MaterialNode.ANISOTROPY ) {
  10675. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  10676. const anisotropyPolar = this.getTexture( scope );
  10677. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  10678. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  10679. } else {
  10680. node = materialAnisotropyVector;
  10681. }
  10682. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  10683. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  10684. if ( material.iridescenceThicknessMap ) {
  10685. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  10686. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  10687. } else {
  10688. node = iridescenceThicknessMaximum;
  10689. }
  10690. } else if ( scope === MaterialNode.TRANSMISSION ) {
  10691. const transmissionNode = this.getFloat( scope );
  10692. if ( material.transmissionMap ) {
  10693. node = transmissionNode.mul( this.getTexture( scope ).r );
  10694. } else {
  10695. node = transmissionNode;
  10696. }
  10697. } else if ( scope === MaterialNode.THICKNESS ) {
  10698. const thicknessNode = this.getFloat( scope );
  10699. if ( material.thicknessMap ) {
  10700. node = thicknessNode.mul( this.getTexture( scope ).g );
  10701. } else {
  10702. node = thicknessNode;
  10703. }
  10704. } else if ( scope === MaterialNode.IOR ) {
  10705. node = this.getFloat( scope );
  10706. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  10707. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  10708. } else if ( scope === MaterialNode.AO ) {
  10709. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  10710. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  10711. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  10712. } else {
  10713. const outputType = this.getNodeType( builder );
  10714. node = this.getCache( scope, outputType );
  10715. }
  10716. return node;
  10717. }
  10718. }
  10719. MaterialNode.ALPHA_TEST = 'alphaTest';
  10720. MaterialNode.COLOR = 'color';
  10721. MaterialNode.OPACITY = 'opacity';
  10722. MaterialNode.SHININESS = 'shininess';
  10723. MaterialNode.SPECULAR = 'specular';
  10724. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  10725. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  10726. MaterialNode.SPECULAR_COLOR = 'specularColor';
  10727. MaterialNode.REFLECTIVITY = 'reflectivity';
  10728. MaterialNode.ROUGHNESS = 'roughness';
  10729. MaterialNode.METALNESS = 'metalness';
  10730. MaterialNode.NORMAL = 'normal';
  10731. MaterialNode.CLEARCOAT = 'clearcoat';
  10732. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  10733. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  10734. MaterialNode.EMISSIVE = 'emissive';
  10735. MaterialNode.ROTATION = 'rotation';
  10736. MaterialNode.SHEEN = 'sheen';
  10737. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  10738. MaterialNode.ANISOTROPY = 'anisotropy';
  10739. MaterialNode.IRIDESCENCE = 'iridescence';
  10740. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  10741. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  10742. MaterialNode.IOR = 'ior';
  10743. MaterialNode.TRANSMISSION = 'transmission';
  10744. MaterialNode.THICKNESS = 'thickness';
  10745. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  10746. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  10747. MaterialNode.LINE_SCALE = 'scale';
  10748. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  10749. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  10750. MaterialNode.LINE_WIDTH = 'linewidth';
  10751. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  10752. MaterialNode.POINT_SIZE = 'size';
  10753. MaterialNode.DISPERSION = 'dispersion';
  10754. MaterialNode.LIGHT_MAP = 'light';
  10755. MaterialNode.AO = 'ao';
  10756. /**
  10757. * TSL object that represents alpha test of the current material.
  10758. *
  10759. * @tsl
  10760. * @type {Node<float>}
  10761. */
  10762. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  10763. /**
  10764. * TSL object that represents the diffuse color of the current material.
  10765. * The value is composed via `color` * `map`.
  10766. *
  10767. * @tsl
  10768. * @type {Node<vec3>}
  10769. */
  10770. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  10771. /**
  10772. * TSL object that represents the shininess of the current material.
  10773. *
  10774. * @tsl
  10775. * @type {Node<float>}
  10776. */
  10777. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  10778. /**
  10779. * TSL object that represents the emissive color of the current material.
  10780. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  10781. *
  10782. * @tsl
  10783. * @type {Node<vec3>}
  10784. */
  10785. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  10786. /**
  10787. * TSL object that represents the opacity of the current material.
  10788. * The value is composed via `opacity` * `alphaMap`.
  10789. *
  10790. * @tsl
  10791. * @type {Node<float>}
  10792. */
  10793. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  10794. /**
  10795. * TSL object that represents the specular of the current material.
  10796. *
  10797. * @tsl
  10798. * @type {Node<vec3>}
  10799. */
  10800. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  10801. /**
  10802. * TSL object that represents the specular intensity of the current material.
  10803. * The value is composed via `specularIntensity` * `specularMap.a`.
  10804. *
  10805. * @tsl
  10806. * @type {Node<float>}
  10807. */
  10808. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  10809. /**
  10810. * TSL object that represents the specular color of the current material.
  10811. * The value is composed via `specularColor` * `specularMap.rgb`.
  10812. *
  10813. * @tsl
  10814. * @type {Node<vec3>}
  10815. */
  10816. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  10817. /**
  10818. * TSL object that represents the specular strength of the current material.
  10819. * The value is composed via `specularMap.r`.
  10820. *
  10821. * @tsl
  10822. * @type {Node<float>}
  10823. */
  10824. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  10825. /**
  10826. * TSL object that represents the reflectivity of the current material.
  10827. *
  10828. * @tsl
  10829. * @type {Node<float>}
  10830. */
  10831. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  10832. /**
  10833. * TSL object that represents the roughness of the current material.
  10834. * The value is composed via `roughness` * `roughnessMap.g`.
  10835. *
  10836. * @tsl
  10837. * @type {Node<float>}
  10838. */
  10839. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  10840. /**
  10841. * TSL object that represents the metalness of the current material.
  10842. * The value is composed via `metalness` * `metalnessMap.b`.
  10843. *
  10844. * @tsl
  10845. * @type {Node<float>}
  10846. */
  10847. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  10848. /**
  10849. * TSL object that represents the normal of the current material.
  10850. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  10851. *
  10852. * @tsl
  10853. * @type {Node<vec3>}
  10854. */
  10855. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  10856. /**
  10857. * TSL object that represents the clearcoat of the current material.
  10858. * The value is composed via `clearcoat` * `clearcoatMap.r`
  10859. *
  10860. * @tsl
  10861. * @type {Node<float>}
  10862. */
  10863. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  10864. /**
  10865. * TSL object that represents the clearcoat roughness of the current material.
  10866. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  10867. *
  10868. * @tsl
  10869. * @type {Node<float>}
  10870. */
  10871. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  10872. /**
  10873. * TSL object that represents the clearcoat normal of the current material.
  10874. * The value will be either `clearcoatNormalMap` or `normalView`.
  10875. *
  10876. * @tsl
  10877. * @type {Node<vec3>}
  10878. */
  10879. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  10880. /**
  10881. * TSL object that represents the rotation of the current sprite material.
  10882. *
  10883. * @tsl
  10884. * @type {Node<float>}
  10885. */
  10886. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  10887. /**
  10888. * TSL object that represents the sheen color of the current material.
  10889. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  10890. *
  10891. * @tsl
  10892. * @type {Node<vec3>}
  10893. */
  10894. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  10895. /**
  10896. * TSL object that represents the sheen roughness of the current material.
  10897. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  10898. *
  10899. * @tsl
  10900. * @type {Node<float>}
  10901. */
  10902. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  10903. /**
  10904. * TSL object that represents the anisotropy of the current material.
  10905. *
  10906. * @tsl
  10907. * @type {Node<vec2>}
  10908. */
  10909. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  10910. /**
  10911. * TSL object that represents the iridescence of the current material.
  10912. *
  10913. * @tsl
  10914. * @type {Node<float>}
  10915. */
  10916. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  10917. /**
  10918. * TSL object that represents the iridescence IOR of the current material.
  10919. *
  10920. * @tsl
  10921. * @type {Node<float>}
  10922. */
  10923. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  10924. /**
  10925. * TSL object that represents the iridescence thickness of the current material.
  10926. *
  10927. * @tsl
  10928. * @type {Node<float>}
  10929. */
  10930. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  10931. /**
  10932. * TSL object that represents the transmission of the current material.
  10933. * The value is composed via `transmission` * `transmissionMap.r`.
  10934. *
  10935. * @tsl
  10936. * @type {Node<float>}
  10937. */
  10938. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  10939. /**
  10940. * TSL object that represents the thickness of the current material.
  10941. * The value is composed via `thickness` * `thicknessMap.g`.
  10942. *
  10943. * @tsl
  10944. * @type {Node<float>}
  10945. */
  10946. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  10947. /**
  10948. * TSL object that represents the IOR of the current material.
  10949. *
  10950. * @tsl
  10951. * @type {Node<float>}
  10952. */
  10953. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10954. /**
  10955. * TSL object that represents the attenuation distance of the current material.
  10956. *
  10957. * @tsl
  10958. * @type {Node<float>}
  10959. */
  10960. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10961. /**
  10962. * TSL object that represents the attenuation color of the current material.
  10963. *
  10964. * @tsl
  10965. * @type {Node<vec3>}
  10966. */
  10967. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10968. /**
  10969. * TSL object that represents the scale of the current dashed line material.
  10970. *
  10971. * @tsl
  10972. * @type {Node<float>}
  10973. */
  10974. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10975. /**
  10976. * TSL object that represents the dash size of the current dashed line material.
  10977. *
  10978. * @tsl
  10979. * @type {Node<float>}
  10980. */
  10981. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10982. /**
  10983. * TSL object that represents the gap size of the current dashed line material.
  10984. *
  10985. * @tsl
  10986. * @type {Node<float>}
  10987. */
  10988. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10989. /**
  10990. * TSL object that represents the line width of the current line material.
  10991. *
  10992. * @tsl
  10993. * @type {Node<float>}
  10994. */
  10995. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10996. /**
  10997. * TSL object that represents the dash offset of the current line material.
  10998. *
  10999. * @tsl
  11000. * @type {Node<float>}
  11001. */
  11002. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  11003. /**
  11004. * TSL object that represents the point size of the current points material.
  11005. *
  11006. * @tsl
  11007. * @type {Node<float>}
  11008. */
  11009. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  11010. /**
  11011. * TSL object that represents the dispersion of the current material.
  11012. *
  11013. * @tsl
  11014. * @type {Node<float>}
  11015. */
  11016. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11017. /**
  11018. * TSL object that represents the light map of the current material.
  11019. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11020. *
  11021. * @tsl
  11022. * @type {Node<vec3>}
  11023. */
  11024. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11025. /**
  11026. * TSL object that represents the ambient occlusion map of the current material.
  11027. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11028. *
  11029. * @tsl
  11030. * @type {Node<float>}
  11031. */
  11032. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11033. /**
  11034. * TSL object that represents the anisotropy vector of the current material.
  11035. *
  11036. * @tsl
  11037. * @type {Node<vec2>}
  11038. */
  11039. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11040. return frame.material;
  11041. } ).onRenderUpdate( function ( { material } ) {
  11042. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11043. } );
  11044. /**
  11045. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11046. *
  11047. * @tsl
  11048. * @type {VaryingNode<vec4>}
  11049. */
  11050. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11051. return builder.context.setupModelViewProjection();
  11052. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11053. /**
  11054. * This class represents shader indices of different types. The following predefined node
  11055. * objects cover frequent use cases:
  11056. *
  11057. * - `vertexIndex`: The index of a vertex within a mesh.
  11058. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  11059. * - `drawIndex`: The index of a draw call.
  11060. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  11061. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  11062. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  11063. *
  11064. * @augments Node
  11065. */
  11066. class IndexNode extends Node {
  11067. static get type() {
  11068. return 'IndexNode';
  11069. }
  11070. /**
  11071. * Constructs a new index node.
  11072. *
  11073. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  11074. */
  11075. constructor( scope ) {
  11076. super( 'uint' );
  11077. /**
  11078. * The scope of the index node.
  11079. *
  11080. * @type {string}
  11081. */
  11082. this.scope = scope;
  11083. /**
  11084. * This flag can be used for type testing.
  11085. *
  11086. * @type {boolean}
  11087. * @readonly
  11088. * @default true
  11089. */
  11090. this.isIndexNode = true;
  11091. }
  11092. generate( builder ) {
  11093. const nodeType = this.getNodeType( builder );
  11094. const scope = this.scope;
  11095. let propertyName;
  11096. if ( scope === IndexNode.VERTEX ) {
  11097. propertyName = builder.getVertexIndex();
  11098. } else if ( scope === IndexNode.INSTANCE ) {
  11099. propertyName = builder.getInstanceIndex();
  11100. } else if ( scope === IndexNode.DRAW ) {
  11101. propertyName = builder.getDrawIndex();
  11102. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  11103. propertyName = builder.getInvocationLocalIndex();
  11104. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  11105. propertyName = builder.getInvocationSubgroupIndex();
  11106. } else if ( scope === IndexNode.SUBGROUP ) {
  11107. propertyName = builder.getSubgroupIndex();
  11108. } else {
  11109. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  11110. }
  11111. let output;
  11112. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  11113. output = propertyName;
  11114. } else {
  11115. const nodeVarying = varying( this );
  11116. output = nodeVarying.build( builder, nodeType );
  11117. }
  11118. return output;
  11119. }
  11120. }
  11121. IndexNode.VERTEX = 'vertex';
  11122. IndexNode.INSTANCE = 'instance';
  11123. IndexNode.SUBGROUP = 'subgroup';
  11124. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  11125. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  11126. IndexNode.DRAW = 'draw';
  11127. /**
  11128. * TSL object that represents the index of a vertex within a mesh.
  11129. *
  11130. * @tsl
  11131. * @type {IndexNode}
  11132. */
  11133. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  11134. /**
  11135. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  11136. *
  11137. * @tsl
  11138. * @type {IndexNode}
  11139. */
  11140. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  11141. /**
  11142. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  11143. *
  11144. * @tsl
  11145. * @type {IndexNode}
  11146. */
  11147. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11148. /**
  11149. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11150. *
  11151. * @tsl
  11152. * @type {IndexNode}
  11153. */
  11154. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11155. /**
  11156. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11157. *
  11158. * @tsl
  11159. * @type {IndexNode}
  11160. */
  11161. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11162. /**
  11163. * TSL object that represents the index of a draw call.
  11164. *
  11165. * @tsl
  11166. * @type {IndexNode}
  11167. */
  11168. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11169. /**
  11170. * This node implements the vertex shader logic which is required
  11171. * when rendering 3D objects via instancing. The code makes sure
  11172. * vertex positions, normals and colors can be modified via instanced
  11173. * data.
  11174. *
  11175. * @augments Node
  11176. */
  11177. class InstanceNode extends Node {
  11178. static get type() {
  11179. return 'InstanceNode';
  11180. }
  11181. /**
  11182. * Constructs a new instance node.
  11183. *
  11184. * @param {number} count - The number of instances.
  11185. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11186. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11187. */
  11188. constructor( count, instanceMatrix, instanceColor = null ) {
  11189. super( 'void' );
  11190. /**
  11191. * The number of instances.
  11192. *
  11193. * @type {number}
  11194. */
  11195. this.count = count;
  11196. /**
  11197. * Instanced buffer attribute representing the transformation of instances.
  11198. *
  11199. * @type {InstancedBufferAttribute}
  11200. */
  11201. this.instanceMatrix = instanceMatrix;
  11202. /**
  11203. * Instanced buffer attribute representing the color of instances.
  11204. *
  11205. * @type {InstancedBufferAttribute}
  11206. */
  11207. this.instanceColor = instanceColor;
  11208. /**
  11209. * The node that represents the instance matrix data.
  11210. *
  11211. * @type {?Node}
  11212. */
  11213. this.instanceMatrixNode = null;
  11214. /**
  11215. * The node that represents the instance color data.
  11216. *
  11217. * @type {?Node}
  11218. * @default null
  11219. */
  11220. this.instanceColorNode = null;
  11221. /**
  11222. * The update type is set to `frame` since an update
  11223. * of instanced buffer data must be checked per frame.
  11224. *
  11225. * @type {string}
  11226. * @default 'frame'
  11227. */
  11228. this.updateType = NodeUpdateType.FRAME;
  11229. /**
  11230. * A reference to a buffer that is used by `instanceMatrixNode`.
  11231. *
  11232. * @type {?InstancedInterleavedBuffer}
  11233. */
  11234. this.buffer = null;
  11235. /**
  11236. * A reference to a buffer that is used by `instanceColorNode`.
  11237. *
  11238. * @type {?InstancedBufferAttribute}
  11239. */
  11240. this.bufferColor = null;
  11241. }
  11242. /**
  11243. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11244. * to predefined node variables for accumulation. That follows the same patterns
  11245. * like with morph and skinning nodes.
  11246. *
  11247. * @param {NodeBuilder} builder - The current node builder.
  11248. */
  11249. setup( builder ) {
  11250. const { instanceMatrix, instanceColor } = this;
  11251. const { count } = instanceMatrix;
  11252. let { instanceMatrixNode, instanceColorNode } = this;
  11253. if ( instanceMatrixNode === null ) {
  11254. // 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.
  11255. if ( count <= 1000 ) {
  11256. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11257. } else {
  11258. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11259. this.buffer = buffer;
  11260. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11261. const instanceBuffers = [
  11262. // F.Signature -> bufferAttribute( array, type, stride, offset )
  11263. bufferFn( buffer, 'vec4', 16, 0 ),
  11264. bufferFn( buffer, 'vec4', 16, 4 ),
  11265. bufferFn( buffer, 'vec4', 16, 8 ),
  11266. bufferFn( buffer, 'vec4', 16, 12 )
  11267. ];
  11268. instanceMatrixNode = mat4( ...instanceBuffers );
  11269. }
  11270. this.instanceMatrixNode = instanceMatrixNode;
  11271. }
  11272. if ( instanceColor && instanceColorNode === null ) {
  11273. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11274. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11275. this.bufferColor = buffer;
  11276. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11277. this.instanceColorNode = instanceColorNode;
  11278. }
  11279. // POSITION
  11280. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11281. positionLocal.assign( instancePosition );
  11282. // NORMAL
  11283. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11284. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11285. // ASSIGNS
  11286. normalLocal.assign( instanceNormal );
  11287. }
  11288. // COLOR
  11289. if ( this.instanceColorNode !== null ) {
  11290. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11291. }
  11292. }
  11293. /**
  11294. * Checks if the internal buffers required an update.
  11295. *
  11296. * @param {NodeFrame} frame - The current node frame.
  11297. */
  11298. update( /*frame*/ ) {
  11299. if ( this.buffer !== null ) {
  11300. // keep update ranges in sync
  11301. this.buffer.clearUpdateRanges();
  11302. this.buffer.updateRanges.push( ... this.instanceMatrix.updateRanges );
  11303. // update version if necessary
  11304. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.instanceMatrix.version !== this.buffer.version ) {
  11305. this.buffer.version = this.instanceMatrix.version;
  11306. }
  11307. }
  11308. if ( this.instanceColor && this.bufferColor !== null ) {
  11309. this.bufferColor.clearUpdateRanges();
  11310. this.bufferColor.updateRanges.push( ... this.instanceColor.updateRanges );
  11311. if ( this.instanceColor.usage !== DynamicDrawUsage && this.instanceColor.version !== this.bufferColor.version ) {
  11312. this.bufferColor.version = this.instanceColor.version;
  11313. }
  11314. }
  11315. }
  11316. }
  11317. /**
  11318. * TSL function for creating an instance node.
  11319. *
  11320. * @tsl
  11321. * @function
  11322. * @param {number} count - The number of instances.
  11323. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11324. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11325. * @returns {InstanceNode}
  11326. */
  11327. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11328. /**
  11329. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11330. * It allows an easier setup of the instance node.
  11331. *
  11332. * @augments InstanceNode
  11333. */
  11334. class InstancedMeshNode extends InstanceNode {
  11335. static get type() {
  11336. return 'InstancedMeshNode';
  11337. }
  11338. /**
  11339. * Constructs a new instanced mesh node.
  11340. *
  11341. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11342. */
  11343. constructor( instancedMesh ) {
  11344. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11345. super( count, instanceMatrix, instanceColor );
  11346. /**
  11347. * A reference to the instanced mesh.
  11348. *
  11349. * @type {InstancedMesh}
  11350. */
  11351. this.instancedMesh = instancedMesh;
  11352. }
  11353. }
  11354. /**
  11355. * TSL function for creating an instanced mesh node.
  11356. *
  11357. * @tsl
  11358. * @function
  11359. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11360. * @returns {InstancedMeshNode}
  11361. */
  11362. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11363. /**
  11364. * This node implements the vertex shader logic which is required
  11365. * when rendering 3D objects via batching. `BatchNode` must be used
  11366. * with instances of {@link BatchedMesh}.
  11367. *
  11368. * @augments Node
  11369. */
  11370. class BatchNode extends Node {
  11371. static get type() {
  11372. return 'BatchNode';
  11373. }
  11374. /**
  11375. * Constructs a new batch node.
  11376. *
  11377. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11378. */
  11379. constructor( batchMesh ) {
  11380. super( 'void' );
  11381. /**
  11382. * A reference to batched mesh.
  11383. *
  11384. * @type {BatchedMesh}
  11385. */
  11386. this.batchMesh = batchMesh;
  11387. /**
  11388. * The batching index node.
  11389. *
  11390. * @type {?IndexNode}
  11391. * @default null
  11392. */
  11393. this.batchingIdNode = null;
  11394. }
  11395. /**
  11396. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11397. * to predefined node variables for accumulation. That follows the same patterns
  11398. * like with morph and skinning nodes.
  11399. *
  11400. * @param {NodeBuilder} builder - The current node builder.
  11401. */
  11402. setup( builder ) {
  11403. if ( this.batchingIdNode === null ) {
  11404. if ( builder.getDrawIndex() === null ) {
  11405. this.batchingIdNode = instanceIndex;
  11406. } else {
  11407. this.batchingIdNode = drawIndex;
  11408. }
  11409. }
  11410. const getIndirectIndex = Fn( ( [ id ] ) => {
  11411. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  11412. const x = int( id ).mod( size );
  11413. const y = int( id ).div( size );
  11414. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11415. } ).setLayout( {
  11416. name: 'getIndirectIndex',
  11417. type: 'uint',
  11418. inputs: [
  11419. { name: 'id', type: 'int' }
  11420. ]
  11421. } );
  11422. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11423. const matricesTexture = this.batchMesh._matricesTexture;
  11424. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  11425. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  11426. const x = j.mod( size );
  11427. const y = j.div( size );
  11428. const batchingMatrix = mat4(
  11429. textureLoad( matricesTexture, ivec2( x, y ) ),
  11430. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11431. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11432. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11433. );
  11434. const colorsTexture = this.batchMesh._colorsTexture;
  11435. if ( colorsTexture !== null ) {
  11436. const getBatchingColor = Fn( ( [ id ] ) => {
  11437. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  11438. const j = id;
  11439. const x = j.mod( size );
  11440. const y = j.div( size );
  11441. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11442. } ).setLayout( {
  11443. name: 'getBatchingColor',
  11444. type: 'vec3',
  11445. inputs: [
  11446. { name: 'id', type: 'int' }
  11447. ]
  11448. } );
  11449. const color = getBatchingColor( indirectId );
  11450. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11451. }
  11452. const bm = mat3( batchingMatrix );
  11453. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11454. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11455. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11456. normalLocal.assign( batchingNormal );
  11457. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11458. tangentLocal.mulAssign( bm );
  11459. }
  11460. }
  11461. }
  11462. /**
  11463. * TSL function for creating a batch node.
  11464. *
  11465. * @tsl
  11466. * @function
  11467. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11468. * @returns {BatchNode}
  11469. */
  11470. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11471. /**
  11472. * This class enables element access on instances of {@link StorageBufferNode}.
  11473. * In most cases, it is indirectly used when accessing elements with the
  11474. * {@link StorageBufferNode#element} method.
  11475. *
  11476. * ```js
  11477. * const position = positionStorage.element( instanceIndex );
  11478. * ```
  11479. *
  11480. * @augments ArrayElementNode
  11481. */
  11482. class StorageArrayElementNode extends ArrayElementNode {
  11483. static get type() {
  11484. return 'StorageArrayElementNode';
  11485. }
  11486. /**
  11487. * Constructs storage buffer element node.
  11488. *
  11489. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11490. * @param {Node} indexNode - The index node that defines the element access.
  11491. */
  11492. constructor( storageBufferNode, indexNode ) {
  11493. super( storageBufferNode, indexNode );
  11494. /**
  11495. * This flag can be used for type testing.
  11496. *
  11497. * @type {boolean}
  11498. * @readonly
  11499. * @default true
  11500. */
  11501. this.isStorageArrayElementNode = true;
  11502. }
  11503. /**
  11504. * The storage buffer node.
  11505. *
  11506. * @param {Node} value
  11507. * @type {StorageBufferNode}
  11508. */
  11509. set storageBufferNode( value ) {
  11510. this.node = value;
  11511. }
  11512. get storageBufferNode() {
  11513. return this.node;
  11514. }
  11515. getMemberType( builder, name ) {
  11516. const structTypeNode = this.storageBufferNode.structTypeNode;
  11517. if ( structTypeNode ) {
  11518. return structTypeNode.getMemberType( builder, name );
  11519. }
  11520. return 'void';
  11521. }
  11522. setup( builder ) {
  11523. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11524. if ( this.node.isPBO === true ) {
  11525. builder.setupPBO( this.node );
  11526. }
  11527. }
  11528. return super.setup( builder );
  11529. }
  11530. generate( builder, output ) {
  11531. let snippet;
  11532. const isAssignContext = builder.context.assign;
  11533. //
  11534. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11535. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11536. snippet = builder.generatePBO( this );
  11537. } else {
  11538. snippet = this.node.build( builder );
  11539. }
  11540. } else {
  11541. snippet = super.generate( builder );
  11542. }
  11543. if ( isAssignContext !== true ) {
  11544. const type = this.getNodeType( builder );
  11545. snippet = builder.format( snippet, type, output );
  11546. }
  11547. return snippet;
  11548. }
  11549. }
  11550. /**
  11551. * TSL function for creating a storage element node.
  11552. *
  11553. * @tsl
  11554. * @function
  11555. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11556. * @param {Node} indexNode - The index node that defines the element access.
  11557. * @returns {StorageArrayElementNode}
  11558. */
  11559. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11560. /**
  11561. * This node is used in context of compute shaders and allows to define a
  11562. * storage buffer for data. A typical workflow is to create instances of
  11563. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11564. * setup up a compute shader that writes into the buffers and then convert
  11565. * the storage buffers to attribute nodes for rendering.
  11566. *
  11567. * ```js
  11568. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11569. *
  11570. * const computeInit = Fn( () => { // the compute shader
  11571. *
  11572. * const position = positionBuffer.element( instanceIndex );
  11573. *
  11574. * // compute position data
  11575. *
  11576. * position.x = 1;
  11577. * position.y = 1;
  11578. * position.z = 1;
  11579. *
  11580. * } )().compute( particleCount );
  11581. *
  11582. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11583. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11584. *
  11585. * renderer.computeAsync( computeInit );
  11586. *
  11587. * ```
  11588. *
  11589. * @augments BufferNode
  11590. */
  11591. class StorageBufferNode extends BufferNode {
  11592. static get type() {
  11593. return 'StorageBufferNode';
  11594. }
  11595. /**
  11596. * Constructs a new storage buffer node.
  11597. *
  11598. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11599. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11600. * @param {number} [bufferCount=0] - The buffer count.
  11601. */
  11602. constructor( value, bufferType = null, bufferCount = 0 ) {
  11603. let nodeType, structTypeNode = null;
  11604. if ( bufferType && bufferType.isStruct ) {
  11605. nodeType = 'struct';
  11606. structTypeNode = bufferType.layout;
  11607. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11608. bufferCount = value.count;
  11609. }
  11610. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11611. nodeType = getTypeFromLength( value.itemSize );
  11612. bufferCount = value.count;
  11613. } else {
  11614. nodeType = bufferType;
  11615. }
  11616. super( value, nodeType, bufferCount );
  11617. /**
  11618. * This flag can be used for type testing.
  11619. *
  11620. * @type {boolean}
  11621. * @readonly
  11622. * @default true
  11623. */
  11624. this.isStorageBufferNode = true;
  11625. /**
  11626. * The buffer struct type.
  11627. *
  11628. * @type {?StructTypeNode}
  11629. * @default null
  11630. */
  11631. this.structTypeNode = structTypeNode;
  11632. /**
  11633. * The access type of the texture node.
  11634. *
  11635. * @type {string}
  11636. * @default 'readWrite'
  11637. */
  11638. this.access = NodeAccess.READ_WRITE;
  11639. /**
  11640. * Whether the node is atomic or not.
  11641. *
  11642. * @type {boolean}
  11643. * @default false
  11644. */
  11645. this.isAtomic = false;
  11646. /**
  11647. * Whether the node represents a PBO or not.
  11648. * Only relevant for WebGL.
  11649. *
  11650. * @type {boolean}
  11651. * @default false
  11652. */
  11653. this.isPBO = false;
  11654. /**
  11655. * A reference to the internal buffer attribute node.
  11656. *
  11657. * @type {?BufferAttributeNode}
  11658. * @default null
  11659. */
  11660. this._attribute = null;
  11661. /**
  11662. * A reference to the internal varying node.
  11663. *
  11664. * @type {?VaryingNode}
  11665. * @default null
  11666. */
  11667. this._varying = null;
  11668. /**
  11669. * `StorageBufferNode` sets this property to `true` by default.
  11670. *
  11671. * @type {boolean}
  11672. * @default true
  11673. */
  11674. this.global = true;
  11675. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11676. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11677. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11678. else value.isStorageBufferAttribute = true;
  11679. }
  11680. }
  11681. /**
  11682. * This method is overwritten since the buffer data might be shared
  11683. * and thus the hash should be shared as well.
  11684. *
  11685. * @param {NodeBuilder} builder - The current node builder.
  11686. * @return {string} The hash.
  11687. */
  11688. getHash( builder ) {
  11689. if ( this.bufferCount === 0 ) {
  11690. let bufferData = builder.globalCache.getData( this.value );
  11691. if ( bufferData === undefined ) {
  11692. bufferData = {
  11693. node: this
  11694. };
  11695. builder.globalCache.setData( this.value, bufferData );
  11696. }
  11697. return bufferData.node.uuid;
  11698. }
  11699. return this.uuid;
  11700. }
  11701. /**
  11702. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11703. *
  11704. * @param {NodeBuilder} builder - The current node builder.
  11705. * @return {string} The input type.
  11706. */
  11707. getInputType( /*builder*/ ) {
  11708. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11709. }
  11710. /**
  11711. * Enables element access with the given index node.
  11712. *
  11713. * @param {IndexNode} indexNode - The index node.
  11714. * @return {StorageArrayElementNode} A node representing the element access.
  11715. */
  11716. element( indexNode ) {
  11717. return storageElement( this, indexNode );
  11718. }
  11719. /**
  11720. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11721. *
  11722. * @param {boolean} value - The value so set.
  11723. * @return {StorageBufferNode} A reference to this node.
  11724. */
  11725. setPBO( value ) {
  11726. this.isPBO = value;
  11727. return this;
  11728. }
  11729. /**
  11730. * Returns the `isPBO` value.
  11731. *
  11732. * @return {boolean} Whether the node represents a PBO or not.
  11733. */
  11734. getPBO() {
  11735. return this.isPBO;
  11736. }
  11737. /**
  11738. * Defines the node access.
  11739. *
  11740. * @param {string} value - The node access.
  11741. * @return {StorageBufferNode} A reference to this node.
  11742. */
  11743. setAccess( value ) {
  11744. this.access = value;
  11745. return this;
  11746. }
  11747. /**
  11748. * Convenience method for configuring a read-only node access.
  11749. *
  11750. * @return {StorageBufferNode} A reference to this node.
  11751. */
  11752. toReadOnly() {
  11753. return this.setAccess( NodeAccess.READ_ONLY );
  11754. }
  11755. /**
  11756. * Defines whether the node is atomic or not.
  11757. *
  11758. * @param {boolean} value - The atomic flag.
  11759. * @return {StorageBufferNode} A reference to this node.
  11760. */
  11761. setAtomic( value ) {
  11762. this.isAtomic = value;
  11763. return this;
  11764. }
  11765. /**
  11766. * Convenience method for making this node atomic.
  11767. *
  11768. * @return {StorageBufferNode} A reference to this node.
  11769. */
  11770. toAtomic() {
  11771. return this.setAtomic( true );
  11772. }
  11773. /**
  11774. * Returns attribute data for this storage buffer node.
  11775. *
  11776. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11777. */
  11778. getAttributeData() {
  11779. if ( this._attribute === null ) {
  11780. this._attribute = bufferAttribute( this.value );
  11781. this._varying = varying( this._attribute );
  11782. }
  11783. return {
  11784. attribute: this._attribute,
  11785. varying: this._varying
  11786. };
  11787. }
  11788. /**
  11789. * This method is overwritten since the node type from the availability of storage buffers
  11790. * and the attribute data.
  11791. *
  11792. * @param {NodeBuilder} builder - The current node builder.
  11793. * @return {string} The node type.
  11794. */
  11795. getNodeType( builder ) {
  11796. if ( this.structTypeNode !== null ) {
  11797. return this.structTypeNode.getNodeType( builder );
  11798. }
  11799. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11800. return super.getNodeType( builder );
  11801. }
  11802. const { attribute } = this.getAttributeData();
  11803. return attribute.getNodeType( builder );
  11804. }
  11805. /**
  11806. * Returns the type of a member of the struct.
  11807. *
  11808. * @param {NodeBuilder} builder - The current node builder.
  11809. * @param {string} name - The name of the member.
  11810. * @return {string} The type of the member.
  11811. */
  11812. getMemberType( builder, name ) {
  11813. if ( this.structTypeNode !== null ) {
  11814. return this.structTypeNode.getMemberType( builder, name );
  11815. }
  11816. return 'void';
  11817. }
  11818. /**
  11819. * Generates the code snippet of the storage buffer node.
  11820. *
  11821. * @param {NodeBuilder} builder - The current node builder.
  11822. * @return {string} The generated code snippet.
  11823. */
  11824. generate( builder ) {
  11825. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11826. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11827. return super.generate( builder );
  11828. }
  11829. const { attribute, varying } = this.getAttributeData();
  11830. const output = varying.build( builder );
  11831. builder.registerTransform( output, attribute );
  11832. return output;
  11833. }
  11834. }
  11835. /**
  11836. * TSL function for creating a storage buffer node.
  11837. *
  11838. * @tsl
  11839. * @function
  11840. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11841. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11842. * @param {number} [count=0] - The buffer count.
  11843. * @returns {StorageBufferNode}
  11844. */
  11845. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11846. /**
  11847. * @tsl
  11848. * @function
  11849. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11850. *
  11851. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11852. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  11853. * @param {number} count - The buffer count.
  11854. * @returns {StorageBufferNode}
  11855. */
  11856. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11857. warn( 'TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11858. return storage( value, type, count ).setPBO( true );
  11859. };
  11860. const _frameId = new WeakMap();
  11861. /**
  11862. * This node implements the vertex transformation shader logic which is required
  11863. * for skinning/skeletal animation.
  11864. *
  11865. * @augments Node
  11866. */
  11867. class SkinningNode extends Node {
  11868. static get type() {
  11869. return 'SkinningNode';
  11870. }
  11871. /**
  11872. * Constructs a new skinning node.
  11873. *
  11874. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11875. */
  11876. constructor( skinnedMesh ) {
  11877. super( 'void' );
  11878. /**
  11879. * The skinned mesh.
  11880. *
  11881. * @type {SkinnedMesh}
  11882. */
  11883. this.skinnedMesh = skinnedMesh;
  11884. /**
  11885. * The update type overwritten since skinning nodes are updated per object.
  11886. *
  11887. * @type {string}
  11888. */
  11889. this.updateType = NodeUpdateType.OBJECT;
  11890. //
  11891. /**
  11892. * The skin index attribute.
  11893. *
  11894. * @type {AttributeNode}
  11895. */
  11896. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  11897. /**
  11898. * The skin weight attribute.
  11899. *
  11900. * @type {AttributeNode}
  11901. */
  11902. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  11903. /**
  11904. * The bind matrix node.
  11905. *
  11906. * @type {Node<mat4>}
  11907. */
  11908. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  11909. /**
  11910. * The bind matrix inverse node.
  11911. *
  11912. * @type {Node<mat4>}
  11913. */
  11914. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  11915. /**
  11916. * The bind matrices as a uniform buffer node.
  11917. *
  11918. * @type {Node}
  11919. */
  11920. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11921. /**
  11922. * The current vertex position in local space.
  11923. *
  11924. * @type {Node<vec3>}
  11925. */
  11926. this.positionNode = positionLocal;
  11927. /**
  11928. * The result of vertex position in local space.
  11929. *
  11930. * @type {Node<vec3>}
  11931. */
  11932. this.toPositionNode = positionLocal;
  11933. /**
  11934. * The previous bind matrices as a uniform buffer node.
  11935. * Required for computing motion vectors.
  11936. *
  11937. * @type {?Node}
  11938. * @default null
  11939. */
  11940. this.previousBoneMatricesNode = null;
  11941. }
  11942. /**
  11943. * Transforms the given vertex position via skinning.
  11944. *
  11945. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11946. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  11947. * @return {Node<vec3>} The transformed vertex position.
  11948. */
  11949. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  11950. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11951. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11952. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11953. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11954. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11955. // POSITION
  11956. const skinVertex = bindMatrixNode.mul( position );
  11957. const skinned = add(
  11958. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  11959. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11960. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11961. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11962. );
  11963. return bindMatrixInverseNode.mul( skinned ).xyz;
  11964. }
  11965. /**
  11966. * Transforms the given vertex normal via skinning.
  11967. *
  11968. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11969. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11970. * @return {Node<vec3>} The transformed vertex normal.
  11971. */
  11972. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11973. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11974. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11975. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11976. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11977. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11978. // NORMAL
  11979. let skinMatrix = add(
  11980. skinWeightNode.x.mul( boneMatX ),
  11981. skinWeightNode.y.mul( boneMatY ),
  11982. skinWeightNode.z.mul( boneMatZ ),
  11983. skinWeightNode.w.mul( boneMatW )
  11984. );
  11985. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11986. return skinMatrix.transformDirection( normal ).xyz;
  11987. }
  11988. /**
  11989. * Computes the transformed/skinned vertex position of the previous frame.
  11990. *
  11991. * @param {NodeBuilder} builder - The current node builder.
  11992. * @return {Node<vec3>} The skinned position from the previous frame.
  11993. */
  11994. getPreviousSkinnedPosition( builder ) {
  11995. const skinnedMesh = builder.object;
  11996. if ( this.previousBoneMatricesNode === null ) {
  11997. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11998. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11999. }
  12000. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  12001. }
  12002. /**
  12003. * Returns `true` if bone matrices from the previous frame are required. Relevant
  12004. * when computing motion vectors with {@link VelocityNode}.
  12005. *
  12006. * @param {NodeBuilder} builder - The current node builder.
  12007. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  12008. */
  12009. needsPreviousBoneMatrices( builder ) {
  12010. const mrt = builder.renderer.getMRT();
  12011. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  12012. }
  12013. /**
  12014. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  12015. *
  12016. * @param {NodeBuilder} builder - The current node builder.
  12017. * @return {Node<vec3>} The transformed vertex position.
  12018. */
  12019. setup( builder ) {
  12020. if ( this.needsPreviousBoneMatrices( builder ) ) {
  12021. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  12022. }
  12023. const skinPosition = this.getSkinnedPosition();
  12024. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12025. //
  12026. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12027. const skinNormal = this.getSkinnedNormal();
  12028. normalLocal.assign( skinNormal );
  12029. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12030. tangentLocal.assign( skinNormal );
  12031. }
  12032. }
  12033. return skinPosition;
  12034. }
  12035. /**
  12036. * Generates the code snippet of the skinning node.
  12037. *
  12038. * @param {NodeBuilder} builder - The current node builder.
  12039. * @param {string} output - The current output.
  12040. * @return {string} The generated code snippet.
  12041. */
  12042. generate( builder, output ) {
  12043. if ( output !== 'void' ) {
  12044. return super.generate( builder, output );
  12045. }
  12046. }
  12047. /**
  12048. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12049. *
  12050. * @param {NodeFrame} frame - The current node frame.
  12051. */
  12052. update( frame ) {
  12053. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12054. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12055. _frameId.set( skeleton, frame.frameId );
  12056. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12057. skeleton.update();
  12058. }
  12059. }
  12060. /**
  12061. * TSL function for creating a skinning node.
  12062. *
  12063. * @tsl
  12064. * @function
  12065. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12066. * @returns {SkinningNode}
  12067. */
  12068. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12069. /**
  12070. * TSL function for computing skinning.
  12071. *
  12072. * @tsl
  12073. * @function
  12074. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12075. * @param {Node<vec3>} [toPosition=null] - The target position.
  12076. * @returns {SkinningNode}
  12077. */
  12078. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12079. const node = new SkinningNode( skinnedMesh );
  12080. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12081. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12082. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12083. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12084. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12085. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12086. node.toPositionNode = toPosition;
  12087. return nodeObject( node );
  12088. };
  12089. /**
  12090. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12091. * ```js
  12092. * Loop( count, ( { i } ) => {
  12093. *
  12094. * } );
  12095. * ```
  12096. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12097. * ```js
  12098. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12099. *
  12100. * } );
  12101. *```
  12102. * Nested loops can be defined in a compacted form:
  12103. * ```js
  12104. * Loop( 10, 5, ( { i, j } ) => {
  12105. *
  12106. * } );
  12107. * ```
  12108. * Loops that should run backwards can be defined like so:
  12109. * ```js
  12110. * Loop( { start: 10 }, () => {} );
  12111. * ```
  12112. * It is possible to execute with boolean values, similar to the `while` syntax.
  12113. * ```js
  12114. * const value = float( 0 ).toVar();
  12115. *
  12116. * Loop( value.lessThan( 10 ), () => {
  12117. *
  12118. * value.addAssign( 1 );
  12119. *
  12120. * } );
  12121. * ```
  12122. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12123. * @augments Node
  12124. */
  12125. class LoopNode extends Node {
  12126. static get type() {
  12127. return 'LoopNode';
  12128. }
  12129. /**
  12130. * Constructs a new loop node.
  12131. *
  12132. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12133. */
  12134. constructor( params = [] ) {
  12135. super();
  12136. this.params = params;
  12137. }
  12138. /**
  12139. * Returns a loop variable name based on an index. The pattern is
  12140. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12141. *
  12142. * @param {number} index - The index.
  12143. * @return {string} The loop variable name.
  12144. */
  12145. getVarName( index ) {
  12146. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12147. }
  12148. /**
  12149. * Returns properties about this node.
  12150. *
  12151. * @param {NodeBuilder} builder - The current node builder.
  12152. * @return {Object} The node properties.
  12153. */
  12154. getProperties( builder ) {
  12155. const properties = builder.getNodeProperties( this );
  12156. if ( properties.stackNode !== undefined ) return properties;
  12157. //
  12158. const inputs = {};
  12159. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12160. const param = this.params[ i ];
  12161. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12162. const type = ( param.isNode !== true && param.type ) || 'int';
  12163. inputs[ name ] = expression( name, type );
  12164. }
  12165. const stack = builder.addStack(); // TODO: cache() it
  12166. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  12167. properties.stackNode = stack;
  12168. const baseParam = this.params[ 0 ];
  12169. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12170. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  12171. }
  12172. builder.removeStack();
  12173. return properties;
  12174. }
  12175. /**
  12176. * This method is overwritten since the node type is inferred based on the loop configuration.
  12177. *
  12178. * @param {NodeBuilder} builder - The current node builder.
  12179. * @return {string} The node type.
  12180. */
  12181. getNodeType( builder ) {
  12182. const { returnsNode } = this.getProperties( builder );
  12183. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  12184. }
  12185. setup( builder ) {
  12186. // setup properties
  12187. this.getProperties( builder );
  12188. }
  12189. generate( builder ) {
  12190. const properties = this.getProperties( builder );
  12191. const params = this.params;
  12192. const stackNode = properties.stackNode;
  12193. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12194. const param = params[ i ];
  12195. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12196. if ( param.isNode ) {
  12197. if ( param.getNodeType( builder ) === 'bool' ) {
  12198. isWhile = true;
  12199. type = 'bool';
  12200. end = param.build( builder, type );
  12201. } else {
  12202. type = 'int';
  12203. name = this.getVarName( i );
  12204. start = '0';
  12205. end = param.build( builder, type );
  12206. condition = '<';
  12207. }
  12208. } else {
  12209. type = param.type || 'int';
  12210. name = param.name || this.getVarName( i );
  12211. start = param.start;
  12212. end = param.end;
  12213. condition = param.condition;
  12214. update = param.update;
  12215. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12216. else if ( start && start.isNode ) start = start.build( builder, type );
  12217. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12218. else if ( end && end.isNode ) end = end.build( builder, type );
  12219. if ( start !== undefined && end === undefined ) {
  12220. start = start + ' - 1';
  12221. end = '0';
  12222. condition = '>=';
  12223. } else if ( end !== undefined && start === undefined ) {
  12224. start = '0';
  12225. condition = '<';
  12226. }
  12227. if ( condition === undefined ) {
  12228. if ( Number( start ) > Number( end ) ) {
  12229. condition = '>=';
  12230. } else {
  12231. condition = '<';
  12232. }
  12233. }
  12234. }
  12235. let loopSnippet;
  12236. if ( isWhile ) {
  12237. loopSnippet = `while ( ${ end } )`;
  12238. } else {
  12239. const internalParam = { start, end};
  12240. //
  12241. const startSnippet = internalParam.start;
  12242. const endSnippet = internalParam.end;
  12243. let updateSnippet;
  12244. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12245. if ( update !== undefined && update !== null ) {
  12246. switch ( typeof update ) {
  12247. case 'function':
  12248. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12249. const snippet = flow.code.replace( /\t|;/g, '' );
  12250. updateSnippet = snippet;
  12251. break;
  12252. case 'number':
  12253. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12254. break;
  12255. case 'string':
  12256. updateSnippet = name + ' ' + update;
  12257. break;
  12258. default:
  12259. if ( update.isNode ) {
  12260. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12261. } else {
  12262. error( 'TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12263. updateSnippet = 'break /* invalid update */';
  12264. }
  12265. }
  12266. } else {
  12267. if ( type === 'int' || type === 'uint' ) {
  12268. update = condition.includes( '<' ) ? '++' : '--';
  12269. } else {
  12270. update = deltaOperator() + ' 1.';
  12271. }
  12272. updateSnippet = name + ' ' + update;
  12273. }
  12274. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12275. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12276. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12277. }
  12278. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12279. }
  12280. const stackSnippet = stackNode.build( builder, 'void' );
  12281. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  12282. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12283. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12284. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12285. }
  12286. builder.addFlowTab();
  12287. return returnsSnippet;
  12288. }
  12289. }
  12290. /**
  12291. * TSL function for creating a loop node.
  12292. *
  12293. * @tsl
  12294. * @function
  12295. * @param {...any} params - A list of parameters.
  12296. * @returns {LoopNode}
  12297. */
  12298. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  12299. /**
  12300. * TSL function for creating a `Continue()` expression.
  12301. *
  12302. * @tsl
  12303. * @function
  12304. * @returns {ExpressionNode}
  12305. */
  12306. const Continue = () => expression( 'continue' ).toStack();
  12307. /**
  12308. * TSL function for creating a `Break()` expression.
  12309. *
  12310. * @tsl
  12311. * @function
  12312. * @returns {ExpressionNode}
  12313. */
  12314. const Break = () => expression( 'break' ).toStack();
  12315. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12316. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12317. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12318. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12319. const y = texelIndex.div( width );
  12320. const x = texelIndex.sub( y.mul( width ) );
  12321. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12322. return bufferAttrib.mul( influence );
  12323. } );
  12324. function getEntry( geometry ) {
  12325. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12326. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12327. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12328. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12329. // into an array of data textures. Each layer represents a single morph target.
  12330. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12331. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12332. let entry = _morphTextures.get( geometry );
  12333. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12334. if ( entry !== undefined ) entry.texture.dispose();
  12335. const morphTargets = geometry.morphAttributes.position || [];
  12336. const morphNormals = geometry.morphAttributes.normal || [];
  12337. const morphColors = geometry.morphAttributes.color || [];
  12338. let vertexDataCount = 0;
  12339. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12340. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12341. if ( hasMorphColors === true ) vertexDataCount = 3;
  12342. let width = geometry.attributes.position.count * vertexDataCount;
  12343. let height = 1;
  12344. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12345. if ( width > maxTextureSize ) {
  12346. height = Math.ceil( width / maxTextureSize );
  12347. width = maxTextureSize;
  12348. }
  12349. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12350. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12351. bufferTexture.type = FloatType;
  12352. bufferTexture.needsUpdate = true;
  12353. // fill buffer
  12354. const vertexDataStride = vertexDataCount * 4;
  12355. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12356. const morphTarget = morphTargets[ i ];
  12357. const morphNormal = morphNormals[ i ];
  12358. const morphColor = morphColors[ i ];
  12359. const offset = width * height * 4 * i;
  12360. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12361. const stride = j * vertexDataStride;
  12362. if ( hasMorphPosition === true ) {
  12363. _morphVec4.fromBufferAttribute( morphTarget, j );
  12364. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12365. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12366. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12367. buffer[ offset + stride + 3 ] = 0;
  12368. }
  12369. if ( hasMorphNormals === true ) {
  12370. _morphVec4.fromBufferAttribute( morphNormal, j );
  12371. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12372. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12373. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12374. buffer[ offset + stride + 7 ] = 0;
  12375. }
  12376. if ( hasMorphColors === true ) {
  12377. _morphVec4.fromBufferAttribute( morphColor, j );
  12378. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12379. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12380. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12381. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12382. }
  12383. }
  12384. }
  12385. entry = {
  12386. count: morphTargetsCount,
  12387. texture: bufferTexture,
  12388. stride: vertexDataCount,
  12389. size: new Vector2( width, height )
  12390. };
  12391. _morphTextures.set( geometry, entry );
  12392. function disposeTexture() {
  12393. bufferTexture.dispose();
  12394. _morphTextures.delete( geometry );
  12395. geometry.removeEventListener( 'dispose', disposeTexture );
  12396. }
  12397. geometry.addEventListener( 'dispose', disposeTexture );
  12398. }
  12399. return entry;
  12400. }
  12401. /**
  12402. * This node implements the vertex transformation shader logic which is required
  12403. * for morph target animation.
  12404. *
  12405. * @augments Node
  12406. */
  12407. class MorphNode extends Node {
  12408. static get type() {
  12409. return 'MorphNode';
  12410. }
  12411. /**
  12412. * Constructs a new morph node.
  12413. *
  12414. * @param {Mesh} mesh - The mesh holding the morph targets.
  12415. */
  12416. constructor( mesh ) {
  12417. super( 'void' );
  12418. /**
  12419. * The mesh holding the morph targets.
  12420. *
  12421. * @type {Mesh}
  12422. */
  12423. this.mesh = mesh;
  12424. /**
  12425. * A uniform node which represents the morph base influence value.
  12426. *
  12427. * @type {UniformNode<float>}
  12428. */
  12429. this.morphBaseInfluence = uniform( 1 );
  12430. /**
  12431. * The update type overwritten since morph nodes are updated per object.
  12432. *
  12433. * @type {string}
  12434. */
  12435. this.updateType = NodeUpdateType.OBJECT;
  12436. }
  12437. /**
  12438. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12439. *
  12440. * @param {NodeBuilder} builder - The current node builder.
  12441. */
  12442. setup( builder ) {
  12443. const { geometry } = builder;
  12444. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12445. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12446. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12447. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12448. // nodes
  12449. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12450. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12451. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12452. const width = int( size.width );
  12453. Loop( morphTargetsCount, ( { i } ) => {
  12454. const influence = float( 0 ).toVar();
  12455. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12456. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12457. } else {
  12458. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12459. }
  12460. If( influence.notEqual( 0 ), () => {
  12461. if ( hasMorphPosition === true ) {
  12462. positionLocal.addAssign( getMorph( {
  12463. bufferMap,
  12464. influence,
  12465. stride,
  12466. width,
  12467. depth: i,
  12468. offset: int( 0 )
  12469. } ) );
  12470. }
  12471. if ( hasMorphNormals === true ) {
  12472. normalLocal.addAssign( getMorph( {
  12473. bufferMap,
  12474. influence,
  12475. stride,
  12476. width,
  12477. depth: i,
  12478. offset: int( 1 )
  12479. } ) );
  12480. }
  12481. } );
  12482. } );
  12483. }
  12484. /**
  12485. * Updates the state of the morphed mesh by updating the base influence.
  12486. *
  12487. * @param {NodeFrame} frame - The current node frame.
  12488. */
  12489. update( /*frame*/ ) {
  12490. const morphBaseInfluence = this.morphBaseInfluence;
  12491. if ( this.mesh.geometry.morphTargetsRelative ) {
  12492. morphBaseInfluence.value = 1;
  12493. } else {
  12494. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12495. }
  12496. }
  12497. }
  12498. /**
  12499. * TSL function for creating a morph node.
  12500. *
  12501. * @tsl
  12502. * @function
  12503. * @param {Mesh} mesh - The mesh holding the morph targets.
  12504. * @returns {MorphNode}
  12505. */
  12506. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12507. /**
  12508. * Base class for lighting nodes.
  12509. *
  12510. * @augments Node
  12511. */
  12512. class LightingNode extends Node {
  12513. static get type() {
  12514. return 'LightingNode';
  12515. }
  12516. /**
  12517. * Constructs a new lighting node.
  12518. */
  12519. constructor() {
  12520. super( 'vec3' );
  12521. /**
  12522. * This flag can be used for type testing.
  12523. *
  12524. * @type {boolean}
  12525. * @readonly
  12526. * @default true
  12527. */
  12528. this.isLightingNode = true;
  12529. }
  12530. }
  12531. /**
  12532. * A generic class that can be used by nodes which contribute
  12533. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12534. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12535. *
  12536. * @augments LightingNode
  12537. */
  12538. class AONode extends LightingNode {
  12539. static get type() {
  12540. return 'AONode';
  12541. }
  12542. /**
  12543. * Constructs a new AO node.
  12544. *
  12545. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12546. */
  12547. constructor( aoNode = null ) {
  12548. super();
  12549. /**
  12550. * The ambient occlusion node.
  12551. *
  12552. * @type {?Node<float>}
  12553. * @default null
  12554. */
  12555. this.aoNode = aoNode;
  12556. }
  12557. setup( builder ) {
  12558. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12559. }
  12560. }
  12561. /**
  12562. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12563. * by adding lighting specific context data. It represents the runtime context of
  12564. * {@link LightsNode}.
  12565. *
  12566. * @augments ContextNode
  12567. */
  12568. class LightingContextNode extends ContextNode {
  12569. static get type() {
  12570. return 'LightingContextNode';
  12571. }
  12572. /**
  12573. * Constructs a new lighting context node.
  12574. *
  12575. * @param {LightsNode} lightsNode - The lights node.
  12576. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12577. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12578. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12579. */
  12580. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12581. super( lightsNode );
  12582. /**
  12583. * The current lighting model.
  12584. *
  12585. * @type {?LightingModel}
  12586. * @default null
  12587. */
  12588. this.lightingModel = lightingModel;
  12589. /**
  12590. * A backdrop node.
  12591. *
  12592. * @type {?Node<vec3>}
  12593. * @default null
  12594. */
  12595. this.backdropNode = backdropNode;
  12596. /**
  12597. * A backdrop alpha node.
  12598. *
  12599. * @type {?Node<float>}
  12600. * @default null
  12601. */
  12602. this.backdropAlphaNode = backdropAlphaNode;
  12603. this._value = null;
  12604. }
  12605. /**
  12606. * Returns a lighting context object.
  12607. *
  12608. * @return {{
  12609. * radiance: Node<vec3>,
  12610. * irradiance: Node<vec3>,
  12611. * iblIrradiance: Node<vec3>,
  12612. * ambientOcclusion: Node<float>,
  12613. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12614. * backdrop: Node<vec3>,
  12615. * backdropAlpha: Node<float>
  12616. * }} The lighting context object.
  12617. */
  12618. getContext() {
  12619. const { backdropNode, backdropAlphaNode } = this;
  12620. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12621. directSpecular = vec3().toVar( 'directSpecular' ),
  12622. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12623. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12624. const reflectedLight = {
  12625. directDiffuse,
  12626. directSpecular,
  12627. indirectDiffuse,
  12628. indirectSpecular
  12629. };
  12630. const context = {
  12631. radiance: vec3().toVar( 'radiance' ),
  12632. irradiance: vec3().toVar( 'irradiance' ),
  12633. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12634. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12635. reflectedLight,
  12636. backdrop: backdropNode,
  12637. backdropAlpha: backdropAlphaNode
  12638. };
  12639. return context;
  12640. }
  12641. setup( builder ) {
  12642. this.value = this._value || ( this._value = this.getContext() );
  12643. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  12644. return super.setup( builder );
  12645. }
  12646. }
  12647. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  12648. /**
  12649. * A generic class that can be used by nodes which contribute
  12650. * irradiance to the scene. E.g. a light map node can be used
  12651. * as input for this module. Used in {@link NodeMaterial}.
  12652. *
  12653. * @augments LightingNode
  12654. */
  12655. class IrradianceNode extends LightingNode {
  12656. static get type() {
  12657. return 'IrradianceNode';
  12658. }
  12659. /**
  12660. * Constructs a new irradiance node.
  12661. *
  12662. * @param {Node<vec3>} node - A node contributing irradiance.
  12663. */
  12664. constructor( node ) {
  12665. super();
  12666. /**
  12667. * A node contributing irradiance.
  12668. *
  12669. * @type {Node<vec3>}
  12670. */
  12671. this.node = node;
  12672. }
  12673. setup( builder ) {
  12674. builder.context.irradiance.addAssign( this.node );
  12675. }
  12676. }
  12677. const _size$5 = /*@__PURE__*/ new Vector2();
  12678. /**
  12679. * A special type of texture node which represents the data of the current viewport
  12680. * as a texture. The module extracts data from the current bound framebuffer with
  12681. * a copy operation so no extra render pass is required to produce the texture data
  12682. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  12683. * variety of effects like refractive or transmissive materials.
  12684. *
  12685. * @augments TextureNode
  12686. */
  12687. class ViewportTextureNode extends TextureNode {
  12688. static get type() {
  12689. return 'ViewportTextureNode';
  12690. }
  12691. /**
  12692. * Constructs a new viewport texture node.
  12693. *
  12694. * @param {Node} [uvNode=screenUV] - The uv node.
  12695. * @param {?Node} [levelNode=null] - The level node.
  12696. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12697. */
  12698. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12699. let defaultFramebuffer = null;
  12700. if ( framebufferTexture === null ) {
  12701. defaultFramebuffer = new FramebufferTexture();
  12702. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  12703. framebufferTexture = defaultFramebuffer;
  12704. } else {
  12705. defaultFramebuffer = framebufferTexture;
  12706. }
  12707. super( framebufferTexture, uvNode, levelNode );
  12708. /**
  12709. * Whether to generate mipmaps or not.
  12710. *
  12711. * @type {boolean}
  12712. * @default false
  12713. */
  12714. this.generateMipmaps = false;
  12715. /**
  12716. * The reference framebuffer texture. This is used to store the framebuffer texture
  12717. * for the current render target. If the render target changes, a new framebuffer texture
  12718. * is created automatically.
  12719. *
  12720. * @type {FramebufferTexture}
  12721. * @default null
  12722. */
  12723. this.defaultFramebuffer = defaultFramebuffer;
  12724. /**
  12725. * This flag can be used for type testing.
  12726. *
  12727. * @type {boolean}
  12728. * @readonly
  12729. * @default true
  12730. */
  12731. this.isOutputTextureNode = true;
  12732. /**
  12733. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  12734. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  12735. *
  12736. * @type {string}
  12737. * @default 'frame'
  12738. */
  12739. this.updateBeforeType = NodeUpdateType.FRAME;
  12740. /**
  12741. * The framebuffer texture for the current renderer context.
  12742. *
  12743. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  12744. * @private
  12745. */
  12746. this._cacheTextures = new WeakMap();
  12747. }
  12748. /**
  12749. * This methods returns a texture for the given render target reference.
  12750. *
  12751. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  12752. * for different render contexts.
  12753. *
  12754. * @param {?RenderTarget} [reference=null] - The render target reference.
  12755. * @return {Texture} The framebuffer texture.
  12756. */
  12757. getTextureForReference( reference = null ) {
  12758. let defaultFramebuffer;
  12759. let cacheTextures;
  12760. if ( this.referenceNode ) {
  12761. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  12762. cacheTextures = this.referenceNode._cacheTextures;
  12763. } else {
  12764. defaultFramebuffer = this.defaultFramebuffer;
  12765. cacheTextures = this._cacheTextures;
  12766. }
  12767. if ( reference === null ) {
  12768. return defaultFramebuffer;
  12769. }
  12770. if ( cacheTextures.has( reference ) === false ) {
  12771. const framebufferTexture = defaultFramebuffer.clone();
  12772. cacheTextures.set( reference, framebufferTexture );
  12773. }
  12774. return cacheTextures.get( reference );
  12775. }
  12776. updateReference( frame ) {
  12777. const renderTarget = frame.renderer.getRenderTarget();
  12778. this.value = this.getTextureForReference( renderTarget );
  12779. return this.value;
  12780. }
  12781. updateBefore( frame ) {
  12782. const renderer = frame.renderer;
  12783. const renderTarget = renderer.getRenderTarget();
  12784. if ( renderTarget === null ) {
  12785. renderer.getDrawingBufferSize( _size$5 );
  12786. } else {
  12787. _size$5.set( renderTarget.width, renderTarget.height );
  12788. }
  12789. //
  12790. const framebufferTexture = this.getTextureForReference( renderTarget );
  12791. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  12792. framebufferTexture.image.width = _size$5.width;
  12793. framebufferTexture.image.height = _size$5.height;
  12794. framebufferTexture.needsUpdate = true;
  12795. }
  12796. //
  12797. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12798. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12799. renderer.copyFramebufferToTexture( framebufferTexture );
  12800. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12801. }
  12802. clone() {
  12803. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12804. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12805. return viewportTextureNode;
  12806. }
  12807. }
  12808. /**
  12809. * TSL function for creating a viewport texture node.
  12810. *
  12811. * @tsl
  12812. * @function
  12813. * @param {?Node} [uvNode=screenUV] - The uv node.
  12814. * @param {?Node} [levelNode=null] - The level node.
  12815. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12816. * @returns {ViewportTextureNode}
  12817. */
  12818. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12819. /**
  12820. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12821. *
  12822. * @tsl
  12823. * @function
  12824. * @param {?Node} [uvNode=screenUV] - The uv node.
  12825. * @param {?Node} [levelNode=null] - The level node.
  12826. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12827. * @returns {ViewportTextureNode}
  12828. */
  12829. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12830. let _sharedDepthbuffer = null;
  12831. /**
  12832. * Represents the depth of the current viewport as a texture. This module
  12833. * can be used in combination with viewport texture to achieve effects
  12834. * that require depth evaluation.
  12835. *
  12836. * @augments ViewportTextureNode
  12837. */
  12838. class ViewportDepthTextureNode extends ViewportTextureNode {
  12839. static get type() {
  12840. return 'ViewportDepthTextureNode';
  12841. }
  12842. /**
  12843. * Constructs a new viewport depth texture node.
  12844. *
  12845. * @param {Node} [uvNode=screenUV] - The uv node.
  12846. * @param {?Node} [levelNode=null] - The level node.
  12847. */
  12848. constructor( uvNode = screenUV, levelNode = null ) {
  12849. if ( _sharedDepthbuffer === null ) {
  12850. _sharedDepthbuffer = new DepthTexture();
  12851. }
  12852. super( uvNode, levelNode, _sharedDepthbuffer );
  12853. }
  12854. /**
  12855. * Overwritten so the method always returns the unique shared
  12856. * depth texture.
  12857. *
  12858. * @return {DepthTexture} The shared depth texture.
  12859. */
  12860. getTextureForReference() {
  12861. return _sharedDepthbuffer;
  12862. }
  12863. }
  12864. /**
  12865. * TSL function for a viewport depth texture node.
  12866. *
  12867. * @tsl
  12868. * @function
  12869. * @param {?Node} [uvNode=screenUV] - The uv node.
  12870. * @param {?Node} [levelNode=null] - The level node.
  12871. * @returns {ViewportDepthTextureNode}
  12872. */
  12873. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12874. /**
  12875. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12876. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12877. * fragment or for depth evaluation purposes.
  12878. *
  12879. * @augments Node
  12880. */
  12881. class ViewportDepthNode extends Node {
  12882. static get type() {
  12883. return 'ViewportDepthNode';
  12884. }
  12885. /**
  12886. * Constructs a new viewport depth node.
  12887. *
  12888. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12889. * @param {?Node} [valueNode=null] - The value node.
  12890. */
  12891. constructor( scope, valueNode = null ) {
  12892. super( 'float' );
  12893. /**
  12894. * The node behaves differently depending on which scope is selected.
  12895. *
  12896. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12897. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12898. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12899. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12900. *
  12901. * @type {('depth'|'depthBase'|'linearDepth')}
  12902. */
  12903. this.scope = scope;
  12904. /**
  12905. * Can be used to define a custom depth value.
  12906. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12907. *
  12908. * @type {?Node}
  12909. * @default null
  12910. */
  12911. this.valueNode = valueNode;
  12912. /**
  12913. * This flag can be used for type testing.
  12914. *
  12915. * @type {boolean}
  12916. * @readonly
  12917. * @default true
  12918. */
  12919. this.isViewportDepthNode = true;
  12920. }
  12921. generate( builder ) {
  12922. const { scope } = this;
  12923. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12924. return builder.getFragDepth();
  12925. }
  12926. return super.generate( builder );
  12927. }
  12928. setup( { camera } ) {
  12929. const { scope } = this;
  12930. const value = this.valueNode;
  12931. let node = null;
  12932. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12933. if ( value !== null ) {
  12934. node = depthBase().assign( value );
  12935. }
  12936. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12937. if ( camera.isPerspectiveCamera ) {
  12938. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12939. } else {
  12940. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12941. }
  12942. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12943. if ( value !== null ) {
  12944. if ( camera.isPerspectiveCamera ) {
  12945. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12946. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12947. } else {
  12948. node = value;
  12949. }
  12950. } else {
  12951. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12952. }
  12953. }
  12954. return node;
  12955. }
  12956. }
  12957. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12958. ViewportDepthNode.DEPTH = 'depth';
  12959. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12960. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12961. /**
  12962. * TSL function for converting a viewZ value to an orthographic depth value.
  12963. *
  12964. * @tsl
  12965. * @function
  12966. * @param {Node<float>} viewZ - The viewZ node.
  12967. * @param {Node<float>} near - The camera's near value.
  12968. * @param {Node<float>} far - The camera's far value.
  12969. * @returns {Node<float>}
  12970. */
  12971. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12972. /**
  12973. * TSL function for converting an orthographic depth value to a viewZ value.
  12974. *
  12975. * @tsl
  12976. * @function
  12977. * @param {Node<float>} depth - The orthographic depth.
  12978. * @param {Node<float>} near - The camera's near value.
  12979. * @param {Node<float>} far - The camera's far value.
  12980. * @returns {Node<float>}
  12981. */
  12982. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12983. /**
  12984. * TSL function for converting a viewZ value to a perspective depth value.
  12985. *
  12986. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12987. *
  12988. * @tsl
  12989. * @function
  12990. * @param {Node<float>} viewZ - The viewZ node.
  12991. * @param {Node<float>} near - The camera's near value.
  12992. * @param {Node<float>} far - The camera's far value.
  12993. * @returns {Node<float>}
  12994. */
  12995. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12996. /**
  12997. * TSL function for converting a perspective depth value to a viewZ value.
  12998. *
  12999. * @tsl
  13000. * @function
  13001. * @param {Node<float>} depth - The perspective depth.
  13002. * @param {Node<float>} near - The camera's near value.
  13003. * @param {Node<float>} far - The camera's far value.
  13004. * @returns {Node<float>}
  13005. */
  13006. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  13007. /**
  13008. * TSL function for converting a viewZ value to a logarithmic depth value.
  13009. *
  13010. * @tsl
  13011. * @function
  13012. * @param {Node<float>} viewZ - The viewZ node.
  13013. * @param {Node<float>} near - The camera's near value.
  13014. * @param {Node<float>} far - The camera's far value.
  13015. * @returns {Node<float>}
  13016. */
  13017. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  13018. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  13019. // The final logarithmic depth formula used here is adapted from one described in an
  13020. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  13021. // which was an improvement upon an earlier formula one described in an
  13022. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13023. // Ulrich's formula is the following:
  13024. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13025. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13026. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13027. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13028. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13029. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13030. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13031. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13032. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13033. // Outerra eventually made another improvement to their original "C-constant" variant,
  13034. // but it still does not incorporate the camera near plane (for this version,
  13035. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13036. // Here we make 4 changes to Ulrich's formula:
  13037. // 1. Clamp the camera near plane so we don't divide by 0.
  13038. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13039. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13040. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13041. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13042. // so we do the same here, hence the 'viewZ.negate()' call.
  13043. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13044. near = near.max( 1e-6 ).toVar();
  13045. const numerator = log2( viewZ.negate().div( near ) );
  13046. const denominator = log2( far.div( near ) );
  13047. return numerator.div( denominator );
  13048. };
  13049. /**
  13050. * TSL function for converting a logarithmic depth value to a viewZ value.
  13051. *
  13052. * @tsl
  13053. * @function
  13054. * @param {Node<float>} depth - The logarithmic depth.
  13055. * @param {Node<float>} near - The camera's near value.
  13056. * @param {Node<float>} far - The camera's far value.
  13057. * @returns {Node<float>}
  13058. */
  13059. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13060. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13061. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13062. // a negative viewZ).
  13063. const exponent = depth.mul( log( far.div( near ) ) );
  13064. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13065. };
  13066. /**
  13067. * TSL function for defining a value for the current fragment's depth.
  13068. *
  13069. * @tsl
  13070. * @function
  13071. * @param {Node<float>} value - The depth value to set.
  13072. * @returns {ViewportDepthNode<float>}
  13073. */
  13074. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13075. /**
  13076. * TSL object that represents the depth value for the current fragment.
  13077. *
  13078. * @tsl
  13079. * @type {ViewportDepthNode}
  13080. */
  13081. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13082. /**
  13083. * TSL function for converting a perspective depth value to linear depth.
  13084. *
  13085. * @tsl
  13086. * @function
  13087. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13088. * @returns {ViewportDepthNode<float>}
  13089. */
  13090. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13091. /**
  13092. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13093. *
  13094. * @tsl
  13095. * @type {ViewportDepthNode}
  13096. */
  13097. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13098. depth.assign = ( value ) => depthBase( value );
  13099. /**
  13100. * This node is used in {@link NodeMaterial} to setup the clipping
  13101. * which can happen hardware-accelerated (if supported) and optionally
  13102. * use alpha-to-coverage for anti-aliasing clipped edges.
  13103. *
  13104. * @augments Node
  13105. */
  13106. class ClippingNode extends Node {
  13107. static get type() {
  13108. return 'ClippingNode';
  13109. }
  13110. /**
  13111. * Constructs a new clipping node.
  13112. *
  13113. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13114. * the selected scope influences the behavior of the node and what type of code is generated.
  13115. */
  13116. constructor( scope = ClippingNode.DEFAULT ) {
  13117. super();
  13118. /**
  13119. * The node's scope. Similar to other nodes, the selected scope influences
  13120. * the behavior of the node and what type of code is generated.
  13121. *
  13122. * @type {('default'|'hardware'|'alphaToCoverage')}
  13123. */
  13124. this.scope = scope;
  13125. }
  13126. /**
  13127. * Setups the node depending on the selected scope.
  13128. *
  13129. * @param {NodeBuilder} builder - The current node builder.
  13130. * @return {Node} The result node.
  13131. */
  13132. setup( builder ) {
  13133. super.setup( builder );
  13134. const clippingContext = builder.clippingContext;
  13135. const { intersectionPlanes, unionPlanes } = clippingContext;
  13136. this.hardwareClipping = builder.material.hardwareClipping;
  13137. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13138. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13139. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13140. return this.setupHardwareClipping( unionPlanes, builder );
  13141. } else {
  13142. return this.setupDefault( intersectionPlanes, unionPlanes );
  13143. }
  13144. }
  13145. /**
  13146. * Setups alpha to coverage.
  13147. *
  13148. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13149. * @param {Array<Vector4>} unionPlanes - The union planes.
  13150. * @return {Node} The result node.
  13151. */
  13152. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13153. return Fn( () => {
  13154. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13155. const distanceGradient = float().toVar( 'distanceToGradient' );
  13156. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13157. const numUnionPlanes = unionPlanes.length;
  13158. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13159. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13160. Loop( numUnionPlanes, ( { i } ) => {
  13161. const plane = clippingPlanes.element( i );
  13162. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13163. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13164. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13165. } );
  13166. }
  13167. const numIntersectionPlanes = intersectionPlanes.length;
  13168. if ( numIntersectionPlanes > 0 ) {
  13169. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13170. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13171. Loop( numIntersectionPlanes, ( { i } ) => {
  13172. const plane = clippingPlanes.element( i );
  13173. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13174. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13175. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13176. } );
  13177. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13178. }
  13179. diffuseColor.a.mulAssign( clipOpacity );
  13180. diffuseColor.a.equal( 0.0 ).discard();
  13181. } )();
  13182. }
  13183. /**
  13184. * Setups the default clipping.
  13185. *
  13186. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13187. * @param {Array<Vector4>} unionPlanes - The union planes.
  13188. * @return {Node} The result node.
  13189. */
  13190. setupDefault( intersectionPlanes, unionPlanes ) {
  13191. return Fn( () => {
  13192. const numUnionPlanes = unionPlanes.length;
  13193. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13194. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13195. Loop( numUnionPlanes, ( { i } ) => {
  13196. const plane = clippingPlanes.element( i );
  13197. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13198. } );
  13199. }
  13200. const numIntersectionPlanes = intersectionPlanes.length;
  13201. if ( numIntersectionPlanes > 0 ) {
  13202. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13203. const clipped = bool( true ).toVar( 'clipped' );
  13204. Loop( numIntersectionPlanes, ( { i } ) => {
  13205. const plane = clippingPlanes.element( i );
  13206. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13207. } );
  13208. clipped.discard();
  13209. }
  13210. } )();
  13211. }
  13212. /**
  13213. * Setups hardware clipping.
  13214. *
  13215. * @param {Array<Vector4>} unionPlanes - The union planes.
  13216. * @param {NodeBuilder} builder - The current node builder.
  13217. * @return {Node} The result node.
  13218. */
  13219. setupHardwareClipping( unionPlanes, builder ) {
  13220. const numUnionPlanes = unionPlanes.length;
  13221. builder.enableHardwareClipping( numUnionPlanes );
  13222. return Fn( () => {
  13223. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13224. const hw_clip_distances = builtin( builder.getClipDistance() );
  13225. Loop( numUnionPlanes, ( { i } ) => {
  13226. const plane = clippingPlanes.element( i );
  13227. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13228. hw_clip_distances.element( i ).assign( distance );
  13229. } );
  13230. } )();
  13231. }
  13232. }
  13233. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13234. ClippingNode.DEFAULT = 'default';
  13235. ClippingNode.HARDWARE = 'hardware';
  13236. /**
  13237. * TSL function for setting up the default clipping logic.
  13238. *
  13239. * @tsl
  13240. * @function
  13241. * @returns {ClippingNode}
  13242. */
  13243. const clipping = () => nodeObject( new ClippingNode() );
  13244. /**
  13245. * TSL function for setting up alpha to coverage.
  13246. *
  13247. * @tsl
  13248. * @function
  13249. * @returns {ClippingNode}
  13250. */
  13251. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13252. /**
  13253. * TSL function for setting up hardware-based clipping.
  13254. *
  13255. * @tsl
  13256. * @function
  13257. * @returns {ClippingNode}
  13258. */
  13259. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13260. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13261. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13262. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13263. 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 ) ) ) ) ) );
  13264. } );
  13265. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13266. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13267. } );
  13268. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13269. // Find the discretized derivatives of our coordinates
  13270. const maxDeriv = max$1(
  13271. length( dFdx( position.xyz ) ),
  13272. length( dFdy( position.xyz ) )
  13273. );
  13274. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13275. // Find two nearest log-discretized noise scales
  13276. const pixScales = vec2(
  13277. exp2( floor( log2( pixScale ) ) ),
  13278. exp2( ceil( log2( pixScale ) ) )
  13279. );
  13280. // Compute alpha thresholds at our two noise scales
  13281. const alpha = vec2(
  13282. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13283. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13284. );
  13285. // Factor to interpolate lerp with
  13286. const lerpFactor = fract( log2( pixScale ) );
  13287. // Interpolate alpha threshold from noise at two scales
  13288. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13289. // Pass into CDF to compute uniformly distrib threshold
  13290. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13291. const cases = vec3(
  13292. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13293. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13294. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13295. // Find our final, uniformly distributed alpha threshold (ατ)
  13296. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13297. // Avoids ατ == 0. Could also do ατ =1-ατ
  13298. return clamp( threshold, 1.0e-6, 1.0 );
  13299. } ).setLayout( {
  13300. name: 'getAlphaHashThreshold',
  13301. type: 'float',
  13302. inputs: [
  13303. { name: 'position', type: 'vec3' }
  13304. ]
  13305. } );
  13306. /**
  13307. * An attribute node for representing vertex colors.
  13308. *
  13309. * @augments AttributeNode
  13310. */
  13311. class VertexColorNode extends AttributeNode {
  13312. static get type() {
  13313. return 'VertexColorNode';
  13314. }
  13315. /**
  13316. * Constructs a new vertex color node.
  13317. *
  13318. * @param {number} index - The attribute index.
  13319. */
  13320. constructor( index ) {
  13321. super( null, 'vec4' );
  13322. /**
  13323. * This flag can be used for type testing.
  13324. *
  13325. * @type {boolean}
  13326. * @readonly
  13327. * @default true
  13328. */
  13329. this.isVertexColorNode = true;
  13330. /**
  13331. * The attribute index to enable more than one sets of vertex colors.
  13332. *
  13333. * @type {number}
  13334. * @default 0
  13335. */
  13336. this.index = index;
  13337. }
  13338. /**
  13339. * Overwrites the default implementation by honoring the attribute index.
  13340. *
  13341. * @param {NodeBuilder} builder - The current node builder.
  13342. * @return {string} The attribute name.
  13343. */
  13344. getAttributeName( /*builder*/ ) {
  13345. const index = this.index;
  13346. return 'color' + ( index > 0 ? index : '' );
  13347. }
  13348. generate( builder ) {
  13349. const attributeName = this.getAttributeName( builder );
  13350. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13351. let result;
  13352. if ( geometryAttribute === true ) {
  13353. result = super.generate( builder );
  13354. } else {
  13355. // Vertex color fallback should be white
  13356. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13357. }
  13358. return result;
  13359. }
  13360. serialize( data ) {
  13361. super.serialize( data );
  13362. data.index = this.index;
  13363. }
  13364. deserialize( data ) {
  13365. super.deserialize( data );
  13366. this.index = data.index;
  13367. }
  13368. }
  13369. /**
  13370. * TSL function for creating a reference node.
  13371. *
  13372. * @tsl
  13373. * @function
  13374. * @param {number} [index=0] - The attribute index.
  13375. * @returns {VertexColorNode}
  13376. */
  13377. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13378. /**
  13379. * Represents a "Color Burn" blend mode.
  13380. *
  13381. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13382. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13383. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13384. *
  13385. * @tsl
  13386. * @function
  13387. * @param {Node<vec3>} base - The base color.
  13388. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13389. * @return {Node<vec3>} The result.
  13390. */
  13391. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13392. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13393. } ).setLayout( {
  13394. name: 'blendBurn',
  13395. type: 'vec3',
  13396. inputs: [
  13397. { name: 'base', type: 'vec3' },
  13398. { name: 'blend', type: 'vec3' }
  13399. ]
  13400. } );
  13401. /**
  13402. * Represents a "Color Dodge" blend mode.
  13403. *
  13404. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13405. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13406. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13407. *
  13408. * @tsl
  13409. * @function
  13410. * @param {Node<vec3>} base - The base color.
  13411. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13412. * @return {Node<vec3>} The result.
  13413. */
  13414. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13415. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13416. } ).setLayout( {
  13417. name: 'blendDodge',
  13418. type: 'vec3',
  13419. inputs: [
  13420. { name: 'base', type: 'vec3' },
  13421. { name: 'blend', type: 'vec3' }
  13422. ]
  13423. } );
  13424. /**
  13425. * Represents a "Screen" blend mode.
  13426. *
  13427. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13428. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13429. * effects.
  13430. *
  13431. * @tsl
  13432. * @function
  13433. * @param {Node<vec3>} base - The base color.
  13434. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13435. * @return {Node<vec3>} The result.
  13436. */
  13437. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13438. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13439. } ).setLayout( {
  13440. name: 'blendScreen',
  13441. type: 'vec3',
  13442. inputs: [
  13443. { name: 'base', type: 'vec3' },
  13444. { name: 'blend', type: 'vec3' }
  13445. ]
  13446. } );
  13447. /**
  13448. * Represents a "Overlay" blend mode.
  13449. *
  13450. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13451. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13452. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13453. *
  13454. * @tsl
  13455. * @function
  13456. * @param {Node<vec3>} base - The base color.
  13457. * @param {Node<vec3>} blend - The blend color
  13458. * @return {Node<vec3>} The result.
  13459. */
  13460. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13461. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13462. } ).setLayout( {
  13463. name: 'blendOverlay',
  13464. type: 'vec3',
  13465. inputs: [
  13466. { name: 'base', type: 'vec3' },
  13467. { name: 'blend', type: 'vec3' }
  13468. ]
  13469. } );
  13470. /**
  13471. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13472. * It assumes both input colors have non-premultiplied alpha.
  13473. *
  13474. * @tsl
  13475. * @function
  13476. * @param {Node<vec4>} base - The base color.
  13477. * @param {Node<vec4>} blend - The blend color
  13478. * @return {Node<vec4>} The result.
  13479. */
  13480. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13481. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13482. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13483. } ).setLayout( {
  13484. name: 'blendColor',
  13485. type: 'vec4',
  13486. inputs: [
  13487. { name: 'base', type: 'vec4' },
  13488. { name: 'blend', type: 'vec4' }
  13489. ]
  13490. } );
  13491. /**
  13492. * Premultiplies the RGB channels of a color by its alpha channel.
  13493. *
  13494. * This function is useful for converting a non-premultiplied alpha color
  13495. * into a premultiplied alpha format, where the RGB values are scaled
  13496. * by the alpha value. Premultiplied alpha is often used in graphics
  13497. * rendering for certain operations, such as compositing and image processing.
  13498. *
  13499. * @tsl
  13500. * @function
  13501. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13502. * @return {Node<vec4>} The color with premultiplied alpha.
  13503. */
  13504. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13505. return vec4( color.rgb.mul( color.a ), color.a );
  13506. }, { color: 'vec4', return: 'vec4' } );
  13507. /**
  13508. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13509. *
  13510. * This function is useful for converting a premultiplied alpha color
  13511. * back into a non-premultiplied alpha format, where the RGB values are
  13512. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13513. * rendering for certain operations, such as compositing and image processing.
  13514. *
  13515. * @tsl
  13516. * @function
  13517. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13518. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13519. */
  13520. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13521. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13522. return vec4( color.rgb.div( color.a ), color.a );
  13523. }, { color: 'vec4', return: 'vec4' } );
  13524. // Deprecated
  13525. /**
  13526. * @tsl
  13527. * @function
  13528. * @deprecated since r171. Use {@link blendBurn} instead.
  13529. *
  13530. * @param {...any} params
  13531. * @returns {Function}
  13532. */
  13533. const burn = ( ...params ) => { // @deprecated, r171
  13534. warn( 'TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13535. return blendBurn( params );
  13536. };
  13537. /**
  13538. * @tsl
  13539. * @function
  13540. * @deprecated since r171. Use {@link blendDodge} instead.
  13541. *
  13542. * @param {...any} params
  13543. * @returns {Function}
  13544. */
  13545. const dodge = ( ...params ) => { // @deprecated, r171
  13546. warn( 'TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13547. return blendDodge( params );
  13548. };
  13549. /**
  13550. * @tsl
  13551. * @function
  13552. * @deprecated since r171. Use {@link blendScreen} instead.
  13553. *
  13554. * @param {...any} params
  13555. * @returns {Function}
  13556. */
  13557. const screen = ( ...params ) => { // @deprecated, r171
  13558. warn( 'TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13559. return blendScreen( params );
  13560. };
  13561. /**
  13562. * @tsl
  13563. * @function
  13564. * @deprecated since r171. Use {@link blendOverlay} instead.
  13565. *
  13566. * @param {...any} params
  13567. * @returns {Function}
  13568. */
  13569. const overlay = ( ...params ) => { // @deprecated, r171
  13570. warn( 'TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13571. return blendOverlay( params );
  13572. };
  13573. /**
  13574. * Base class for all node materials.
  13575. *
  13576. * @augments Material
  13577. */
  13578. class NodeMaterial extends Material {
  13579. static get type() {
  13580. return 'NodeMaterial';
  13581. }
  13582. /**
  13583. * Represents the type of the node material.
  13584. *
  13585. * @type {string}
  13586. */
  13587. get type() {
  13588. return this.constructor.type;
  13589. }
  13590. set type( _value ) { /* */ }
  13591. /**
  13592. * Constructs a new node material.
  13593. */
  13594. constructor() {
  13595. super();
  13596. /**
  13597. * This flag can be used for type testing.
  13598. *
  13599. * @type {boolean}
  13600. * @readonly
  13601. * @default true
  13602. */
  13603. this.isNodeMaterial = true;
  13604. /**
  13605. * Whether this material is affected by fog or not.
  13606. *
  13607. * @type {boolean}
  13608. * @default true
  13609. */
  13610. this.fog = true;
  13611. /**
  13612. * Whether this material is affected by lights or not.
  13613. *
  13614. * @type {boolean}
  13615. * @default false
  13616. */
  13617. this.lights = false;
  13618. /**
  13619. * Whether this material uses hardware clipping or not.
  13620. * This property is managed by the engine and should not be
  13621. * modified by apps.
  13622. *
  13623. * @type {boolean}
  13624. * @default false
  13625. */
  13626. this.hardwareClipping = false;
  13627. /**
  13628. * Node materials which set their `lights` property to `true`
  13629. * are affected by all lights of the scene. Sometimes selective
  13630. * lighting is wanted which means only _some_ lights in the scene
  13631. * affect a material. This can be achieved by creating an instance
  13632. * of {@link LightsNode} with a list of selective
  13633. * lights and assign the node to this property.
  13634. *
  13635. * ```js
  13636. * const customLightsNode = lights( [ light1, light2 ] );
  13637. * material.lightsNode = customLightsNode;
  13638. * ```
  13639. *
  13640. * @type {?LightsNode}
  13641. * @default null
  13642. */
  13643. this.lightsNode = null;
  13644. /**
  13645. * The environment of node materials can be defined by an environment
  13646. * map assigned to the `envMap` property or by `Scene.environment`
  13647. * if the node material is a PBR material. This node property allows to overwrite
  13648. * the default behavior and define the environment with a custom node.
  13649. *
  13650. * ```js
  13651. * material.envNode = pmremTexture( renderTarget.texture );
  13652. * ```
  13653. *
  13654. * @type {?Node<vec3>}
  13655. * @default null
  13656. */
  13657. this.envNode = null;
  13658. /**
  13659. * The lighting of node materials might be influenced by ambient occlusion.
  13660. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13661. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13662. * the default and define the ambient occlusion with a custom node instead.
  13663. *
  13664. * If you don't want to overwrite the diffuse color but modify the existing
  13665. * values instead, use {@link materialAO}.
  13666. *
  13667. * @type {?Node<float>}
  13668. * @default null
  13669. */
  13670. this.aoNode = null;
  13671. /**
  13672. * The diffuse color of node materials is by default inferred from the
  13673. * `color` and `map` properties. This node property allows to overwrite the default
  13674. * and define the diffuse color with a node instead.
  13675. *
  13676. * ```js
  13677. * material.colorNode = color( 0xff0000 ); // define red color
  13678. * ```
  13679. *
  13680. * If you don't want to overwrite the diffuse color but modify the existing
  13681. * values instead, use {@link materialColor}.
  13682. *
  13683. * ```js
  13684. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  13685. * ```
  13686. *
  13687. * @type {?Node<vec3>}
  13688. * @default null
  13689. */
  13690. this.colorNode = null;
  13691. /**
  13692. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  13693. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  13694. * and define the normals with a node instead.
  13695. *
  13696. * If you don't want to overwrite the normals but modify the existing values instead,
  13697. * use {@link materialNormal}.
  13698. *
  13699. * @type {?Node<vec3>}
  13700. * @default null
  13701. */
  13702. this.normalNode = null;
  13703. /**
  13704. * The opacity of node materials is by default inferred from the `opacity`
  13705. * and `alphaMap` properties. This node property allows to overwrite the default
  13706. * and define the opacity with a node instead.
  13707. *
  13708. * If you don't want to overwrite the normals but modify the existing
  13709. * value instead, use {@link materialOpacity}.
  13710. *
  13711. * @type {?Node<float>}
  13712. * @default null
  13713. */
  13714. this.opacityNode = null;
  13715. /**
  13716. * This node can be used to implement a variety of filter-like effects. The idea is
  13717. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  13718. * to create an arbitrary effect and then assign the node composition to this property.
  13719. * Everything behind the object using this material will now be affected by a filter.
  13720. *
  13721. * ```js
  13722. * const material = new NodeMaterial()
  13723. * material.transparent = true;
  13724. *
  13725. * // everything behind the object will be monochromatic
  13726. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  13727. * ```
  13728. *
  13729. * Backdrop computations are part of the lighting so only lit materials can use this property.
  13730. *
  13731. * @type {?Node<vec3>}
  13732. * @default null
  13733. */
  13734. this.backdropNode = null;
  13735. /**
  13736. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  13737. *
  13738. * @type {?Node<float>}
  13739. * @default null
  13740. */
  13741. this.backdropAlphaNode = null;
  13742. /**
  13743. * The alpha test of node materials is by default inferred from the `alphaTest`
  13744. * property. This node property allows to overwrite the default and define the
  13745. * alpha test with a node instead.
  13746. *
  13747. * If you don't want to overwrite the alpha test but modify the existing
  13748. * value instead, use {@link materialAlphaTest}.
  13749. *
  13750. * @type {?Node<float>}
  13751. * @default null
  13752. */
  13753. this.alphaTestNode = null;
  13754. /**
  13755. * Discards the fragment if the mask value is `false`.
  13756. *
  13757. * @type {?Node<bool>}
  13758. * @default null
  13759. */
  13760. this.maskNode = null;
  13761. /**
  13762. * The local vertex positions are computed based on multiple factors like the
  13763. * attribute data, morphing or skinning. This node property allows to overwrite
  13764. * the default and define local vertex positions with nodes instead.
  13765. *
  13766. * If you don't want to overwrite the vertex positions but modify the existing
  13767. * values instead, use {@link positionLocal}.
  13768. *
  13769. *```js
  13770. * material.positionNode = positionLocal.add( displace );
  13771. * ```
  13772. *
  13773. * @type {?Node<vec3>}
  13774. * @default null
  13775. */
  13776. this.positionNode = null;
  13777. /**
  13778. * This node property is intended for logic which modifies geometry data once or per animation step.
  13779. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  13780. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  13781. * can be implemented.
  13782. *
  13783. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  13784. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  13785. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  13786. * eventually assigned to `geometryNode`.
  13787. *
  13788. * @type {?Function}
  13789. * @default null
  13790. */
  13791. this.geometryNode = null;
  13792. /**
  13793. * Allows to overwrite depth values in the fragment shader.
  13794. *
  13795. * @type {?Node<float>}
  13796. * @default null
  13797. */
  13798. this.depthNode = null;
  13799. /**
  13800. * Allows to overwrite the position used for shadow map rendering which
  13801. * is by default {@link positionWorld}, the vertex position
  13802. * in world space.
  13803. *
  13804. * @type {?Node<float>}
  13805. * @default null
  13806. */
  13807. this.receivedShadowPositionNode = null;
  13808. /**
  13809. * Allows to overwrite the geometry position used for shadow map projection which
  13810. * is by default {@link positionLocal}, the vertex position in local space.
  13811. *
  13812. * @type {?Node<float>}
  13813. * @default null
  13814. */
  13815. this.castShadowPositionNode = null;
  13816. /**
  13817. * This node can be used to influence how an object using this node material
  13818. * receive shadows.
  13819. *
  13820. * ```js
  13821. * const totalShadows = float( 1 ).toVar();
  13822. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  13823. * totalShadows.mulAssign( shadow );
  13824. * //return float( 1 ); // bypass received shadows
  13825. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  13826. * } );
  13827. *
  13828. * @type {?(Function|FunctionNode<vec4>)}
  13829. * @default null
  13830. */
  13831. this.receivedShadowNode = null;
  13832. /**
  13833. * This node can be used to influence how an object using this node material
  13834. * casts shadows. To apply a color to shadows, you can simply do:
  13835. *
  13836. * ```js
  13837. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  13838. * ```
  13839. *
  13840. * Which can be nice to fake colored shadows of semi-transparent objects. It
  13841. * is also common to use the property with `Fn` function so checks are performed
  13842. * per fragment.
  13843. *
  13844. * ```js
  13845. * materialCustomShadow.castShadowNode = Fn( () => {
  13846. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  13847. * return materialColor;
  13848. * } )();
  13849. * ```
  13850. *
  13851. * @type {?Node<vec4>}
  13852. * @default null
  13853. */
  13854. this.castShadowNode = null;
  13855. /**
  13856. * This node can be used to define the final output of the material.
  13857. *
  13858. * TODO: Explain the differences to `fragmentNode`.
  13859. *
  13860. * @type {?Node<vec4>}
  13861. * @default null
  13862. */
  13863. this.outputNode = null;
  13864. /**
  13865. * MRT configuration is done on renderer or pass level. This node allows to
  13866. * overwrite what values are written into MRT targets on material level. This
  13867. * can be useful for implementing selective FX features that should only affect
  13868. * specific objects.
  13869. *
  13870. * @type {?MRTNode}
  13871. * @default null
  13872. */
  13873. this.mrtNode = null;
  13874. /**
  13875. * This node property can be used if you need complete freedom in implementing
  13876. * the fragment shader. Assigning a node will replace the built-in material
  13877. * logic used in the fragment stage.
  13878. *
  13879. * @type {?Node<vec4>}
  13880. * @default null
  13881. */
  13882. this.fragmentNode = null;
  13883. /**
  13884. * This node property can be used if you need complete freedom in implementing
  13885. * the vertex shader. Assigning a node will replace the built-in material logic
  13886. * used in the vertex stage.
  13887. *
  13888. * @type {?Node<vec4>}
  13889. * @default null
  13890. */
  13891. this.vertexNode = null;
  13892. // Deprecated properties
  13893. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  13894. get: () => {
  13895. return this.receivedShadowPositionNode;
  13896. },
  13897. set: ( value ) => {
  13898. warn( 'NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  13899. this.receivedShadowPositionNode = value;
  13900. }
  13901. } );
  13902. }
  13903. /**
  13904. * Allows to define a custom cache key that influence the material key computation
  13905. * for render objects.
  13906. *
  13907. * @return {string} The custom cache key.
  13908. */
  13909. customProgramCacheKey() {
  13910. return this.type + getCacheKey$1( this );
  13911. }
  13912. /**
  13913. * Builds this material with the given node builder.
  13914. *
  13915. * @param {NodeBuilder} builder - The current node builder.
  13916. */
  13917. build( builder ) {
  13918. this.setup( builder );
  13919. }
  13920. /**
  13921. * Setups a node material observer with the given builder.
  13922. *
  13923. * @param {NodeBuilder} builder - The current node builder.
  13924. * @return {NodeMaterialObserver} The node material observer.
  13925. */
  13926. setupObserver( builder ) {
  13927. return new NodeMaterialObserver( builder );
  13928. }
  13929. /**
  13930. * Setups the vertex and fragment stage of this node material.
  13931. *
  13932. * @param {NodeBuilder} builder - The current node builder.
  13933. */
  13934. setup( builder ) {
  13935. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  13936. builder.context.setupPositionView = () => this.setupPositionView( builder );
  13937. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  13938. const renderer = builder.renderer;
  13939. const renderTarget = renderer.getRenderTarget();
  13940. // < VERTEX STAGE >
  13941. builder.addStack();
  13942. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  13943. const vertexNode = this.vertexNode || mvp;
  13944. builder.stack.outputNode = vertexNode;
  13945. this.setupHardwareClipping( builder );
  13946. if ( this.geometryNode !== null ) {
  13947. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  13948. }
  13949. builder.addFlow( 'vertex', builder.removeStack() );
  13950. // < FRAGMENT STAGE >
  13951. builder.addStack();
  13952. let resultNode;
  13953. const clippingNode = this.setupClipping( builder );
  13954. if ( this.depthWrite === true || this.depthTest === true ) {
  13955. // only write depth if depth buffer is configured
  13956. if ( renderTarget !== null ) {
  13957. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  13958. } else {
  13959. if ( renderer.depth === true ) this.setupDepth( builder );
  13960. }
  13961. }
  13962. if ( this.fragmentNode === null ) {
  13963. this.setupDiffuseColor( builder );
  13964. this.setupVariants( builder );
  13965. const outgoingLightNode = this.setupLighting( builder );
  13966. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  13967. // force unsigned floats - useful for RenderTargets
  13968. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  13969. resultNode = this.setupOutput( builder, basicOutput );
  13970. // OUTPUT NODE
  13971. output.assign( resultNode );
  13972. //
  13973. const isCustomOutput = this.outputNode !== null;
  13974. if ( isCustomOutput ) resultNode = this.outputNode;
  13975. // MRT
  13976. if ( renderTarget !== null ) {
  13977. const mrt = renderer.getMRT();
  13978. const materialMRT = this.mrtNode;
  13979. if ( mrt !== null ) {
  13980. if ( isCustomOutput ) output.assign( resultNode );
  13981. resultNode = mrt;
  13982. if ( materialMRT !== null ) {
  13983. resultNode = mrt.merge( materialMRT );
  13984. }
  13985. } else if ( materialMRT !== null ) {
  13986. resultNode = materialMRT;
  13987. }
  13988. }
  13989. } else {
  13990. let fragmentNode = this.fragmentNode;
  13991. if ( fragmentNode.isOutputStructNode !== true ) {
  13992. fragmentNode = vec4( fragmentNode );
  13993. }
  13994. resultNode = this.setupOutput( builder, fragmentNode );
  13995. }
  13996. builder.stack.outputNode = resultNode;
  13997. builder.addFlow( 'fragment', builder.removeStack() );
  13998. // < OBSERVER >
  13999. builder.observer = this.setupObserver( builder );
  14000. }
  14001. /**
  14002. * Setups the clipping node.
  14003. *
  14004. * @param {NodeBuilder} builder - The current node builder.
  14005. * @return {ClippingNode} The clipping node.
  14006. */
  14007. setupClipping( builder ) {
  14008. if ( builder.clippingContext === null ) return null;
  14009. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  14010. let result = null;
  14011. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  14012. const samples = builder.renderer.samples;
  14013. if ( this.alphaToCoverage && samples > 1 ) {
  14014. // to be added to flow when the color/alpha value has been determined
  14015. result = clippingAlpha();
  14016. } else {
  14017. builder.stack.add( clipping() );
  14018. }
  14019. }
  14020. return result;
  14021. }
  14022. /**
  14023. * Setups the hardware clipping if available on the current device.
  14024. *
  14025. * @param {NodeBuilder} builder - The current node builder.
  14026. */
  14027. setupHardwareClipping( builder ) {
  14028. this.hardwareClipping = false;
  14029. if ( builder.clippingContext === null ) return;
  14030. const candidateCount = builder.clippingContext.unionPlanes.length;
  14031. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14032. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14033. builder.stack.add( hardwareClipping() );
  14034. this.hardwareClipping = true;
  14035. }
  14036. return;
  14037. }
  14038. /**
  14039. * Setups the depth of this material.
  14040. *
  14041. * @param {NodeBuilder} builder - The current node builder.
  14042. */
  14043. setupDepth( builder ) {
  14044. const { renderer, camera } = builder;
  14045. // Depth
  14046. let depthNode = this.depthNode;
  14047. if ( depthNode === null ) {
  14048. const mrt = renderer.getMRT();
  14049. if ( mrt && mrt.has( 'depth' ) ) {
  14050. depthNode = mrt.get( 'depth' );
  14051. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14052. if ( camera.isPerspectiveCamera ) {
  14053. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14054. } else {
  14055. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14056. }
  14057. }
  14058. }
  14059. if ( depthNode !== null ) {
  14060. depth.assign( depthNode ).toStack();
  14061. }
  14062. }
  14063. /**
  14064. * Setups the position node in view space. This method exists
  14065. * so derived node materials can modify the implementation e.g. sprite materials.
  14066. *
  14067. * @param {NodeBuilder} builder - The current node builder.
  14068. * @return {Node<vec3>} The position in view space.
  14069. */
  14070. setupPositionView( /*builder*/ ) {
  14071. return modelViewMatrix.mul( positionLocal ).xyz;
  14072. }
  14073. /**
  14074. * Setups the position in clip space.
  14075. *
  14076. * @param {NodeBuilder} builder - The current node builder.
  14077. * @return {Node<vec4>} The position in view space.
  14078. */
  14079. setupModelViewProjection( /*builder*/ ) {
  14080. return cameraProjectionMatrix.mul( positionView );
  14081. }
  14082. /**
  14083. * Setups the logic for the vertex stage.
  14084. *
  14085. * @param {NodeBuilder} builder - The current node builder.
  14086. * @return {Node<vec4>} The position in clip space.
  14087. */
  14088. setupVertex( builder ) {
  14089. builder.addStack();
  14090. this.setupPosition( builder );
  14091. builder.context.vertex = builder.removeStack();
  14092. return modelViewProjection;
  14093. }
  14094. /**
  14095. * Setups the computation of the position in local space.
  14096. *
  14097. * @param {NodeBuilder} builder - The current node builder.
  14098. * @return {Node<vec3>} The position in local space.
  14099. */
  14100. setupPosition( builder ) {
  14101. const { object, geometry } = builder;
  14102. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14103. morphReference( object ).toStack();
  14104. }
  14105. if ( object.isSkinnedMesh === true ) {
  14106. skinning( object ).toStack();
  14107. }
  14108. if ( this.displacementMap ) {
  14109. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14110. const displacementScale = materialReference( 'displacementScale', 'float' );
  14111. const displacementBias = materialReference( 'displacementBias', 'float' );
  14112. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14113. }
  14114. if ( object.isBatchedMesh ) {
  14115. batch( object ).toStack();
  14116. }
  14117. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14118. instancedMesh( object ).toStack();
  14119. }
  14120. if ( this.positionNode !== null ) {
  14121. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14122. }
  14123. return positionLocal;
  14124. }
  14125. /**
  14126. * Setups the computation of the material's diffuse color.
  14127. *
  14128. * @param {NodeBuilder} builder - The current node builder.
  14129. * @param {BufferGeometry} geometry - The geometry.
  14130. */
  14131. setupDiffuseColor( { object, geometry } ) {
  14132. // MASK
  14133. if ( this.maskNode !== null ) {
  14134. // Discard if the mask is `false`
  14135. bool( this.maskNode ).not().discard();
  14136. }
  14137. // COLOR
  14138. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14139. // VERTEX COLORS
  14140. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14141. colorNode = colorNode.mul( vertexColor() );
  14142. }
  14143. // INSTANCED COLORS
  14144. if ( object.instanceColor ) {
  14145. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14146. colorNode = instanceColor.mul( colorNode );
  14147. }
  14148. if ( object.isBatchedMesh && object._colorsTexture ) {
  14149. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14150. colorNode = batchColor.mul( colorNode );
  14151. }
  14152. // DIFFUSE COLOR
  14153. diffuseColor.assign( colorNode );
  14154. // OPACITY
  14155. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14156. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14157. // ALPHA TEST
  14158. let alphaTestNode = null;
  14159. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14160. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14161. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14162. }
  14163. // ALPHA HASH
  14164. if ( this.alphaHash === true ) {
  14165. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14166. }
  14167. // OPAQUE
  14168. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  14169. if ( isOpaque ) {
  14170. diffuseColor.a.assign( 1.0 );
  14171. } else if ( alphaTestNode === null ) {
  14172. diffuseColor.a.lessThanEqual( 0 ).discard();
  14173. }
  14174. }
  14175. /**
  14176. * Abstract interface method that can be implemented by derived materials
  14177. * to setup material-specific node variables.
  14178. *
  14179. * @abstract
  14180. * @param {NodeBuilder} builder - The current node builder.
  14181. */
  14182. setupVariants( /*builder*/ ) {
  14183. // Interface function.
  14184. }
  14185. /**
  14186. * Setups the outgoing light node variable
  14187. *
  14188. * @return {Node<vec3>} The outgoing light node.
  14189. */
  14190. setupOutgoingLight() {
  14191. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14192. }
  14193. /**
  14194. * Setups the normal node from the material.
  14195. *
  14196. * @return {Node<vec3>} The normal node.
  14197. */
  14198. setupNormal() {
  14199. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14200. }
  14201. /**
  14202. * Setups the environment node from the material.
  14203. *
  14204. * @param {NodeBuilder} builder - The current node builder.
  14205. * @return {Node<vec4>} The environment node.
  14206. */
  14207. setupEnvironment( /*builder*/ ) {
  14208. let node = null;
  14209. if ( this.envNode ) {
  14210. node = this.envNode;
  14211. } else if ( this.envMap ) {
  14212. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14213. }
  14214. return node;
  14215. }
  14216. /**
  14217. * Setups the light map node from the material.
  14218. *
  14219. * @param {NodeBuilder} builder - The current node builder.
  14220. * @return {Node<vec3>} The light map node.
  14221. */
  14222. setupLightMap( builder ) {
  14223. let node = null;
  14224. if ( builder.material.lightMap ) {
  14225. node = new IrradianceNode( materialLightMap );
  14226. }
  14227. return node;
  14228. }
  14229. /**
  14230. * Setups the lights node based on the scene, environment and material.
  14231. *
  14232. * @param {NodeBuilder} builder - The current node builder.
  14233. * @return {LightsNode} The lights node.
  14234. */
  14235. setupLights( builder ) {
  14236. const materialLightsNode = [];
  14237. //
  14238. const envNode = this.setupEnvironment( builder );
  14239. if ( envNode && envNode.isLightingNode ) {
  14240. materialLightsNode.push( envNode );
  14241. }
  14242. const lightMapNode = this.setupLightMap( builder );
  14243. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14244. materialLightsNode.push( lightMapNode );
  14245. }
  14246. if ( this.aoNode !== null || builder.material.aoMap ) {
  14247. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14248. materialLightsNode.push( new AONode( aoNode ) );
  14249. }
  14250. let lightsN = this.lightsNode || builder.lightsNode;
  14251. if ( materialLightsNode.length > 0 ) {
  14252. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14253. }
  14254. return lightsN;
  14255. }
  14256. /**
  14257. * This method should be implemented by most derived materials
  14258. * since it defines the material's lighting model.
  14259. *
  14260. * @abstract
  14261. * @param {NodeBuilder} builder - The current node builder.
  14262. * @return {LightingModel} The lighting model.
  14263. */
  14264. setupLightingModel( /*builder*/ ) {
  14265. // Interface function.
  14266. }
  14267. /**
  14268. * Setups the outgoing light node.
  14269. *
  14270. * @param {NodeBuilder} builder - The current node builder.
  14271. * @return {Node<vec3>} The outgoing light node.
  14272. */
  14273. setupLighting( builder ) {
  14274. const { material } = builder;
  14275. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14276. // OUTGOING LIGHT
  14277. const lights = this.lights === true || this.lightsNode !== null;
  14278. const lightsNode = lights ? this.setupLights( builder ) : null;
  14279. let outgoingLightNode = this.setupOutgoingLight( builder );
  14280. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14281. const lightingModel = this.setupLightingModel( builder ) || null;
  14282. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14283. } else if ( backdropNode !== null ) {
  14284. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14285. }
  14286. // EMISSIVE
  14287. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14288. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14289. outgoingLightNode = outgoingLightNode.add( emissive );
  14290. }
  14291. return outgoingLightNode;
  14292. }
  14293. /**
  14294. * Setup the fog.
  14295. *
  14296. * @param {NodeBuilder} builder - The current node builder.
  14297. * @param {Node<vec4>} outputNode - The existing output node.
  14298. * @return {Node<vec4>} The output node.
  14299. */
  14300. setupFog( builder, outputNode ) {
  14301. const fogNode = builder.fogNode;
  14302. if ( fogNode ) {
  14303. output.assign( outputNode );
  14304. outputNode = vec4( fogNode.toVar() );
  14305. }
  14306. return outputNode;
  14307. }
  14308. /**
  14309. * Setups premultiplied alpha.
  14310. *
  14311. * @param {NodeBuilder} builder - The current node builder.
  14312. * @param {Node<vec4>} outputNode - The existing output node.
  14313. * @return {Node<vec4>} The output node.
  14314. */
  14315. setupPremultipliedAlpha( builder, outputNode ) {
  14316. return premultiplyAlpha( outputNode );
  14317. }
  14318. /**
  14319. * Setups the output node.
  14320. *
  14321. * @param {NodeBuilder} builder - The current node builder.
  14322. * @param {Node<vec4>} outputNode - The existing output node.
  14323. * @return {Node<vec4>} The output node.
  14324. */
  14325. setupOutput( builder, outputNode ) {
  14326. // FOG
  14327. if ( this.fog === true ) {
  14328. outputNode = this.setupFog( builder, outputNode );
  14329. }
  14330. // PREMULTIPLIED ALPHA
  14331. if ( this.premultipliedAlpha === true ) {
  14332. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14333. }
  14334. return outputNode;
  14335. }
  14336. /**
  14337. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14338. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14339. * defining all material properties of the classic type in the node type.
  14340. *
  14341. * @param {Material} material - The material to copy properties with their values to this node material.
  14342. */
  14343. setDefaultValues( material ) {
  14344. // This approach is to reuse the native refreshUniforms*
  14345. // and turn available the use of features like transmission and environment in core
  14346. for ( const property in material ) {
  14347. const value = material[ property ];
  14348. if ( this[ property ] === undefined ) {
  14349. this[ property ] = value;
  14350. if ( value && value.clone ) this[ property ] = value.clone();
  14351. }
  14352. }
  14353. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14354. for ( const key in descriptors ) {
  14355. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14356. descriptors[ key ].get !== undefined ) {
  14357. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14358. }
  14359. }
  14360. }
  14361. /**
  14362. * Serializes this material to JSON.
  14363. *
  14364. * @param {?(Object|string)} meta - The meta information for serialization.
  14365. * @return {Object} The serialized node.
  14366. */
  14367. toJSON( meta ) {
  14368. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14369. if ( isRoot ) {
  14370. meta = {
  14371. textures: {},
  14372. images: {},
  14373. nodes: {}
  14374. };
  14375. }
  14376. const data = Material.prototype.toJSON.call( this, meta );
  14377. const nodeChildren = getNodeChildren( this );
  14378. data.inputNodes = {};
  14379. for ( const { property, childNode } of nodeChildren ) {
  14380. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14381. }
  14382. // TODO: Copied from Object3D.toJSON
  14383. function extractFromCache( cache ) {
  14384. const values = [];
  14385. for ( const key in cache ) {
  14386. const data = cache[ key ];
  14387. delete data.metadata;
  14388. values.push( data );
  14389. }
  14390. return values;
  14391. }
  14392. if ( isRoot ) {
  14393. const textures = extractFromCache( meta.textures );
  14394. const images = extractFromCache( meta.images );
  14395. const nodes = extractFromCache( meta.nodes );
  14396. if ( textures.length > 0 ) data.textures = textures;
  14397. if ( images.length > 0 ) data.images = images;
  14398. if ( nodes.length > 0 ) data.nodes = nodes;
  14399. }
  14400. return data;
  14401. }
  14402. /**
  14403. * Copies the properties of the given node material to this instance.
  14404. *
  14405. * @param {NodeMaterial} source - The material to copy.
  14406. * @return {NodeMaterial} A reference to this node material.
  14407. */
  14408. copy( source ) {
  14409. this.lightsNode = source.lightsNode;
  14410. this.envNode = source.envNode;
  14411. this.colorNode = source.colorNode;
  14412. this.normalNode = source.normalNode;
  14413. this.opacityNode = source.opacityNode;
  14414. this.backdropNode = source.backdropNode;
  14415. this.backdropAlphaNode = source.backdropAlphaNode;
  14416. this.alphaTestNode = source.alphaTestNode;
  14417. this.maskNode = source.maskNode;
  14418. this.positionNode = source.positionNode;
  14419. this.geometryNode = source.geometryNode;
  14420. this.depthNode = source.depthNode;
  14421. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14422. this.castShadowPositionNode = source.castShadowPositionNode;
  14423. this.receivedShadowNode = source.receivedShadowNode;
  14424. this.castShadowNode = source.castShadowNode;
  14425. this.outputNode = source.outputNode;
  14426. this.mrtNode = source.mrtNode;
  14427. this.fragmentNode = source.fragmentNode;
  14428. this.vertexNode = source.vertexNode;
  14429. return super.copy( source );
  14430. }
  14431. }
  14432. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14433. /**
  14434. * Node material version of {@link LineBasicMaterial}.
  14435. *
  14436. * @augments NodeMaterial
  14437. */
  14438. class LineBasicNodeMaterial extends NodeMaterial {
  14439. static get type() {
  14440. return 'LineBasicNodeMaterial';
  14441. }
  14442. /**
  14443. * Constructs a new line basic node material.
  14444. *
  14445. * @param {Object} [parameters] - The configuration parameter.
  14446. */
  14447. constructor( parameters ) {
  14448. super();
  14449. /**
  14450. * This flag can be used for type testing.
  14451. *
  14452. * @type {boolean}
  14453. * @readonly
  14454. * @default true
  14455. */
  14456. this.isLineBasicNodeMaterial = true;
  14457. this.setDefaultValues( _defaultValues$d );
  14458. this.setValues( parameters );
  14459. }
  14460. }
  14461. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14462. /**
  14463. * Node material version of {@link LineDashedMaterial}.
  14464. *
  14465. * @augments NodeMaterial
  14466. */
  14467. class LineDashedNodeMaterial extends NodeMaterial {
  14468. static get type() {
  14469. return 'LineDashedNodeMaterial';
  14470. }
  14471. /**
  14472. * Constructs a new line dashed node material.
  14473. *
  14474. * @param {Object} [parameters] - The configuration parameter.
  14475. */
  14476. constructor( parameters ) {
  14477. super();
  14478. /**
  14479. * This flag can be used for type testing.
  14480. *
  14481. * @type {boolean}
  14482. * @readonly
  14483. * @default true
  14484. */
  14485. this.isLineDashedNodeMaterial = true;
  14486. this.setDefaultValues( _defaultValues$c );
  14487. /**
  14488. * The dash offset.
  14489. *
  14490. * @type {number}
  14491. * @default 0
  14492. */
  14493. this.dashOffset = 0;
  14494. /**
  14495. * The offset of dash materials is by default inferred from the `dashOffset`
  14496. * property. This node property allows to overwrite the default
  14497. * and define the offset with a node instead.
  14498. *
  14499. * If you don't want to overwrite the offset but modify the existing
  14500. * value instead, use {@link materialLineDashOffset}.
  14501. *
  14502. * @type {?Node<float>}
  14503. * @default null
  14504. */
  14505. this.offsetNode = null;
  14506. /**
  14507. * The scale of dash materials is by default inferred from the `scale`
  14508. * property. This node property allows to overwrite the default
  14509. * and define the scale with a node instead.
  14510. *
  14511. * If you don't want to overwrite the scale but modify the existing
  14512. * value instead, use {@link materialLineScale}.
  14513. *
  14514. * @type {?Node<float>}
  14515. * @default null
  14516. */
  14517. this.dashScaleNode = null;
  14518. /**
  14519. * The dash size of dash materials is by default inferred from the `dashSize`
  14520. * property. This node property allows to overwrite the default
  14521. * and define the dash size with a node instead.
  14522. *
  14523. * If you don't want to overwrite the dash size but modify the existing
  14524. * value instead, use {@link materialLineDashSize}.
  14525. *
  14526. * @type {?Node<float>}
  14527. * @default null
  14528. */
  14529. this.dashSizeNode = null;
  14530. /**
  14531. * The gap size of dash materials is by default inferred from the `gapSize`
  14532. * property. This node property allows to overwrite the default
  14533. * and define the gap size with a node instead.
  14534. *
  14535. * If you don't want to overwrite the gap size but modify the existing
  14536. * value instead, use {@link materialLineGapSize}.
  14537. *
  14538. * @type {?Node<float>}
  14539. * @default null
  14540. */
  14541. this.gapSizeNode = null;
  14542. this.setValues( parameters );
  14543. }
  14544. /**
  14545. * Setups the dash specific node variables.
  14546. *
  14547. * @param {NodeBuilder} builder - The current node builder.
  14548. */
  14549. setupVariants( /* builder */ ) {
  14550. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14551. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14552. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14553. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14554. dashSize.assign( dashSizeNode );
  14555. gapSize.assign( gapSizeNode );
  14556. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14557. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14558. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14559. }
  14560. }
  14561. let _sharedFramebuffer = null;
  14562. /**
  14563. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14564. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14565. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14566. *
  14567. * @augments ViewportTextureNode
  14568. */
  14569. class ViewportSharedTextureNode extends ViewportTextureNode {
  14570. static get type() {
  14571. return 'ViewportSharedTextureNode';
  14572. }
  14573. /**
  14574. * Constructs a new viewport shared texture node.
  14575. *
  14576. * @param {Node} [uvNode=screenUV] - The uv node.
  14577. * @param {?Node} [levelNode=null] - The level node.
  14578. */
  14579. constructor( uvNode = screenUV, levelNode = null ) {
  14580. if ( _sharedFramebuffer === null ) {
  14581. _sharedFramebuffer = new FramebufferTexture();
  14582. }
  14583. super( uvNode, levelNode, _sharedFramebuffer );
  14584. }
  14585. /**
  14586. * Overwritten so the method always returns the unique shared
  14587. * framebuffer texture.
  14588. *
  14589. * @return {FramebufferTexture} The shared framebuffer texture.
  14590. */
  14591. getTextureForReference() {
  14592. return _sharedFramebuffer;
  14593. }
  14594. updateReference() {
  14595. return this;
  14596. }
  14597. }
  14598. /**
  14599. * TSL function for creating a shared viewport texture node.
  14600. *
  14601. * @tsl
  14602. * @function
  14603. * @param {?Node} [uvNode=screenUV] - The uv node.
  14604. * @param {?Node} [levelNode=null] - The level node.
  14605. * @returns {ViewportSharedTextureNode}
  14606. */
  14607. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14608. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14609. /**
  14610. * This node material can be used to render lines with a size larger than one
  14611. * by representing them as instanced meshes.
  14612. *
  14613. * @augments NodeMaterial
  14614. */
  14615. class Line2NodeMaterial extends NodeMaterial {
  14616. static get type() {
  14617. return 'Line2NodeMaterial';
  14618. }
  14619. /**
  14620. * Constructs a new node material for wide line rendering.
  14621. *
  14622. * @param {Object} [parameters={}] - The configuration parameter.
  14623. */
  14624. constructor( parameters = {} ) {
  14625. super();
  14626. /**
  14627. * This flag can be used for type testing.
  14628. *
  14629. * @type {boolean}
  14630. * @readonly
  14631. * @default true
  14632. */
  14633. this.isLine2NodeMaterial = true;
  14634. this.setDefaultValues( _defaultValues$b );
  14635. /**
  14636. * Whether vertex colors should be used or not.
  14637. *
  14638. * @type {boolean}
  14639. * @default false
  14640. */
  14641. this.useColor = parameters.vertexColors;
  14642. /**
  14643. * The dash offset.
  14644. *
  14645. * @type {number}
  14646. * @default 0
  14647. */
  14648. this.dashOffset = 0;
  14649. /**
  14650. * Defines the lines color.
  14651. *
  14652. * @type {?Node<vec3>}
  14653. * @default null
  14654. */
  14655. this.lineColorNode = null;
  14656. /**
  14657. * Defines the offset.
  14658. *
  14659. * @type {?Node<float>}
  14660. * @default null
  14661. */
  14662. this.offsetNode = null;
  14663. /**
  14664. * Defines the dash scale.
  14665. *
  14666. * @type {?Node<float>}
  14667. * @default null
  14668. */
  14669. this.dashScaleNode = null;
  14670. /**
  14671. * Defines the dash size.
  14672. *
  14673. * @type {?Node<float>}
  14674. * @default null
  14675. */
  14676. this.dashSizeNode = null;
  14677. /**
  14678. * Defines the gap size.
  14679. *
  14680. * @type {?Node<float>}
  14681. * @default null
  14682. */
  14683. this.gapSizeNode = null;
  14684. /**
  14685. * Blending is set to `NoBlending` since transparency
  14686. * is not supported, yet.
  14687. *
  14688. * @type {number}
  14689. * @default 0
  14690. */
  14691. this.blending = NoBlending;
  14692. this._useDash = parameters.dashed;
  14693. this._useAlphaToCoverage = true;
  14694. this._useWorldUnits = false;
  14695. this.setValues( parameters );
  14696. }
  14697. /**
  14698. * Setups the vertex and fragment stage of this node material.
  14699. *
  14700. * @param {NodeBuilder} builder - The current node builder.
  14701. */
  14702. setup( builder ) {
  14703. const { renderer } = builder;
  14704. const useAlphaToCoverage = this._useAlphaToCoverage;
  14705. const useColor = this.useColor;
  14706. const useDash = this._useDash;
  14707. const useWorldUnits = this._useWorldUnits;
  14708. const trimSegment = Fn( ( { start, end } ) => {
  14709. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  14710. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  14711. const nearEstimate = b.mul( -0.5 ).div( a );
  14712. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  14713. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  14714. } ).setLayout( {
  14715. name: 'trimSegment',
  14716. type: 'vec4',
  14717. inputs: [
  14718. { name: 'start', type: 'vec4' },
  14719. { name: 'end', type: 'vec4' }
  14720. ]
  14721. } );
  14722. this.vertexNode = Fn( () => {
  14723. const instanceStart = attribute( 'instanceStart' );
  14724. const instanceEnd = attribute( 'instanceEnd' );
  14725. // camera space
  14726. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  14727. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  14728. if ( useDash ) {
  14729. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14730. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14731. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  14732. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  14733. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  14734. lineDistance = lineDistance.add( offsetNode );
  14735. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  14736. }
  14737. if ( useWorldUnits ) {
  14738. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  14739. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  14740. }
  14741. const aspect = viewport.z.div( viewport.w );
  14742. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  14743. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  14744. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  14745. // perhaps there is a more elegant solution -- WestLangley
  14746. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  14747. If( perspective, () => {
  14748. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  14749. end.assign( trimSegment( { start: start, end: end } ) );
  14750. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  14751. start.assign( trimSegment( { start: end, end: start } ) );
  14752. } );
  14753. } );
  14754. // clip space
  14755. const clipStart = cameraProjectionMatrix.mul( start );
  14756. const clipEnd = cameraProjectionMatrix.mul( end );
  14757. // ndc space
  14758. const ndcStart = clipStart.xyz.div( clipStart.w );
  14759. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  14760. // direction
  14761. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  14762. // account for clip-space aspect ratio
  14763. dir.x.assign( dir.x.mul( aspect ) );
  14764. dir.assign( dir.normalize() );
  14765. const clip = vec4().toVar();
  14766. if ( useWorldUnits ) {
  14767. // get the offset direction as perpendicular to the view vector
  14768. const worldDir = end.xyz.sub( start.xyz ).normalize();
  14769. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  14770. const worldUp = worldDir.cross( tmpFwd ).normalize();
  14771. const worldFwd = worldDir.cross( worldUp );
  14772. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  14773. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  14774. // height offset
  14775. const hw = materialLineWidth.mul( 0.5 );
  14776. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  14777. // don't extend the line if we're rendering dashes because we
  14778. // won't be rendering the endcaps
  14779. if ( ! useDash ) {
  14780. // cap extension
  14781. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  14782. // add width to the box
  14783. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  14784. // endcaps
  14785. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  14786. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  14787. } );
  14788. }
  14789. // project the worldpos
  14790. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  14791. // shift the depth of the projected points so the line
  14792. // segments overlap neatly
  14793. const clipPose = vec3().toVar();
  14794. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  14795. clip.z.assign( clipPose.z.mul( clip.w ) );
  14796. } else {
  14797. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  14798. // undo aspect ratio adjustment
  14799. dir.x.assign( dir.x.div( aspect ) );
  14800. offset.x.assign( offset.x.div( aspect ) );
  14801. // sign flip
  14802. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  14803. // endcaps
  14804. If( positionGeometry.y.lessThan( 0.0 ), () => {
  14805. offset.assign( offset.sub( dir ) );
  14806. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  14807. offset.assign( offset.add( dir ) );
  14808. } );
  14809. // adjust for linewidth
  14810. offset.assign( offset.mul( materialLineWidth ) );
  14811. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  14812. offset.assign( offset.div( viewport.w ) );
  14813. // select end
  14814. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  14815. // back to clip space
  14816. offset.assign( offset.mul( clip.w ) );
  14817. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  14818. }
  14819. return clip;
  14820. } )();
  14821. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  14822. const p13 = p1.sub( p3 );
  14823. const p43 = p4.sub( p3 );
  14824. const p21 = p2.sub( p1 );
  14825. const d1343 = p13.dot( p43 );
  14826. const d4321 = p43.dot( p21 );
  14827. const d1321 = p13.dot( p21 );
  14828. const d4343 = p43.dot( p43 );
  14829. const d2121 = p21.dot( p21 );
  14830. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  14831. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  14832. const mua = numer.div( denom ).clamp();
  14833. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  14834. return vec2( mua, mub );
  14835. } );
  14836. this.colorNode = Fn( () => {
  14837. const vUv = uv$1();
  14838. if ( useDash ) {
  14839. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14840. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14841. dashSize.assign( dashSizeNode );
  14842. gapSize.assign( gapSizeNode );
  14843. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  14844. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  14845. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  14846. }
  14847. const alpha = float( 1 ).toVar( 'alpha' );
  14848. if ( useWorldUnits ) {
  14849. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  14850. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  14851. // Find the closest points on the view ray and the line segment
  14852. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  14853. const lineDir = worldEnd.sub( worldStart );
  14854. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  14855. const p1 = worldStart.add( lineDir.mul( params.x ) );
  14856. const p2 = rayEnd.mul( params.y );
  14857. const delta = p1.sub( p2 );
  14858. const len = delta.length();
  14859. const norm = len.div( materialLineWidth );
  14860. if ( ! useDash ) {
  14861. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14862. const dnorm = norm.fwidth();
  14863. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  14864. } else {
  14865. norm.greaterThan( 0.5 ).discard();
  14866. }
  14867. }
  14868. } else {
  14869. // round endcaps
  14870. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14871. const a = vUv.x;
  14872. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14873. const len2 = a.mul( a ).add( b.mul( b ) );
  14874. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  14875. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14876. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  14877. } );
  14878. } else {
  14879. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14880. const a = vUv.x;
  14881. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14882. const len2 = a.mul( a ).add( b.mul( b ) );
  14883. len2.greaterThan( 1.0 ).discard();
  14884. } );
  14885. }
  14886. }
  14887. let lineColorNode;
  14888. if ( this.lineColorNode ) {
  14889. lineColorNode = this.lineColorNode;
  14890. } else {
  14891. if ( useColor ) {
  14892. const instanceColorStart = attribute( 'instanceColorStart' );
  14893. const instanceColorEnd = attribute( 'instanceColorEnd' );
  14894. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  14895. lineColorNode = instanceColor.mul( materialColor );
  14896. } else {
  14897. lineColorNode = materialColor;
  14898. }
  14899. }
  14900. return vec4( lineColorNode, alpha );
  14901. } )();
  14902. if ( this.transparent ) {
  14903. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14904. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  14905. }
  14906. super.setup( builder );
  14907. }
  14908. /**
  14909. * Whether the lines should sized in world units or not.
  14910. * When set to `false` the unit is pixel.
  14911. *
  14912. * @type {boolean}
  14913. * @default false
  14914. */
  14915. get worldUnits() {
  14916. return this._useWorldUnits;
  14917. }
  14918. set worldUnits( value ) {
  14919. if ( this._useWorldUnits !== value ) {
  14920. this._useWorldUnits = value;
  14921. this.needsUpdate = true;
  14922. }
  14923. }
  14924. /**
  14925. * Whether the lines should be dashed or not.
  14926. *
  14927. * @type {boolean}
  14928. * @default false
  14929. */
  14930. get dashed() {
  14931. return this._useDash;
  14932. }
  14933. set dashed( value ) {
  14934. if ( this._useDash !== value ) {
  14935. this._useDash = value;
  14936. this.needsUpdate = true;
  14937. }
  14938. }
  14939. /**
  14940. * Whether alpha to coverage should be used or not.
  14941. *
  14942. * @type {boolean}
  14943. * @default true
  14944. */
  14945. get alphaToCoverage() {
  14946. return this._useAlphaToCoverage;
  14947. }
  14948. set alphaToCoverage( value ) {
  14949. if ( this._useAlphaToCoverage !== value ) {
  14950. this._useAlphaToCoverage = value;
  14951. this.needsUpdate = true;
  14952. }
  14953. }
  14954. }
  14955. /**
  14956. * Packs a direction vector into a color value.
  14957. *
  14958. * @tsl
  14959. * @function
  14960. * @param {Node<vec3>} node - The direction to pack.
  14961. * @return {Node<vec3>} The color.
  14962. */
  14963. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  14964. /**
  14965. * Unpacks a color value into a direction vector.
  14966. *
  14967. * @tsl
  14968. * @function
  14969. * @param {Node<vec3>} node - The color to unpack.
  14970. * @return {Node<vec3>} The direction.
  14971. */
  14972. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  14973. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  14974. /**
  14975. * Node material version of {@link MeshNormalMaterial}.
  14976. *
  14977. * @augments NodeMaterial
  14978. */
  14979. class MeshNormalNodeMaterial extends NodeMaterial {
  14980. static get type() {
  14981. return 'MeshNormalNodeMaterial';
  14982. }
  14983. /**
  14984. * Constructs a new mesh normal node material.
  14985. *
  14986. * @param {Object} [parameters] - The configuration parameter.
  14987. */
  14988. constructor( parameters ) {
  14989. super();
  14990. /**
  14991. * This flag can be used for type testing.
  14992. *
  14993. * @type {boolean}
  14994. * @readonly
  14995. * @default true
  14996. */
  14997. this.isMeshNormalNodeMaterial = true;
  14998. this.setDefaultValues( _defaultValues$a );
  14999. this.setValues( parameters );
  15000. }
  15001. /**
  15002. * Overwrites the default implementation by computing the diffuse color
  15003. * based on the normal data.
  15004. */
  15005. setupDiffuseColor() {
  15006. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  15007. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  15008. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  15009. }
  15010. }
  15011. /**
  15012. * TSL function for creating an equirect uv node.
  15013. *
  15014. * Can be used to compute texture coordinates for projecting an
  15015. * equirectangular texture onto a mesh for using it as the scene's
  15016. * background.
  15017. *
  15018. * ```js
  15019. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  15020. * ```
  15021. *
  15022. * @tsl
  15023. * @function
  15024. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15025. * @returns {Node<vec2>}
  15026. */
  15027. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15028. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15029. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15030. return vec2( u, v );
  15031. } );
  15032. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15033. /**
  15034. * This class represents a cube render target. It is a special version
  15035. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15036. *
  15037. * @augments WebGLCubeRenderTarget
  15038. */
  15039. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15040. /**
  15041. * Constructs a new cube render target.
  15042. *
  15043. * @param {number} [size=1] - The size of the render target.
  15044. * @param {RenderTarget~Options} [options] - The configuration object.
  15045. */
  15046. constructor( size = 1, options = {} ) {
  15047. super( size, options );
  15048. /**
  15049. * This flag can be used for type testing.
  15050. *
  15051. * @type {boolean}
  15052. * @readonly
  15053. * @default true
  15054. */
  15055. this.isCubeRenderTarget = true;
  15056. }
  15057. /**
  15058. * Converts the given equirectangular texture to a cube map.
  15059. *
  15060. * @param {Renderer} renderer - The renderer.
  15061. * @param {Texture} texture - The equirectangular texture.
  15062. * @return {CubeRenderTarget} A reference to this cube render target.
  15063. */
  15064. fromEquirectangularTexture( renderer, texture$1 ) {
  15065. const currentMinFilter = texture$1.minFilter;
  15066. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15067. texture$1.generateMipmaps = true;
  15068. this.texture.type = texture$1.type;
  15069. this.texture.colorSpace = texture$1.colorSpace;
  15070. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15071. this.texture.minFilter = texture$1.minFilter;
  15072. this.texture.magFilter = texture$1.magFilter;
  15073. const geometry = new BoxGeometry( 5, 5, 5 );
  15074. const uvNode = equirectUV( positionWorldDirection );
  15075. const material = new NodeMaterial();
  15076. material.colorNode = texture( texture$1, uvNode, 0 );
  15077. material.side = BackSide;
  15078. material.blending = NoBlending;
  15079. const mesh = new Mesh( geometry, material );
  15080. const scene = new Scene();
  15081. scene.add( mesh );
  15082. // Avoid blurred poles
  15083. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15084. const camera = new CubeCamera( 1, 10, this );
  15085. const currentMRT = renderer.getMRT();
  15086. renderer.setMRT( null );
  15087. camera.update( renderer, scene );
  15088. renderer.setMRT( currentMRT );
  15089. texture$1.minFilter = currentMinFilter;
  15090. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15091. mesh.geometry.dispose();
  15092. mesh.material.dispose();
  15093. return this;
  15094. }
  15095. }
  15096. const _cache$1 = new WeakMap();
  15097. /**
  15098. * This node can be used to automatically convert environment maps in the
  15099. * equirectangular format into the cube map format.
  15100. *
  15101. * @augments TempNode
  15102. */
  15103. class CubeMapNode extends TempNode {
  15104. static get type() {
  15105. return 'CubeMapNode';
  15106. }
  15107. /**
  15108. * Constructs a new cube map node.
  15109. *
  15110. * @param {Node} envNode - The node representing the environment map.
  15111. */
  15112. constructor( envNode ) {
  15113. super( 'vec3' );
  15114. /**
  15115. * The node representing the environment map.
  15116. *
  15117. * @type {Node}
  15118. */
  15119. this.envNode = envNode;
  15120. /**
  15121. * A reference to the internal cube texture.
  15122. *
  15123. * @private
  15124. * @type {?CubeTexture}
  15125. * @default null
  15126. */
  15127. this._cubeTexture = null;
  15128. /**
  15129. * A reference to the internal cube texture node.
  15130. *
  15131. * @private
  15132. * @type {CubeTextureNode}
  15133. */
  15134. this._cubeTextureNode = cubeTexture( null );
  15135. const defaultTexture = new CubeTexture();
  15136. defaultTexture.isRenderTargetTexture = true;
  15137. /**
  15138. * A default cube texture that acts as a placeholder.
  15139. * It is used when the conversion from equirectangular to cube
  15140. * map has not finished yet for a given texture.
  15141. *
  15142. * @private
  15143. * @type {CubeTexture}
  15144. */
  15145. this._defaultTexture = defaultTexture;
  15146. /**
  15147. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15148. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15149. *
  15150. * @type {string}
  15151. * @default 'render'
  15152. */
  15153. this.updateBeforeType = NodeUpdateType.RENDER;
  15154. }
  15155. updateBefore( frame ) {
  15156. const { renderer, material } = frame;
  15157. const envNode = this.envNode;
  15158. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15159. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15160. if ( texture && texture.isTexture ) {
  15161. const mapping = texture.mapping;
  15162. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15163. // check for converted cubemap map
  15164. if ( _cache$1.has( texture ) ) {
  15165. const cubeMap = _cache$1.get( texture );
  15166. mapTextureMapping( cubeMap, texture.mapping );
  15167. this._cubeTexture = cubeMap;
  15168. } else {
  15169. // create cube map from equirectangular map
  15170. const image = texture.image;
  15171. if ( isEquirectangularMapReady$1( image ) ) {
  15172. const renderTarget = new CubeRenderTarget( image.height );
  15173. renderTarget.fromEquirectangularTexture( renderer, texture );
  15174. mapTextureMapping( renderTarget.texture, texture.mapping );
  15175. this._cubeTexture = renderTarget.texture;
  15176. _cache$1.set( texture, renderTarget.texture );
  15177. texture.addEventListener( 'dispose', onTextureDispose );
  15178. } else {
  15179. // default cube texture as fallback when equirectangular texture is not yet loaded
  15180. this._cubeTexture = this._defaultTexture;
  15181. }
  15182. }
  15183. //
  15184. this._cubeTextureNode.value = this._cubeTexture;
  15185. } else {
  15186. // envNode already refers to a cube map
  15187. this._cubeTextureNode = this.envNode;
  15188. }
  15189. }
  15190. }
  15191. }
  15192. setup( builder ) {
  15193. this.updateBefore( builder );
  15194. return this._cubeTextureNode;
  15195. }
  15196. }
  15197. /**
  15198. * Returns true if the given equirectangular image has been fully loaded
  15199. * and is ready for further processing.
  15200. *
  15201. * @private
  15202. * @param {Image} image - The equirectangular image to check.
  15203. * @return {boolean} Whether the image is ready or not.
  15204. */
  15205. function isEquirectangularMapReady$1( image ) {
  15206. if ( image === null || image === undefined ) return false;
  15207. return image.height > 0;
  15208. }
  15209. /**
  15210. * This function is executed when `dispose()` is called on the equirectangular
  15211. * texture. In this case, the generated cube map with its render target
  15212. * is deleted as well.
  15213. *
  15214. * @private
  15215. * @param {Object} event - The event object.
  15216. */
  15217. function onTextureDispose( event ) {
  15218. const texture = event.target;
  15219. texture.removeEventListener( 'dispose', onTextureDispose );
  15220. const renderTarget = _cache$1.get( texture );
  15221. if ( renderTarget !== undefined ) {
  15222. _cache$1.delete( texture );
  15223. renderTarget.dispose();
  15224. }
  15225. }
  15226. /**
  15227. * This function makes sure the generated cube map uses the correct
  15228. * texture mapping that corresponds to the equirectangular original.
  15229. *
  15230. * @private
  15231. * @param {Texture} texture - The cube texture.
  15232. * @param {number} mapping - The original texture mapping.
  15233. */
  15234. function mapTextureMapping( texture, mapping ) {
  15235. if ( mapping === EquirectangularReflectionMapping ) {
  15236. texture.mapping = CubeReflectionMapping;
  15237. } else if ( mapping === EquirectangularRefractionMapping ) {
  15238. texture.mapping = CubeRefractionMapping;
  15239. }
  15240. }
  15241. /**
  15242. * TSL function for creating a cube map node.
  15243. *
  15244. * @tsl
  15245. * @function
  15246. * @param {Node} envNode - The node representing the environment map.
  15247. * @returns {CubeMapNode}
  15248. */
  15249. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15250. /**
  15251. * Represents a basic model for Image-based lighting (IBL). The environment
  15252. * is defined via environment maps in the equirectangular or cube map format.
  15253. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15254. * or {@link MeshPhongNodeMaterial}.
  15255. *
  15256. * @augments LightingNode
  15257. */
  15258. class BasicEnvironmentNode extends LightingNode {
  15259. static get type() {
  15260. return 'BasicEnvironmentNode';
  15261. }
  15262. /**
  15263. * Constructs a new basic environment node.
  15264. *
  15265. * @param {Node} [envNode=null] - A node representing the environment.
  15266. */
  15267. constructor( envNode = null ) {
  15268. super();
  15269. /**
  15270. * A node representing the environment.
  15271. *
  15272. * @type {Node}
  15273. * @default null
  15274. */
  15275. this.envNode = envNode;
  15276. }
  15277. setup( builder ) {
  15278. // environment property is used in the finish() method of BasicLightingModel
  15279. builder.context.environment = cubeMapNode( this.envNode );
  15280. }
  15281. }
  15282. /**
  15283. * A specific version of {@link IrradianceNode} that is only relevant
  15284. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15285. * requires a special scaling factor for the light map.
  15286. *
  15287. * @augments LightingNode
  15288. */
  15289. class BasicLightMapNode extends LightingNode {
  15290. static get type() {
  15291. return 'BasicLightMapNode';
  15292. }
  15293. /**
  15294. * Constructs a new basic light map node.
  15295. *
  15296. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15297. */
  15298. constructor( lightMapNode = null ) {
  15299. super();
  15300. /**
  15301. * The light map node.
  15302. *
  15303. * @type {?Node<vec3>}
  15304. */
  15305. this.lightMapNode = lightMapNode;
  15306. }
  15307. setup( builder ) {
  15308. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15309. const RECIPROCAL_PI = float( 1 / Math.PI );
  15310. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15311. }
  15312. }
  15313. /**
  15314. * Abstract class for implementing lighting models. The module defines
  15315. * multiple methods that concrete lighting models can implement. These
  15316. * methods are executed at different points during the light evaluation
  15317. * process.
  15318. */
  15319. class LightingModel {
  15320. /**
  15321. * This method is intended for setting up lighting model and context data
  15322. * which are later used in the evaluation process.
  15323. *
  15324. * @abstract
  15325. * @param {NodeBuilder} builder - The current node builder.
  15326. */
  15327. start( builder ) {
  15328. // lights ( direct )
  15329. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15330. // indirect
  15331. this.indirect( builder );
  15332. }
  15333. /**
  15334. * This method is intended for executing final tasks like final updates
  15335. * to the outgoing light.
  15336. *
  15337. * @abstract
  15338. * @param {NodeBuilder} builder - The current node builder.
  15339. */
  15340. finish( /*builder*/ ) { }
  15341. /**
  15342. * This method is intended for implementing the direct light term and
  15343. * executed during the build process of directional, point and spot light nodes.
  15344. *
  15345. * @abstract
  15346. * @param {Object} lightData - The light data.
  15347. * @param {NodeBuilder} builder - The current node builder.
  15348. */
  15349. direct( /*lightData, builder*/ ) { }
  15350. /**
  15351. * This method is intended for implementing the direct light term for
  15352. * rect area light nodes.
  15353. *
  15354. * @abstract
  15355. * @param {Object} lightData - The light data.
  15356. * @param {NodeBuilder} builder - The current node builder.
  15357. */
  15358. directRectArea( /*lightData, builder*/ ) {}
  15359. /**
  15360. * This method is intended for implementing the indirect light term.
  15361. *
  15362. * @abstract
  15363. * @param {NodeBuilder} builder - The current node builder.
  15364. */
  15365. indirect( /*builder*/ ) { }
  15366. /**
  15367. * This method is intended for implementing the ambient occlusion term.
  15368. * Unlike other methods, this method must be called manually by the lighting
  15369. * model in its indirect term.
  15370. *
  15371. * @abstract
  15372. * @param {NodeBuilder} builder - The current node builder.
  15373. */
  15374. ambientOcclusion( /*input, stack, builder*/ ) { }
  15375. }
  15376. /**
  15377. * Represents the lighting model for unlit materials. The only light contribution
  15378. * is baked indirect lighting modulated with ambient occlusion and the material's
  15379. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15380. *
  15381. * @augments LightingModel
  15382. */
  15383. class BasicLightingModel extends LightingModel {
  15384. /**
  15385. * Constructs a new basic lighting model.
  15386. */
  15387. constructor() {
  15388. super();
  15389. }
  15390. /**
  15391. * Implements the baked indirect lighting with its modulation.
  15392. *
  15393. * @param {NodeBuilder} builder - The current node builder.
  15394. */
  15395. indirect( { context } ) {
  15396. const ambientOcclusion = context.ambientOcclusion;
  15397. const reflectedLight = context.reflectedLight;
  15398. const irradianceLightMap = context.irradianceLightMap;
  15399. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15400. // accumulation (baked indirect lighting only)
  15401. if ( irradianceLightMap ) {
  15402. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15403. } else {
  15404. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15405. }
  15406. // modulation
  15407. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15408. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15409. }
  15410. /**
  15411. * Implements the environment mapping.
  15412. *
  15413. * @param {NodeBuilder} builder - The current node builder.
  15414. */
  15415. finish( builder ) {
  15416. const { material, context } = builder;
  15417. const outgoingLight = context.outgoingLight;
  15418. const envNode = builder.context.environment;
  15419. if ( envNode ) {
  15420. switch ( material.combine ) {
  15421. case MultiplyOperation:
  15422. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15423. break;
  15424. case MixOperation:
  15425. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15426. break;
  15427. case AddOperation:
  15428. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15429. break;
  15430. default:
  15431. warn( 'BasicLightingModel: Unsupported .combine value:', material.combine );
  15432. break;
  15433. }
  15434. }
  15435. }
  15436. }
  15437. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15438. /**
  15439. * Node material version of {@link MeshBasicMaterial}.
  15440. *
  15441. * @augments NodeMaterial
  15442. */
  15443. class MeshBasicNodeMaterial extends NodeMaterial {
  15444. static get type() {
  15445. return 'MeshBasicNodeMaterial';
  15446. }
  15447. /**
  15448. * Constructs a new mesh basic node material.
  15449. *
  15450. * @param {Object} [parameters] - The configuration parameter.
  15451. */
  15452. constructor( parameters ) {
  15453. super();
  15454. /**
  15455. * This flag can be used for type testing.
  15456. *
  15457. * @type {boolean}
  15458. * @readonly
  15459. * @default true
  15460. */
  15461. this.isMeshBasicNodeMaterial = true;
  15462. /**
  15463. * Although the basic material is by definition unlit, we set
  15464. * this property to `true` since we use a lighting model to compute
  15465. * the outgoing light of the fragment shader.
  15466. *
  15467. * @type {boolean}
  15468. * @default true
  15469. */
  15470. this.lights = true;
  15471. this.setDefaultValues( _defaultValues$9 );
  15472. this.setValues( parameters );
  15473. }
  15474. /**
  15475. * Basic materials are not affected by normal and bump maps so we
  15476. * return by default {@link normalViewGeometry}.
  15477. *
  15478. * @return {Node<vec3>} The normal node.
  15479. */
  15480. setupNormal() {
  15481. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15482. }
  15483. /**
  15484. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15485. * to implement the default environment mapping.
  15486. *
  15487. * @param {NodeBuilder} builder - The current node builder.
  15488. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15489. */
  15490. setupEnvironment( builder ) {
  15491. const envNode = super.setupEnvironment( builder );
  15492. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15493. }
  15494. /**
  15495. * This method must be overwritten since light maps are evaluated
  15496. * with a special scaling factor for basic materials.
  15497. *
  15498. * @param {NodeBuilder} builder - The current node builder.
  15499. * @return {?BasicLightMapNode<vec3>} The light map node.
  15500. */
  15501. setupLightMap( builder ) {
  15502. let node = null;
  15503. if ( builder.material.lightMap ) {
  15504. node = new BasicLightMapNode( materialLightMap );
  15505. }
  15506. return node;
  15507. }
  15508. /**
  15509. * The material overwrites this method because `lights` is set to `true` but
  15510. * we still want to return the diffuse color as the outgoing light.
  15511. *
  15512. * @return {Node<vec3>} The outgoing light node.
  15513. */
  15514. setupOutgoingLight() {
  15515. return diffuseColor.rgb;
  15516. }
  15517. /**
  15518. * Setups the lighting model.
  15519. *
  15520. * @return {BasicLightingModel} The lighting model.
  15521. */
  15522. setupLightingModel() {
  15523. return new BasicLightingModel();
  15524. }
  15525. }
  15526. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15527. // Original approximation by Christophe Schlick '94
  15528. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15529. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15530. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15531. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15532. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15533. } ); // validated
  15534. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15535. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15536. } ); // validated
  15537. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15538. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15539. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15540. } );
  15541. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15542. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15543. const dotNH = normalView.dot( halfDir ).clamp();
  15544. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15545. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15546. const G = G_BlinnPhong_Implicit();
  15547. const D = D_BlinnPhong( { dotNH } );
  15548. return F.mul( G ).mul( D );
  15549. } );
  15550. /**
  15551. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15552. *
  15553. * @augments BasicLightingModel
  15554. */
  15555. class PhongLightingModel extends BasicLightingModel {
  15556. /**
  15557. * Constructs a new phong lighting model.
  15558. *
  15559. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15560. */
  15561. constructor( specular = true ) {
  15562. super();
  15563. /**
  15564. * Whether specular is supported or not. Set this to `false` if you are
  15565. * looking for a Lambert-like material meaning a material for non-shiny
  15566. * surfaces, without specular highlights.
  15567. *
  15568. * @type {boolean}
  15569. * @default true
  15570. */
  15571. this.specular = specular;
  15572. }
  15573. /**
  15574. * Implements the direct lighting. The specular portion is optional an can be controlled
  15575. * with the {@link PhongLightingModel#specular} flag.
  15576. *
  15577. * @param {Object} lightData - The light data.
  15578. */
  15579. direct( { lightDirection, lightColor, reflectedLight } ) {
  15580. const dotNL = normalView.dot( lightDirection ).clamp();
  15581. const irradiance = dotNL.mul( lightColor );
  15582. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15583. if ( this.specular === true ) {
  15584. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15585. }
  15586. }
  15587. /**
  15588. * Implements the indirect lighting.
  15589. *
  15590. * @param {NodeBuilder} builder - The current node builder.
  15591. */
  15592. indirect( builder ) {
  15593. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15594. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15595. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15596. }
  15597. }
  15598. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15599. /**
  15600. * Node material version of {@link MeshLambertMaterial}.
  15601. *
  15602. * @augments NodeMaterial
  15603. */
  15604. class MeshLambertNodeMaterial extends NodeMaterial {
  15605. static get type() {
  15606. return 'MeshLambertNodeMaterial';
  15607. }
  15608. /**
  15609. * Constructs a new mesh lambert node material.
  15610. *
  15611. * @param {Object} [parameters] - The configuration parameter.
  15612. */
  15613. constructor( parameters ) {
  15614. super();
  15615. /**
  15616. * This flag can be used for type testing.
  15617. *
  15618. * @type {boolean}
  15619. * @readonly
  15620. * @default true
  15621. */
  15622. this.isMeshLambertNodeMaterial = true;
  15623. /**
  15624. * Set to `true` because lambert materials react on lights.
  15625. *
  15626. * @type {boolean}
  15627. * @default true
  15628. */
  15629. this.lights = true;
  15630. this.setDefaultValues( _defaultValues$8 );
  15631. this.setValues( parameters );
  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. * Setups the lighting model.
  15646. *
  15647. * @return {PhongLightingModel} The lighting model.
  15648. */
  15649. setupLightingModel( /*builder*/ ) {
  15650. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15651. }
  15652. }
  15653. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15654. /**
  15655. * Node material version of {@link MeshPhongMaterial}.
  15656. *
  15657. * @augments NodeMaterial
  15658. */
  15659. class MeshPhongNodeMaterial extends NodeMaterial {
  15660. static get type() {
  15661. return 'MeshPhongNodeMaterial';
  15662. }
  15663. /**
  15664. * Constructs a new mesh lambert node material.
  15665. *
  15666. * @param {Object} [parameters] - The configuration parameter.
  15667. */
  15668. constructor( parameters ) {
  15669. super();
  15670. /**
  15671. * This flag can be used for type testing.
  15672. *
  15673. * @type {boolean}
  15674. * @readonly
  15675. * @default true
  15676. */
  15677. this.isMeshPhongNodeMaterial = true;
  15678. /**
  15679. * Set to `true` because phong materials react on lights.
  15680. *
  15681. * @type {boolean}
  15682. * @default true
  15683. */
  15684. this.lights = true;
  15685. /**
  15686. * The shininess of phong materials is by default inferred from the `shininess`
  15687. * property. This node property allows to overwrite the default
  15688. * and define the shininess with a node instead.
  15689. *
  15690. * If you don't want to overwrite the shininess but modify the existing
  15691. * value instead, use {@link materialShininess}.
  15692. *
  15693. * @type {?Node<float>}
  15694. * @default null
  15695. */
  15696. this.shininessNode = null;
  15697. /**
  15698. * The specular color of phong materials is by default inferred from the
  15699. * `specular` property. This node property allows to overwrite the default
  15700. * and define the specular color with a node instead.
  15701. *
  15702. * If you don't want to overwrite the specular color but modify the existing
  15703. * value instead, use {@link materialSpecular}.
  15704. *
  15705. * @type {?Node<vec3>}
  15706. * @default null
  15707. */
  15708. this.specularNode = null;
  15709. this.setDefaultValues( _defaultValues$7 );
  15710. this.setValues( parameters );
  15711. }
  15712. /**
  15713. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15714. * to implement the default environment mapping.
  15715. *
  15716. * @param {NodeBuilder} builder - The current node builder.
  15717. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15718. */
  15719. setupEnvironment( builder ) {
  15720. const envNode = super.setupEnvironment( builder );
  15721. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15722. }
  15723. /**
  15724. * Setups the lighting model.
  15725. *
  15726. * @return {PhongLightingModel} The lighting model.
  15727. */
  15728. setupLightingModel( /*builder*/ ) {
  15729. return new PhongLightingModel();
  15730. }
  15731. /**
  15732. * Setups the phong specific node variables.
  15733. *
  15734. * @param {NodeBuilder} builder - The current node builder.
  15735. */
  15736. setupVariants( /*builder*/ ) {
  15737. // SHININESS
  15738. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15739. shininess.assign( shininessNode );
  15740. // SPECULAR COLOR
  15741. const specularNode = this.specularNode || materialSpecular;
  15742. specularColor.assign( specularNode );
  15743. }
  15744. copy( source ) {
  15745. this.shininessNode = source.shininessNode;
  15746. this.specularNode = source.specularNode;
  15747. return super.copy( source );
  15748. }
  15749. }
  15750. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  15751. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  15752. return float( 0 );
  15753. }
  15754. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  15755. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  15756. return geometryRoughness;
  15757. } );
  15758. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  15759. const { roughness } = inputs;
  15760. const geometryRoughness = getGeometryRoughness();
  15761. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  15762. roughnessFactor = roughnessFactor.add( geometryRoughness );
  15763. roughnessFactor = roughnessFactor.min( 1.0 );
  15764. return roughnessFactor;
  15765. } );
  15766. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  15767. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15768. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  15769. const a2 = alpha.pow2();
  15770. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  15771. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  15772. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  15773. } ).setLayout( {
  15774. name: 'V_GGX_SmithCorrelated',
  15775. type: 'float',
  15776. inputs: [
  15777. { name: 'alpha', type: 'float' },
  15778. { name: 'dotNL', type: 'float' },
  15779. { name: 'dotNV', type: 'float' }
  15780. ]
  15781. } ); // validated
  15782. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15783. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  15784. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  15785. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  15786. const v = div( 0.5, gv.add( gl ) );
  15787. return v.saturate();
  15788. } ).setLayout( {
  15789. name: 'V_GGX_SmithCorrelated_Anisotropic',
  15790. type: 'float',
  15791. inputs: [
  15792. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15793. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15794. { name: 'dotTV', type: 'float', qualifier: 'in' },
  15795. { name: 'dotBV', type: 'float', qualifier: 'in' },
  15796. { name: 'dotTL', type: 'float', qualifier: 'in' },
  15797. { name: 'dotBL', type: 'float', qualifier: 'in' },
  15798. { name: 'dotNV', type: 'float', qualifier: 'in' },
  15799. { name: 'dotNL', type: 'float', qualifier: 'in' }
  15800. ]
  15801. } );
  15802. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  15803. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  15804. // alpha is "roughness squared" in Disney’s reparameterization
  15805. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  15806. const a2 = alpha.pow2();
  15807. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  15808. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  15809. } ).setLayout( {
  15810. name: 'D_GGX',
  15811. type: 'float',
  15812. inputs: [
  15813. { name: 'alpha', type: 'float' },
  15814. { name: 'dotNH', type: 'float' }
  15815. ]
  15816. } ); // validated
  15817. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  15818. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15819. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  15820. const a2 = alphaT.mul( alphaB );
  15821. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  15822. const v2 = v.dot( v );
  15823. const w2 = a2.div( v2 );
  15824. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  15825. } ).setLayout( {
  15826. name: 'D_GGX_Anisotropic',
  15827. type: 'float',
  15828. inputs: [
  15829. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15830. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15831. { name: 'dotNH', type: 'float', qualifier: 'in' },
  15832. { name: 'dotTH', type: 'float', qualifier: 'in' },
  15833. { name: 'dotBH', type: 'float', qualifier: 'in' }
  15834. ]
  15835. } );
  15836. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  15837. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  15838. const alpha = roughness.pow2(); // UE4's roughness
  15839. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15840. const dotNL = normalView$1.dot( lightDirection ).clamp();
  15841. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15842. const dotNH = normalView$1.dot( halfDir ).clamp();
  15843. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15844. let F = F_Schlick( { f0, f90, dotVH } );
  15845. let V, D;
  15846. if ( defined( USE_IRIDESCENCE ) ) {
  15847. F = iridescence.mix( F, f );
  15848. }
  15849. if ( defined( USE_ANISOTROPY ) ) {
  15850. const dotTL = anisotropyT.dot( lightDirection );
  15851. const dotTV = anisotropyT.dot( positionViewDirection );
  15852. const dotTH = anisotropyT.dot( halfDir );
  15853. const dotBL = anisotropyB.dot( lightDirection );
  15854. const dotBV = anisotropyB.dot( positionViewDirection );
  15855. const dotBH = anisotropyB.dot( halfDir );
  15856. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  15857. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  15858. } else {
  15859. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  15860. D = D_GGX( { alpha, dotNH } );
  15861. }
  15862. return F.mul( V ).mul( D );
  15863. } ); // validated
  15864. // Analytical approximation of the DFG LUT, one half of the
  15865. // split-sum approximation used in indirect specular lighting.
  15866. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  15867. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  15868. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  15869. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  15870. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  15871. const r = roughness.mul( c0 ).add( c1 );
  15872. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  15873. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  15874. return fab;
  15875. } ).setLayout( {
  15876. name: 'DFGApprox',
  15877. type: 'vec2',
  15878. inputs: [
  15879. { name: 'roughness', type: 'float' },
  15880. { name: 'dotNV', type: 'vec3' }
  15881. ]
  15882. } );
  15883. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  15884. const { dotNV, specularColor, specularF90, roughness } = inputs;
  15885. const fab = DFGApprox( { dotNV, roughness } );
  15886. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15887. } );
  15888. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  15889. const x = dotVH.oneMinus().saturate();
  15890. const x2 = x.mul( x );
  15891. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  15892. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  15893. } ).setLayout( {
  15894. name: 'Schlick_to_F0',
  15895. type: 'vec3',
  15896. inputs: [
  15897. { name: 'f', type: 'vec3' },
  15898. { name: 'f90', type: 'float' },
  15899. { name: 'dotVH', type: 'float' }
  15900. ]
  15901. } );
  15902. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15903. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  15904. const alpha = roughness.pow2();
  15905. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  15906. const invAlpha = float( 1.0 ).div( alpha );
  15907. const cos2h = dotNH.pow2();
  15908. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  15909. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  15910. } ).setLayout( {
  15911. name: 'D_Charlie',
  15912. type: 'float',
  15913. inputs: [
  15914. { name: 'roughness', type: 'float' },
  15915. { name: 'dotNH', type: 'float' }
  15916. ]
  15917. } );
  15918. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15919. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  15920. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  15921. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  15922. } ).setLayout( {
  15923. name: 'V_Neubelt',
  15924. type: 'float',
  15925. inputs: [
  15926. { name: 'dotNV', type: 'float' },
  15927. { name: 'dotNL', type: 'float' }
  15928. ]
  15929. } );
  15930. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15931. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15932. const dotNL = normalView.dot( lightDirection ).clamp();
  15933. const dotNV = normalView.dot( positionViewDirection ).clamp();
  15934. const dotNH = normalView.dot( halfDir ).clamp();
  15935. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  15936. const V = V_Neubelt( { dotNV, dotNL } );
  15937. return sheen.mul( D ).mul( V );
  15938. } );
  15939. // Rect Area Light
  15940. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  15941. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  15942. // code: https://github.com/selfshadow/ltc_code/
  15943. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  15944. const LUT_SIZE = 64.0;
  15945. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  15946. const LUT_BIAS = 0.5 / LUT_SIZE;
  15947. const dotNV = N.dot( V ).saturate();
  15948. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  15949. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  15950. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  15951. return uv;
  15952. } ).setLayout( {
  15953. name: 'LTC_Uv',
  15954. type: 'vec2',
  15955. inputs: [
  15956. { name: 'N', type: 'vec3' },
  15957. { name: 'V', type: 'vec3' },
  15958. { name: 'roughness', type: 'float' }
  15959. ]
  15960. } );
  15961. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  15962. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  15963. // An approximation of the form factor of a horizon-clipped rectangle.
  15964. const l = f.length();
  15965. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  15966. } ).setLayout( {
  15967. name: 'LTC_ClippedSphereFormFactor',
  15968. type: 'float',
  15969. inputs: [
  15970. { name: 'f', type: 'vec3' }
  15971. ]
  15972. } );
  15973. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  15974. const x = v1.dot( v2 );
  15975. const y = x.abs().toVar();
  15976. // rational polynomial approximation to theta / sin( theta ) / 2PI
  15977. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  15978. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  15979. const v = a.div( b );
  15980. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  15981. return v1.cross( v2 ).mul( theta_sintheta );
  15982. } ).setLayout( {
  15983. name: 'LTC_EdgeVectorFormFactor',
  15984. type: 'vec3',
  15985. inputs: [
  15986. { name: 'v1', type: 'vec3' },
  15987. { name: 'v2', type: 'vec3' }
  15988. ]
  15989. } );
  15990. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  15991. // bail if point is on back side of plane of light
  15992. // assumes ccw winding order of light vertices
  15993. const v1 = p1.sub( p0 ).toVar();
  15994. const v2 = p3.sub( p0 ).toVar();
  15995. const lightNormal = v1.cross( v2 );
  15996. const result = vec3().toVar();
  15997. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15998. // construct orthonormal basis around N
  15999. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  16000. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  16001. // compute transform
  16002. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  16003. // transform rect
  16004. // & project rect onto sphere
  16005. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  16006. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  16007. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  16008. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  16009. // calculate vector form factor
  16010. const vectorFormFactor = vec3( 0 ).toVar();
  16011. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16012. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16013. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16014. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16015. // adjust for horizon clipping
  16016. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  16017. } );
  16018. return result;
  16019. } ).setLayout( {
  16020. name: 'LTC_Evaluate',
  16021. type: 'vec3',
  16022. inputs: [
  16023. { name: 'N', type: 'vec3' },
  16024. { name: 'V', type: 'vec3' },
  16025. { name: 'P', type: 'vec3' },
  16026. { name: 'mInv', type: 'mat3' },
  16027. { name: 'p0', type: 'vec3' },
  16028. { name: 'p1', type: 'vec3' },
  16029. { name: 'p2', type: 'vec3' },
  16030. { name: 'p3', type: 'vec3' }
  16031. ]
  16032. } );
  16033. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16034. // bail if point is on back side of plane of light
  16035. // assumes ccw winding order of light vertices
  16036. const v1 = p1.sub( p0 ).toVar();
  16037. const v2 = p3.sub( p0 ).toVar();
  16038. const lightNormal = v1.cross( v2 );
  16039. const result = vec3().toVar();
  16040. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16041. // transform rect
  16042. // & project rect onto sphere
  16043. const coords0 = p0.sub( P ).normalize().toVar();
  16044. const coords1 = p1.sub( P ).normalize().toVar();
  16045. const coords2 = p2.sub( P ).normalize().toVar();
  16046. const coords3 = p3.sub( P ).normalize().toVar();
  16047. // calculate vector form factor
  16048. const vectorFormFactor = vec3( 0 ).toVar();
  16049. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16050. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16051. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16052. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16053. // adjust for horizon clipping
  16054. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16055. } );
  16056. return result;
  16057. } ).setLayout( {
  16058. name: 'LTC_Evaluate',
  16059. type: 'vec3',
  16060. inputs: [
  16061. { name: 'P', type: 'vec3' },
  16062. { name: 'p0', type: 'vec3' },
  16063. { name: 'p1', type: 'vec3' },
  16064. { name: 'p2', type: 'vec3' },
  16065. { name: 'p3', type: 'vec3' }
  16066. ]
  16067. } );
  16068. // Mipped Bicubic Texture Filtering by N8
  16069. // https://www.shadertoy.com/view/Dl2SDW
  16070. const bC = 1.0 / 6.0;
  16071. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16072. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16073. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16074. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16075. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16076. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16077. // h0 and h1 are the two offset functions
  16078. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16079. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16080. const bicubic = ( textureNode, texelSize, lod ) => {
  16081. const uv = textureNode.uvNode;
  16082. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16083. const iuv = floor( uvScaled );
  16084. const fuv = fract( uvScaled );
  16085. const g0x = g0( fuv.x );
  16086. const g1x = g1( fuv.x );
  16087. const h0x = h0( fuv.x );
  16088. const h1x = h1( fuv.x );
  16089. const h0y = h0( fuv.y );
  16090. const h1y = h1( fuv.y );
  16091. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16092. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16093. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16094. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16095. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16096. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16097. return a.add( b );
  16098. };
  16099. /**
  16100. * Applies mipped bicubic texture filtering to the given texture node.
  16101. *
  16102. * @tsl
  16103. * @function
  16104. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16105. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16106. * @return {Node} The filtered texture sample.
  16107. */
  16108. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16109. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16110. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16111. const fLodSizeInv = div( 1.0, fLodSize );
  16112. const cLodSizeInv = div( 1.0, cLodSize );
  16113. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16114. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16115. return fract( lodNode ).mix( fSample, cSample );
  16116. } );
  16117. /**
  16118. * Applies mipped bicubic texture filtering to the given texture node.
  16119. *
  16120. * @tsl
  16121. * @function
  16122. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16123. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16124. * @return {Node} The filtered texture sample.
  16125. */
  16126. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16127. const lod = strength.mul( maxMipLevel( textureNode ) );
  16128. return textureBicubicLevel( textureNode, lod );
  16129. } );
  16130. //
  16131. // Transmission
  16132. //
  16133. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16134. // Direction of refracted light.
  16135. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16136. // Compute rotation-independent scaling of the model matrix.
  16137. const modelScale = vec3(
  16138. length( modelMatrix[ 0 ].xyz ),
  16139. length( modelMatrix[ 1 ].xyz ),
  16140. length( modelMatrix[ 2 ].xyz )
  16141. );
  16142. // The thickness is specified in local space.
  16143. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16144. } ).setLayout( {
  16145. name: 'getVolumeTransmissionRay',
  16146. type: 'vec3',
  16147. inputs: [
  16148. { name: 'n', type: 'vec3' },
  16149. { name: 'v', type: 'vec3' },
  16150. { name: 'thickness', type: 'float' },
  16151. { name: 'ior', type: 'float' },
  16152. { name: 'modelMatrix', type: 'mat4' }
  16153. ]
  16154. } );
  16155. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16156. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16157. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16158. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16159. } ).setLayout( {
  16160. name: 'applyIorToRoughness',
  16161. type: 'float',
  16162. inputs: [
  16163. { name: 'roughness', type: 'float' },
  16164. { name: 'ior', type: 'float' }
  16165. ]
  16166. } );
  16167. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16168. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16169. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16170. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16171. const transmissionSample = vTexture.sample( fragCoord );
  16172. //const transmissionSample = viewportMipTexture( fragCoord );
  16173. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16174. return textureBicubicLevel( transmissionSample, lod );
  16175. } );
  16176. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16177. If( attenuationDistance.notEqual( 0 ), () => {
  16178. // Compute light attenuation using Beer's law.
  16179. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16180. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16181. return transmittance;
  16182. } );
  16183. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16184. return vec3( 1.0 );
  16185. } ).setLayout( {
  16186. name: 'volumeAttenuation',
  16187. type: 'vec3',
  16188. inputs: [
  16189. { name: 'transmissionDistance', type: 'float' },
  16190. { name: 'attenuationColor', type: 'vec3' },
  16191. { name: 'attenuationDistance', type: 'float' }
  16192. ]
  16193. } );
  16194. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16195. let transmittedLight, transmittance;
  16196. if ( dispersion ) {
  16197. transmittedLight = vec4().toVar();
  16198. transmittance = vec3().toVar();
  16199. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16200. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16201. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16202. const ior = iors.element( i );
  16203. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16204. const refractedRayExit = position.add( transmissionRay );
  16205. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16206. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16207. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16208. refractionCoords.addAssign( 1.0 );
  16209. refractionCoords.divAssign( 2.0 );
  16210. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16211. // Sample framebuffer to get pixel the refracted ray hits.
  16212. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16213. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16214. transmittedLight.a.addAssign( transmissionSample.a );
  16215. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16216. } );
  16217. transmittedLight.a.divAssign( 3.0 );
  16218. } else {
  16219. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16220. const refractedRayExit = position.add( transmissionRay );
  16221. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16222. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16223. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16224. refractionCoords.addAssign( 1.0 );
  16225. refractionCoords.divAssign( 2.0 );
  16226. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16227. // Sample framebuffer to get pixel the refracted ray hits.
  16228. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16229. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16230. }
  16231. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16232. const dotNV = n.dot( v ).clamp();
  16233. // Get the specular component.
  16234. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16235. dotNV,
  16236. specularColor,
  16237. specularF90,
  16238. roughness
  16239. } ) );
  16240. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16241. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16242. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16243. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16244. } );
  16245. //
  16246. // Iridescence
  16247. //
  16248. // XYZ to linear-sRGB color space
  16249. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16250. 3.2404542, -0.969266, 0.0556434,
  16251. -1.5371385, 1.8760108, -0.2040259,
  16252. -0.4985314, 0.0415560, 1.0572252
  16253. );
  16254. // Assume air interface for top
  16255. // Note: We don't handle the case fresnel0 == 1
  16256. const Fresnel0ToIor = ( fresnel0 ) => {
  16257. const sqrtF0 = fresnel0.sqrt();
  16258. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16259. };
  16260. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16261. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16262. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16263. };
  16264. // Fresnel equations for dielectric/dielectric interfaces.
  16265. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16266. // Evaluation XYZ sensitivity curves in Fourier space
  16267. const evalSensitivity = ( OPD, shift ) => {
  16268. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16269. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16270. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16271. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16272. 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() );
  16273. 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() );
  16274. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16275. const rgb = XYZ_TO_REC709.mul( xyz );
  16276. return rgb;
  16277. };
  16278. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16279. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16280. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16281. // Evaluate the cosTheta on the base layer (Snell law)
  16282. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16283. // Handle TIR:
  16284. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16285. If( cosTheta2Sq.lessThan( 0 ), () => {
  16286. return vec3( 1.0 );
  16287. } );
  16288. const cosTheta2 = cosTheta2Sq.sqrt();
  16289. // First interface
  16290. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16291. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16292. //const R21 = R12;
  16293. const T121 = R12.oneMinus();
  16294. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16295. const phi21 = float( Math.PI ).sub( phi12 );
  16296. // Second interface
  16297. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16298. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16299. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16300. const phi23 = vec3(
  16301. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16302. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16303. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16304. );
  16305. // Phase shift
  16306. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16307. const phi = vec3( phi21 ).add( phi23 );
  16308. // Compound terms
  16309. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16310. const r123 = R123.sqrt();
  16311. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16312. // Reflectance term for m = 0 (DC term amplitude)
  16313. const C0 = R12.add( Rs );
  16314. const I = C0.toVar();
  16315. // Reflectance term for m > 0 (pairs of diracs)
  16316. const Cm = Rs.sub( T121 ).toVar();
  16317. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16318. Cm.mulAssign( r123 );
  16319. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16320. I.addAssign( Cm.mul( Sm ) );
  16321. } );
  16322. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16323. return I.max( vec3( 0.0 ) );
  16324. } ).setLayout( {
  16325. name: 'evalIridescence',
  16326. type: 'vec3',
  16327. inputs: [
  16328. { name: 'outsideIOR', type: 'float' },
  16329. { name: 'eta2', type: 'float' },
  16330. { name: 'cosTheta1', type: 'float' },
  16331. { name: 'thinFilmThickness', type: 'float' },
  16332. { name: 'baseF0', type: 'vec3' }
  16333. ]
  16334. } );
  16335. //
  16336. // Sheen
  16337. //
  16338. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16339. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16340. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16341. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16342. const dotNV = normal.dot( viewDir ).saturate();
  16343. const r2 = roughness.pow2();
  16344. const a = select(
  16345. roughness.lessThan( 0.25 ),
  16346. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16347. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16348. );
  16349. const b = select(
  16350. roughness.lessThan( 0.25 ),
  16351. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16352. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16353. );
  16354. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16355. return DG.mul( 1.0 / Math.PI ).saturate();
  16356. } );
  16357. const clearcoatF0 = vec3( 0.04 );
  16358. const clearcoatF90 = float( 1 );
  16359. /**
  16360. * Represents the lighting model for a PBR material.
  16361. *
  16362. * @augments LightingModel
  16363. */
  16364. class PhysicalLightingModel extends LightingModel {
  16365. /**
  16366. * Constructs a new physical lighting model.
  16367. *
  16368. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16369. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16370. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16371. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16372. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16373. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16374. */
  16375. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16376. super();
  16377. /**
  16378. * Whether clearcoat is supported or not.
  16379. *
  16380. * @type {boolean}
  16381. * @default false
  16382. */
  16383. this.clearcoat = clearcoat;
  16384. /**
  16385. * Whether sheen is supported or not.
  16386. *
  16387. * @type {boolean}
  16388. * @default false
  16389. */
  16390. this.sheen = sheen;
  16391. /**
  16392. * Whether iridescence is supported or not.
  16393. *
  16394. * @type {boolean}
  16395. * @default false
  16396. */
  16397. this.iridescence = iridescence;
  16398. /**
  16399. * Whether anisotropy is supported or not.
  16400. *
  16401. * @type {boolean}
  16402. * @default false
  16403. */
  16404. this.anisotropy = anisotropy;
  16405. /**
  16406. * Whether transmission is supported or not.
  16407. *
  16408. * @type {boolean}
  16409. * @default false
  16410. */
  16411. this.transmission = transmission;
  16412. /**
  16413. * Whether dispersion is supported or not.
  16414. *
  16415. * @type {boolean}
  16416. * @default false
  16417. */
  16418. this.dispersion = dispersion;
  16419. /**
  16420. * The clear coat radiance.
  16421. *
  16422. * @type {?Node}
  16423. * @default null
  16424. */
  16425. this.clearcoatRadiance = null;
  16426. /**
  16427. * The clear coat specular direct.
  16428. *
  16429. * @type {?Node}
  16430. * @default null
  16431. */
  16432. this.clearcoatSpecularDirect = null;
  16433. /**
  16434. * The clear coat specular indirect.
  16435. *
  16436. * @type {?Node}
  16437. * @default null
  16438. */
  16439. this.clearcoatSpecularIndirect = null;
  16440. /**
  16441. * The sheen specular direct.
  16442. *
  16443. * @type {?Node}
  16444. * @default null
  16445. */
  16446. this.sheenSpecularDirect = null;
  16447. /**
  16448. * The sheen specular indirect.
  16449. *
  16450. * @type {?Node}
  16451. * @default null
  16452. */
  16453. this.sheenSpecularIndirect = null;
  16454. /**
  16455. * The iridescence Fresnel.
  16456. *
  16457. * @type {?Node}
  16458. * @default null
  16459. */
  16460. this.iridescenceFresnel = null;
  16461. /**
  16462. * The iridescence F0.
  16463. *
  16464. * @type {?Node}
  16465. * @default null
  16466. */
  16467. this.iridescenceF0 = null;
  16468. }
  16469. /**
  16470. * Depending on what features are requested, the method prepares certain node variables
  16471. * which are later used for lighting computations.
  16472. *
  16473. * @param {NodeBuilder} builder - The current node builder.
  16474. */
  16475. start( builder ) {
  16476. if ( this.clearcoat === true ) {
  16477. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16478. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16479. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16480. }
  16481. if ( this.sheen === true ) {
  16482. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16483. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16484. }
  16485. if ( this.iridescence === true ) {
  16486. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16487. this.iridescenceFresnel = evalIridescence( {
  16488. outsideIOR: float( 1.0 ),
  16489. eta2: iridescenceIOR,
  16490. cosTheta1: dotNVi,
  16491. thinFilmThickness: iridescenceThickness,
  16492. baseF0: specularColor
  16493. } );
  16494. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16495. }
  16496. if ( this.transmission === true ) {
  16497. const position = positionWorld;
  16498. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16499. const n = normalWorld;
  16500. const context = builder.context;
  16501. context.backdrop = getIBLVolumeRefraction(
  16502. n,
  16503. v,
  16504. roughness,
  16505. diffuseColor,
  16506. specularColor,
  16507. specularF90, // specularF90
  16508. position, // positionWorld
  16509. modelWorldMatrix, // modelMatrix
  16510. cameraViewMatrix, // viewMatrix
  16511. cameraProjectionMatrix, // projMatrix
  16512. ior,
  16513. thickness,
  16514. attenuationColor,
  16515. attenuationDistance,
  16516. this.dispersion ? dispersion : null
  16517. );
  16518. context.backdropAlpha = transmission;
  16519. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16520. }
  16521. super.start( builder );
  16522. }
  16523. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16524. // Approximates multi-scattering in order to preserve energy.
  16525. // http://www.jcgt.org/published/0008/01/03/
  16526. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16527. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16528. const fab = DFGApprox( { roughness, dotNV } );
  16529. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16530. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16531. const Ess = fab.x.add( fab.y );
  16532. const Ems = Ess.oneMinus();
  16533. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16534. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16535. singleScatter.addAssign( FssEss );
  16536. multiScatter.addAssign( Fms.mul( Ems ) );
  16537. }
  16538. /**
  16539. * Implements the direct light.
  16540. *
  16541. * @param {Object} lightData - The light data.
  16542. * @param {NodeBuilder} builder - The current node builder.
  16543. */
  16544. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16545. const dotNL = normalView.dot( lightDirection ).clamp();
  16546. const irradiance = dotNL.mul( lightColor );
  16547. if ( this.sheen === true ) {
  16548. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16549. }
  16550. if ( this.clearcoat === true ) {
  16551. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16552. const ccIrradiance = dotNLcc.mul( lightColor );
  16553. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16554. }
  16555. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16556. 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 } ) ) );
  16557. }
  16558. /**
  16559. * This method is intended for implementing the direct light term for
  16560. * rect area light nodes.
  16561. *
  16562. * @param {Object} input - The input data.
  16563. * @param {NodeBuilder} builder - The current node builder.
  16564. */
  16565. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16566. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16567. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16568. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16569. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16570. const N = normalView;
  16571. const V = positionViewDirection;
  16572. const P = positionView.toVar();
  16573. const uv = LTC_Uv( { N, V, roughness } );
  16574. const t1 = ltc_1.sample( uv ).toVar();
  16575. const t2 = ltc_2.sample( uv ).toVar();
  16576. const mInv = mat3(
  16577. vec3( t1.x, 0, t1.y ),
  16578. vec3( 0, 1, 0 ),
  16579. vec3( t1.z, 0, t1.w )
  16580. ).toVar();
  16581. // LTC Fresnel Approximation by Stephen Hill
  16582. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16583. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16584. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16585. 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 } ) ) );
  16586. }
  16587. /**
  16588. * Implements the indirect lighting.
  16589. *
  16590. * @param {NodeBuilder} builder - The current node builder.
  16591. */
  16592. indirect( builder ) {
  16593. this.indirectDiffuse( builder );
  16594. this.indirectSpecular( builder );
  16595. this.ambientOcclusion( builder );
  16596. }
  16597. /**
  16598. * Implements the indirect diffuse term.
  16599. *
  16600. * @param {NodeBuilder} builder - The current node builder.
  16601. */
  16602. indirectDiffuse( builder ) {
  16603. const { irradiance, reflectedLight } = builder.context;
  16604. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16605. }
  16606. /**
  16607. * Implements the indirect specular term.
  16608. *
  16609. * @param {NodeBuilder} builder - The current node builder.
  16610. */
  16611. indirectSpecular( builder ) {
  16612. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16613. if ( this.sheen === true ) {
  16614. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16615. sheen,
  16616. IBLSheenBRDF( {
  16617. normal: normalView,
  16618. viewDir: positionViewDirection,
  16619. roughness: sheenRoughness
  16620. } )
  16621. ) );
  16622. }
  16623. if ( this.clearcoat === true ) {
  16624. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16625. const clearcoatEnv = EnvironmentBRDF( {
  16626. dotNV: dotNVcc,
  16627. specularColor: clearcoatF0,
  16628. specularF90: clearcoatF90,
  16629. roughness: clearcoatRoughness
  16630. } );
  16631. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16632. }
  16633. // Both indirect specular and indirect diffuse light accumulate here
  16634. const singleScattering = vec3().toVar( 'singleScattering' );
  16635. const multiScattering = vec3().toVar( 'multiScattering' );
  16636. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16637. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16638. const totalScattering = singleScattering.add( multiScattering );
  16639. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16640. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16641. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16642. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16643. }
  16644. /**
  16645. * Implements the ambient occlusion term.
  16646. *
  16647. * @param {NodeBuilder} builder - The current node builder.
  16648. */
  16649. ambientOcclusion( builder ) {
  16650. const { ambientOcclusion, reflectedLight } = builder.context;
  16651. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16652. const aoNV = dotNV.add( ambientOcclusion );
  16653. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16654. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16655. if ( this.clearcoat === true ) {
  16656. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16657. }
  16658. if ( this.sheen === true ) {
  16659. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16660. }
  16661. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16662. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16663. }
  16664. /**
  16665. * Used for final lighting accumulations depending on the requested features.
  16666. *
  16667. * @param {NodeBuilder} builder - The current node builder.
  16668. */
  16669. finish( { context } ) {
  16670. const { outgoingLight } = context;
  16671. if ( this.clearcoat === true ) {
  16672. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16673. const Fcc = F_Schlick( {
  16674. dotVH: dotNVcc,
  16675. f0: clearcoatF0,
  16676. f90: clearcoatF90
  16677. } );
  16678. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  16679. outgoingLight.assign( clearcoatLight );
  16680. }
  16681. if ( this.sheen === true ) {
  16682. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  16683. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  16684. outgoingLight.assign( sheenLight );
  16685. }
  16686. }
  16687. }
  16688. // These defines must match with PMREMGenerator
  16689. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  16690. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  16691. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  16692. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  16693. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  16694. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  16695. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  16696. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  16697. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  16698. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  16699. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  16700. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  16701. // These shader functions convert between the UV coordinates of a single face of
  16702. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  16703. // sampling a textureCube (not generally normalized ).
  16704. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  16705. const absDirection = vec3( abs( direction ) ).toVar();
  16706. const face = float( -1 ).toVar();
  16707. If( absDirection.x.greaterThan( absDirection.z ), () => {
  16708. If( absDirection.x.greaterThan( absDirection.y ), () => {
  16709. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  16710. } ).Else( () => {
  16711. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16712. } );
  16713. } ).Else( () => {
  16714. If( absDirection.z.greaterThan( absDirection.y ), () => {
  16715. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  16716. } ).Else( () => {
  16717. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16718. } );
  16719. } );
  16720. return face;
  16721. } ).setLayout( {
  16722. name: 'getFace',
  16723. type: 'float',
  16724. inputs: [
  16725. { name: 'direction', type: 'vec3' }
  16726. ]
  16727. } );
  16728. // RH coordinate system; PMREM face-indexing convention
  16729. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  16730. const uv = vec2().toVar();
  16731. If( face.equal( 0.0 ), () => {
  16732. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  16733. } ).ElseIf( face.equal( 1.0 ), () => {
  16734. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  16735. } ).ElseIf( face.equal( 2.0 ), () => {
  16736. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  16737. } ).ElseIf( face.equal( 3.0 ), () => {
  16738. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  16739. } ).ElseIf( face.equal( 4.0 ), () => {
  16740. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  16741. } ).Else( () => {
  16742. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  16743. } );
  16744. return mul( 0.5, uv.add( 1.0 ) );
  16745. } ).setLayout( {
  16746. name: 'getUV',
  16747. type: 'vec2',
  16748. inputs: [
  16749. { name: 'direction', type: 'vec3' },
  16750. { name: 'face', type: 'float' }
  16751. ]
  16752. } );
  16753. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  16754. const mip = float( 0.0 ).toVar();
  16755. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  16756. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  16757. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  16758. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  16759. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  16760. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  16761. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  16762. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  16763. } ).Else( () => {
  16764. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  16765. } );
  16766. return mip;
  16767. } ).setLayout( {
  16768. name: 'roughnessToMip',
  16769. type: 'float',
  16770. inputs: [
  16771. { name: 'roughness', type: 'float' }
  16772. ]
  16773. } );
  16774. // RH coordinate system; PMREM face-indexing convention
  16775. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  16776. const uv = uv_immutable.toVar();
  16777. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  16778. const direction = vec3( uv, 1.0 ).toVar();
  16779. If( face.equal( 0.0 ), () => {
  16780. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  16781. } ).ElseIf( face.equal( 1.0 ), () => {
  16782. direction.assign( direction.xzy );
  16783. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  16784. } ).ElseIf( face.equal( 2.0 ), () => {
  16785. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  16786. } ).ElseIf( face.equal( 3.0 ), () => {
  16787. direction.assign( direction.zyx );
  16788. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  16789. } ).ElseIf( face.equal( 4.0 ), () => {
  16790. direction.assign( direction.xzy );
  16791. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  16792. } ).ElseIf( face.equal( 5.0 ), () => {
  16793. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  16794. } );
  16795. return direction;
  16796. } ).setLayout( {
  16797. name: 'getDirection',
  16798. type: 'vec3',
  16799. inputs: [
  16800. { name: 'uv', type: 'vec2' },
  16801. { name: 'face', type: 'float' }
  16802. ]
  16803. } );
  16804. //
  16805. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16806. const roughness = float( roughness_immutable );
  16807. const sampleDir = vec3( sampleDir_immutable );
  16808. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  16809. const mipF = fract( mip );
  16810. const mipInt = floor( mip );
  16811. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16812. If( mipF.notEqual( 0.0 ), () => {
  16813. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16814. color0.assign( mix( color0, color1, mipF ) );
  16815. } );
  16816. return color0;
  16817. } );
  16818. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16819. const mipInt = float( mipInt_immutable ).toVar();
  16820. const direction = vec3( direction_immutable );
  16821. const face = float( getFace( direction ) ).toVar();
  16822. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  16823. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  16824. const faceSize = float( exp2( mipInt ) ).toVar();
  16825. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  16826. If( face.greaterThan( 2.0 ), () => {
  16827. uv.y.addAssign( faceSize );
  16828. face.subAssign( 3.0 );
  16829. } );
  16830. uv.x.addAssign( face.mul( faceSize ) );
  16831. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  16832. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  16833. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  16834. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  16835. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  16836. } );
  16837. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16838. const cosTheta = cos( theta );
  16839. // Rodrigues' axis-angle rotation
  16840. const sampleDirection = outputDirection.mul( cosTheta )
  16841. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  16842. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  16843. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  16844. } );
  16845. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16846. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  16847. If( axis.equal( vec3( 0.0 ) ), () => {
  16848. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  16849. } );
  16850. axis.assign( normalize( axis ) );
  16851. const gl_FragColor = vec3().toVar();
  16852. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16853. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  16854. If( i.greaterThanEqual( samples ), () => {
  16855. Break();
  16856. } );
  16857. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  16858. 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 } ) ) );
  16859. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16860. } );
  16861. return vec4( gl_FragColor, 1 );
  16862. } );
  16863. const LOD_MIN = 4;
  16864. // The standard deviations (radians) associated with the extra mips. These are
  16865. // chosen to approximate a Trowbridge-Reitz distribution function times the
  16866. // geometric shadowing function. These sigma values squared must match the
  16867. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  16868. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  16869. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  16870. // samples and exit early, but not recompile the shader.
  16871. const MAX_SAMPLES = 20;
  16872. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  16873. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  16874. const _clearColor$2 = /*@__PURE__*/ new Color();
  16875. let _oldTarget = null;
  16876. let _oldActiveCubeFace = 0;
  16877. let _oldActiveMipmapLevel = 0;
  16878. // Golden Ratio
  16879. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  16880. const INV_PHI = 1 / PHI;
  16881. // Vertices of a dodecahedron (except the opposites, which represent the
  16882. // same axis), used as axis directions evenly spread on a sphere.
  16883. const _axisDirections = [
  16884. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  16885. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  16886. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  16887. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  16888. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  16889. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  16890. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  16891. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  16892. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  16893. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  16894. ];
  16895. const _origin = /*@__PURE__*/ new Vector3();
  16896. // maps blur materials to their uniforms dictionary
  16897. const _uniformsMap = new WeakMap();
  16898. // WebGPU Face indices
  16899. const _faceLib = [
  16900. 3, 1, 5,
  16901. 0, 4, 2
  16902. ];
  16903. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  16904. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  16905. /**
  16906. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  16907. * (PMREM) from a cubeMap environment texture. This allows different levels of
  16908. * blur to be quickly accessed based on material roughness. It is packed into a
  16909. * special CubeUV format that allows us to perform custom interpolation so that
  16910. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  16911. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  16912. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  16913. * higher roughness levels. In this way we maintain resolution to smoothly
  16914. * interpolate diffuse lighting while limiting sampling computation.
  16915. *
  16916. * Paper: Fast, Accurate Image-Based Lighting:
  16917. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  16918. */
  16919. class PMREMGenerator {
  16920. /**
  16921. * Constructs a new PMREM generator.
  16922. *
  16923. * @param {Renderer} renderer - The renderer.
  16924. */
  16925. constructor( renderer ) {
  16926. this._renderer = renderer;
  16927. this._pingPongRenderTarget = null;
  16928. this._lodMax = 0;
  16929. this._cubeSize = 0;
  16930. this._lodPlanes = [];
  16931. this._sizeLods = [];
  16932. this._sigmas = [];
  16933. this._lodMeshes = [];
  16934. this._blurMaterial = null;
  16935. this._cubemapMaterial = null;
  16936. this._equirectMaterial = null;
  16937. this._backgroundBox = null;
  16938. }
  16939. get _hasInitialized() {
  16940. return this._renderer.hasInitialized();
  16941. }
  16942. /**
  16943. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16944. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16945. * in radians to be applied to the scene before PMREM generation. Optional near
  16946. * and far planes ensure the scene is rendered in its entirety.
  16947. *
  16948. * @param {Scene} scene - The scene to be captured.
  16949. * @param {number} [sigma=0] - The blur radius in radians.
  16950. * @param {number} [near=0.1] - The near plane distance.
  16951. * @param {number} [far=100] - The far plane distance.
  16952. * @param {Object} [options={}] - The configuration options.
  16953. * @param {number} [options.size=256] - The texture size of the PMREM.
  16954. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  16955. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16956. * @return {RenderTarget} The resulting PMREM.
  16957. * @see {@link PMREMGenerator#fromSceneAsync}
  16958. */
  16959. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16960. const {
  16961. size = 256,
  16962. position = _origin,
  16963. renderTarget = null,
  16964. } = options;
  16965. this._setSize( size );
  16966. if ( this._hasInitialized === false ) {
  16967. warn( 'PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  16968. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16969. options.renderTarget = cubeUVRenderTarget;
  16970. this.fromSceneAsync( scene, sigma, near, far, options );
  16971. return cubeUVRenderTarget;
  16972. }
  16973. _oldTarget = this._renderer.getRenderTarget();
  16974. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16975. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16976. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16977. cubeUVRenderTarget.depthBuffer = true;
  16978. this._init( cubeUVRenderTarget );
  16979. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  16980. if ( sigma > 0 ) {
  16981. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  16982. }
  16983. this._applyPMREM( cubeUVRenderTarget );
  16984. this._cleanup( cubeUVRenderTarget );
  16985. return cubeUVRenderTarget;
  16986. }
  16987. /**
  16988. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16989. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16990. * in radians to be applied to the scene before PMREM generation. Optional near
  16991. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  16992. * is placed at the origin).
  16993. *
  16994. * @param {Scene} scene - The scene to be captured.
  16995. * @param {number} [sigma=0] - The blur radius in radians.
  16996. * @param {number} [near=0.1] - The near plane distance.
  16997. * @param {number} [far=100] - The far plane distance.
  16998. * @param {Object} [options={}] - The configuration options.
  16999. * @param {number} [options.size=256] - The texture size of the PMREM.
  17000. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  17001. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  17002. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  17003. * @see {@link PMREMGenerator#fromScene}
  17004. */
  17005. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  17006. if ( this._hasInitialized === false ) await this._renderer.init();
  17007. return this.fromScene( scene, sigma, near, far, options );
  17008. }
  17009. /**
  17010. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17011. * or HDR. The ideal input image size is 1k (1024 x 512),
  17012. * as this matches best with the 256 x 256 cubemap output.
  17013. *
  17014. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17015. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17016. * @return {RenderTarget} The resulting PMREM.
  17017. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  17018. */
  17019. fromEquirectangular( equirectangular, renderTarget = null ) {
  17020. if ( this._hasInitialized === false ) {
  17021. warn( 'PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  17022. this._setSizeFromTexture( equirectangular );
  17023. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17024. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17025. return cubeUVRenderTarget;
  17026. }
  17027. return this._fromTexture( equirectangular, renderTarget );
  17028. }
  17029. /**
  17030. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17031. * or HDR. The ideal input image size is 1k (1024 x 512),
  17032. * as this matches best with the 256 x 256 cubemap output.
  17033. *
  17034. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17035. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17036. * @return {Promise<RenderTarget>} The resulting PMREM.
  17037. * @see {@link PMREMGenerator#fromEquirectangular}
  17038. */
  17039. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17040. if ( this._hasInitialized === false ) await this._renderer.init();
  17041. return this._fromTexture( equirectangular, renderTarget );
  17042. }
  17043. /**
  17044. * Generates a PMREM from an cubemap texture, which can be either LDR
  17045. * or HDR. The ideal input cube size is 256 x 256,
  17046. * as this matches best with the 256 x 256 cubemap output.
  17047. *
  17048. * @param {Texture} cubemap - The cubemap texture to be converted.
  17049. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17050. * @return {RenderTarget} The resulting PMREM.
  17051. * @see {@link PMREMGenerator#fromCubemapAsync}
  17052. */
  17053. fromCubemap( cubemap, renderTarget = null ) {
  17054. if ( this._hasInitialized === false ) {
  17055. warn( 'PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17056. this._setSizeFromTexture( cubemap );
  17057. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17058. this.fromCubemapAsync( cubemap, renderTarget );
  17059. return cubeUVRenderTarget;
  17060. }
  17061. return this._fromTexture( cubemap, renderTarget );
  17062. }
  17063. /**
  17064. * Generates a PMREM from an cubemap texture, which can be either LDR
  17065. * or HDR. The ideal input cube size is 256 x 256,
  17066. * with the 256 x 256 cubemap output.
  17067. *
  17068. * @param {Texture} cubemap - The cubemap texture to be converted.
  17069. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17070. * @return {Promise<RenderTarget>} The resulting PMREM.
  17071. * @see {@link PMREMGenerator#fromCubemap}
  17072. */
  17073. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17074. if ( this._hasInitialized === false ) await this._renderer.init();
  17075. return this._fromTexture( cubemap, renderTarget );
  17076. }
  17077. /**
  17078. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17079. * your texture's network fetch for increased concurrency.
  17080. *
  17081. * @returns {Promise}
  17082. */
  17083. async compileCubemapShader() {
  17084. if ( this._cubemapMaterial === null ) {
  17085. this._cubemapMaterial = _getCubemapMaterial();
  17086. await this._compileMaterial( this._cubemapMaterial );
  17087. }
  17088. }
  17089. /**
  17090. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17091. * your texture's network fetch for increased concurrency.
  17092. *
  17093. * @returns {Promise}
  17094. */
  17095. async compileEquirectangularShader() {
  17096. if ( this._equirectMaterial === null ) {
  17097. this._equirectMaterial = _getEquirectMaterial();
  17098. await this._compileMaterial( this._equirectMaterial );
  17099. }
  17100. }
  17101. /**
  17102. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17103. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17104. * one of them will cause any others to also become unusable.
  17105. */
  17106. dispose() {
  17107. this._dispose();
  17108. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17109. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17110. if ( this._backgroundBox !== null ) {
  17111. this._backgroundBox.geometry.dispose();
  17112. this._backgroundBox.material.dispose();
  17113. }
  17114. }
  17115. // private interface
  17116. _setSizeFromTexture( texture ) {
  17117. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17118. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17119. } else { // Equirectangular
  17120. this._setSize( texture.image.width / 4 );
  17121. }
  17122. }
  17123. _setSize( cubeSize ) {
  17124. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17125. this._cubeSize = Math.pow( 2, this._lodMax );
  17126. }
  17127. _dispose() {
  17128. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17129. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17130. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  17131. this._lodPlanes[ i ].dispose();
  17132. }
  17133. }
  17134. _cleanup( outputTarget ) {
  17135. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17136. outputTarget.scissorTest = false;
  17137. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17138. }
  17139. _fromTexture( texture, renderTarget ) {
  17140. this._setSizeFromTexture( texture );
  17141. _oldTarget = this._renderer.getRenderTarget();
  17142. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17143. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17144. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17145. this._init( cubeUVRenderTarget );
  17146. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17147. this._applyPMREM( cubeUVRenderTarget );
  17148. this._cleanup( cubeUVRenderTarget );
  17149. return cubeUVRenderTarget;
  17150. }
  17151. _allocateTarget() {
  17152. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17153. const height = 4 * this._cubeSize;
  17154. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17155. return cubeUVRenderTarget;
  17156. }
  17157. _init( renderTarget ) {
  17158. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17159. if ( this._pingPongRenderTarget !== null ) {
  17160. this._dispose();
  17161. }
  17162. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17163. const { _lodMax } = this;
  17164. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  17165. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17166. }
  17167. }
  17168. async _compileMaterial( material ) {
  17169. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  17170. await this._renderer.compile( tmpMesh, _flatCamera );
  17171. }
  17172. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17173. const cubeCamera = _cubeCamera;
  17174. cubeCamera.near = near;
  17175. cubeCamera.far = far;
  17176. // px, py, pz, nx, ny, nz
  17177. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17178. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17179. const renderer = this._renderer;
  17180. const originalAutoClear = renderer.autoClear;
  17181. renderer.getClearColor( _clearColor$2 );
  17182. renderer.autoClear = false;
  17183. let backgroundBox = this._backgroundBox;
  17184. if ( backgroundBox === null ) {
  17185. const backgroundMaterial = new MeshBasicMaterial( {
  17186. name: 'PMREM.Background',
  17187. side: BackSide,
  17188. depthWrite: false,
  17189. depthTest: false
  17190. } );
  17191. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  17192. }
  17193. let useSolidColor = false;
  17194. const background = scene.background;
  17195. if ( background ) {
  17196. if ( background.isColor ) {
  17197. backgroundBox.material.color.copy( background );
  17198. scene.background = null;
  17199. useSolidColor = true;
  17200. }
  17201. } else {
  17202. backgroundBox.material.color.copy( _clearColor$2 );
  17203. useSolidColor = true;
  17204. }
  17205. renderer.setRenderTarget( cubeUVRenderTarget );
  17206. renderer.clear();
  17207. if ( useSolidColor ) {
  17208. renderer.render( backgroundBox, cubeCamera );
  17209. }
  17210. for ( let i = 0; i < 6; i ++ ) {
  17211. const col = i % 3;
  17212. if ( col === 0 ) {
  17213. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17214. cubeCamera.position.set( position.x, position.y, position.z );
  17215. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17216. } else if ( col === 1 ) {
  17217. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17218. cubeCamera.position.set( position.x, position.y, position.z );
  17219. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17220. } else {
  17221. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17222. cubeCamera.position.set( position.x, position.y, position.z );
  17223. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17224. }
  17225. const size = this._cubeSize;
  17226. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17227. renderer.render( scene, cubeCamera );
  17228. }
  17229. renderer.autoClear = originalAutoClear;
  17230. scene.background = background;
  17231. }
  17232. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17233. const renderer = this._renderer;
  17234. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17235. if ( isCubeTexture ) {
  17236. if ( this._cubemapMaterial === null ) {
  17237. this._cubemapMaterial = _getCubemapMaterial( texture );
  17238. }
  17239. } else {
  17240. if ( this._equirectMaterial === null ) {
  17241. this._equirectMaterial = _getEquirectMaterial( texture );
  17242. }
  17243. }
  17244. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17245. material.fragmentNode.value = texture;
  17246. const mesh = this._lodMeshes[ 0 ];
  17247. mesh.material = material;
  17248. const size = this._cubeSize;
  17249. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17250. renderer.setRenderTarget( cubeUVRenderTarget );
  17251. renderer.render( mesh, _flatCamera );
  17252. }
  17253. _applyPMREM( cubeUVRenderTarget ) {
  17254. const renderer = this._renderer;
  17255. const autoClear = renderer.autoClear;
  17256. renderer.autoClear = false;
  17257. const n = this._lodPlanes.length;
  17258. for ( let i = 1; i < n; i ++ ) {
  17259. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  17260. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  17261. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  17262. }
  17263. renderer.autoClear = autoClear;
  17264. }
  17265. /**
  17266. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17267. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17268. * the blur latitudinally (around the poles), and then longitudinally (towards
  17269. * the poles) to approximate the orthogonally-separable blur. It is least
  17270. * accurate at the poles, but still does a decent job.
  17271. *
  17272. * @private
  17273. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17274. * @param {number} lodIn - The input level-of-detail.
  17275. * @param {number} lodOut - The output level-of-detail.
  17276. * @param {number} sigma - The blur radius in radians.
  17277. * @param {Vector3} [poleAxis] - The pole axis.
  17278. */
  17279. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17280. const pingPongRenderTarget = this._pingPongRenderTarget;
  17281. this._halfBlur(
  17282. cubeUVRenderTarget,
  17283. pingPongRenderTarget,
  17284. lodIn,
  17285. lodOut,
  17286. sigma,
  17287. 'latitudinal',
  17288. poleAxis );
  17289. this._halfBlur(
  17290. pingPongRenderTarget,
  17291. cubeUVRenderTarget,
  17292. lodOut,
  17293. lodOut,
  17294. sigma,
  17295. 'longitudinal',
  17296. poleAxis );
  17297. }
  17298. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17299. const renderer = this._renderer;
  17300. const blurMaterial = this._blurMaterial;
  17301. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17302. error( 'blur direction must be either latitudinal or longitudinal!' );
  17303. }
  17304. // Number of standard deviations at which to cut off the discrete approximation.
  17305. const STANDARD_DEVIATIONS = 3;
  17306. const blurMesh = this._lodMeshes[ lodOut ];
  17307. blurMesh.material = blurMaterial;
  17308. const blurUniforms = _uniformsMap.get( blurMaterial );
  17309. const pixels = this._sizeLods[ lodIn ] - 1;
  17310. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17311. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17312. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17313. if ( samples > MAX_SAMPLES ) {
  17314. warn( `sigmaRadians, ${
  17315. sigmaRadians}, is too large and will clip, as it requested ${
  17316. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17317. }
  17318. const weights = [];
  17319. let sum = 0;
  17320. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17321. const x = i / sigmaPixels;
  17322. const weight = Math.exp( - x * x / 2 );
  17323. weights.push( weight );
  17324. if ( i === 0 ) {
  17325. sum += weight;
  17326. } else if ( i < samples ) {
  17327. sum += 2 * weight;
  17328. }
  17329. }
  17330. for ( let i = 0; i < weights.length; i ++ ) {
  17331. weights[ i ] = weights[ i ] / sum;
  17332. }
  17333. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17334. blurUniforms.envMap.value = targetIn.texture;
  17335. blurUniforms.samples.value = samples;
  17336. blurUniforms.weights.array = weights;
  17337. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17338. if ( poleAxis ) {
  17339. blurUniforms.poleAxis.value = poleAxis;
  17340. }
  17341. const { _lodMax } = this;
  17342. blurUniforms.dTheta.value = radiansPerPixel;
  17343. blurUniforms.mipInt.value = _lodMax - lodIn;
  17344. const outputSize = this._sizeLods[ lodOut ];
  17345. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17346. const y = 4 * ( this._cubeSize - outputSize );
  17347. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17348. renderer.setRenderTarget( targetOut );
  17349. renderer.render( blurMesh, _flatCamera );
  17350. }
  17351. }
  17352. function _createPlanes( lodMax ) {
  17353. const lodPlanes = [];
  17354. const sizeLods = [];
  17355. const sigmas = [];
  17356. const lodMeshes = [];
  17357. let lod = lodMax;
  17358. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17359. for ( let i = 0; i < totalLods; i ++ ) {
  17360. const sizeLod = Math.pow( 2, lod );
  17361. sizeLods.push( sizeLod );
  17362. let sigma = 1.0 / sizeLod;
  17363. if ( i > lodMax - LOD_MIN ) {
  17364. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17365. } else if ( i === 0 ) {
  17366. sigma = 0;
  17367. }
  17368. sigmas.push( sigma );
  17369. const texelSize = 1.0 / ( sizeLod - 2 );
  17370. const min = - texelSize;
  17371. const max = 1 + texelSize;
  17372. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17373. const cubeFaces = 6;
  17374. const vertices = 6;
  17375. const positionSize = 3;
  17376. const uvSize = 2;
  17377. const faceIndexSize = 1;
  17378. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17379. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17380. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17381. for ( let face = 0; face < cubeFaces; face ++ ) {
  17382. const x = ( face % 3 ) * 2 / 3 - 1;
  17383. const y = face > 2 ? 0 : -1;
  17384. const coordinates = [
  17385. x, y, 0,
  17386. x + 2 / 3, y, 0,
  17387. x + 2 / 3, y + 1, 0,
  17388. x, y, 0,
  17389. x + 2 / 3, y + 1, 0,
  17390. x, y + 1, 0
  17391. ];
  17392. const faceIdx = _faceLib[ face ];
  17393. position.set( coordinates, positionSize * vertices * faceIdx );
  17394. uv.set( uv1, uvSize * vertices * faceIdx );
  17395. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17396. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17397. }
  17398. const planes = new BufferGeometry();
  17399. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17400. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17401. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17402. lodPlanes.push( planes );
  17403. lodMeshes.push( new Mesh( planes, null ) );
  17404. if ( lod > LOD_MIN ) {
  17405. lod --;
  17406. }
  17407. }
  17408. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17409. }
  17410. function _createRenderTarget( width, height ) {
  17411. const params = {
  17412. magFilter: LinearFilter,
  17413. minFilter: LinearFilter,
  17414. generateMipmaps: false,
  17415. type: HalfFloatType,
  17416. format: RGBAFormat,
  17417. colorSpace: LinearSRGBColorSpace,
  17418. //depthBuffer: false
  17419. };
  17420. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17421. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17422. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17423. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17424. cubeUVRenderTarget.scissorTest = true;
  17425. return cubeUVRenderTarget;
  17426. }
  17427. function _setViewport( target, x, y, width, height ) {
  17428. target.viewport.set( x, y, width, height );
  17429. target.scissor.set( x, y, width, height );
  17430. }
  17431. function _getMaterial( type ) {
  17432. const material = new NodeMaterial();
  17433. material.depthTest = false;
  17434. material.depthWrite = false;
  17435. material.blending = NoBlending;
  17436. material.name = `PMREM_${ type }`;
  17437. return material;
  17438. }
  17439. function _getBlurShader( lodMax, width, height ) {
  17440. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17441. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17442. const dTheta = uniform( 0 );
  17443. const n = float( MAX_SAMPLES );
  17444. const latitudinal = uniform( 0 ); // false, bool
  17445. const samples = uniform( 1 ); // int
  17446. const envMap = texture( null );
  17447. const mipInt = uniform( 0 ); // int
  17448. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17449. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17450. const CUBEUV_MAX_MIP = float( lodMax );
  17451. const materialUniforms = {
  17452. n,
  17453. latitudinal,
  17454. weights,
  17455. poleAxis,
  17456. outputDirection: _outputDirection,
  17457. dTheta,
  17458. samples,
  17459. envMap,
  17460. mipInt,
  17461. CUBEUV_TEXEL_WIDTH,
  17462. CUBEUV_TEXEL_HEIGHT,
  17463. CUBEUV_MAX_MIP
  17464. };
  17465. const material = _getMaterial( 'blur' );
  17466. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17467. _uniformsMap.set( material, materialUniforms );
  17468. return material;
  17469. }
  17470. function _getCubemapMaterial( envTexture ) {
  17471. const material = _getMaterial( 'cubemap' );
  17472. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17473. return material;
  17474. }
  17475. function _getEquirectMaterial( envTexture ) {
  17476. const material = _getMaterial( 'equirect' );
  17477. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17478. return material;
  17479. }
  17480. const _cache = new WeakMap();
  17481. /**
  17482. * Generates the cubeUV size based on the given image height.
  17483. *
  17484. * @private
  17485. * @param {number} imageHeight - The image height.
  17486. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17487. */
  17488. function _generateCubeUVSize( imageHeight ) {
  17489. const maxMip = Math.log2( imageHeight ) - 2;
  17490. const texelHeight = 1.0 / imageHeight;
  17491. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17492. return { texelWidth, texelHeight, maxMip };
  17493. }
  17494. /**
  17495. * Generates a PMREM from the given texture.
  17496. *
  17497. * @private
  17498. * @param {Texture} texture - The texture to create the PMREM for.
  17499. * @param {Renderer} renderer - The renderer.
  17500. * @param {PMREMGenerator} generator - The PMREM generator.
  17501. * @return {?Texture} The PMREM.
  17502. */
  17503. function _getPMREMFromTexture( texture, renderer, generator ) {
  17504. const cache = _getCache( renderer );
  17505. let cacheTexture = cache.get( texture );
  17506. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17507. if ( pmremVersion !== texture.pmremVersion ) {
  17508. const image = texture.image;
  17509. if ( texture.isCubeTexture ) {
  17510. if ( isCubeMapReady( image ) ) {
  17511. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17512. } else {
  17513. return null;
  17514. }
  17515. } else {
  17516. if ( isEquirectangularMapReady( image ) ) {
  17517. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17518. } else {
  17519. return null;
  17520. }
  17521. }
  17522. cacheTexture.pmremVersion = texture.pmremVersion;
  17523. cache.set( texture, cacheTexture );
  17524. }
  17525. return cacheTexture.texture;
  17526. }
  17527. /**
  17528. * Returns a cache that stores generated PMREMs for the respective textures.
  17529. * A cache must be maintained per renderer since PMREMs are render target textures
  17530. * which can't be shared across render contexts.
  17531. *
  17532. * @private
  17533. * @param {Renderer} renderer - The renderer.
  17534. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17535. */
  17536. function _getCache( renderer ) {
  17537. let rendererCache = _cache.get( renderer );
  17538. if ( rendererCache === undefined ) {
  17539. rendererCache = new WeakMap();
  17540. _cache.set( renderer, rendererCache );
  17541. }
  17542. return rendererCache;
  17543. }
  17544. /**
  17545. * This node represents a PMREM which is a special type of preprocessed
  17546. * environment map intended for PBR materials.
  17547. *
  17548. * ```js
  17549. * const material = new MeshStandardNodeMaterial();
  17550. * material.envNode = pmremTexture( envMap );
  17551. * ```
  17552. *
  17553. * @augments TempNode
  17554. */
  17555. class PMREMNode extends TempNode {
  17556. static get type() {
  17557. return 'PMREMNode';
  17558. }
  17559. /**
  17560. * Constructs a new function overloading node.
  17561. *
  17562. * @param {Texture} value - The input texture.
  17563. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17564. * @param {Node<float>} [levelNode=null] - The level node.
  17565. */
  17566. constructor( value, uvNode = null, levelNode = null ) {
  17567. super( 'vec3' );
  17568. /**
  17569. * Reference to the input texture.
  17570. *
  17571. * @private
  17572. * @type {Texture}
  17573. */
  17574. this._value = value;
  17575. /**
  17576. * Reference to the generated PMREM.
  17577. *
  17578. * @private
  17579. * @type {Texture | null}
  17580. * @default null
  17581. */
  17582. this._pmrem = null;
  17583. /**
  17584. * The uv node.
  17585. *
  17586. * @type {Node<vec2>}
  17587. */
  17588. this.uvNode = uvNode;
  17589. /**
  17590. * The level node.
  17591. *
  17592. * @type {Node<float>}
  17593. */
  17594. this.levelNode = levelNode;
  17595. /**
  17596. * Reference to a PMREM generator.
  17597. *
  17598. * @private
  17599. * @type {?PMREMGenerator}
  17600. * @default null
  17601. */
  17602. this._generator = null;
  17603. const defaultTexture = new Texture();
  17604. defaultTexture.isRenderTargetTexture = true;
  17605. /**
  17606. * The texture node holding the generated PMREM.
  17607. *
  17608. * @private
  17609. * @type {TextureNode}
  17610. */
  17611. this._texture = texture( defaultTexture );
  17612. /**
  17613. * A uniform representing the PMREM's width.
  17614. *
  17615. * @private
  17616. * @type {UniformNode<float>}
  17617. */
  17618. this._width = uniform( 0 );
  17619. /**
  17620. * A uniform representing the PMREM's height.
  17621. *
  17622. * @private
  17623. * @type {UniformNode<float>}
  17624. */
  17625. this._height = uniform( 0 );
  17626. /**
  17627. * A uniform representing the PMREM's max Mip.
  17628. *
  17629. * @private
  17630. * @type {UniformNode<float>}
  17631. */
  17632. this._maxMip = uniform( 0 );
  17633. /**
  17634. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17635. *
  17636. * @type {string}
  17637. * @default 'render'
  17638. */
  17639. this.updateBeforeType = NodeUpdateType.RENDER;
  17640. }
  17641. set value( value ) {
  17642. this._value = value;
  17643. this._pmrem = null;
  17644. }
  17645. /**
  17646. * The node's texture value.
  17647. *
  17648. * @type {Texture}
  17649. */
  17650. get value() {
  17651. return this._value;
  17652. }
  17653. /**
  17654. * Uses the given PMREM texture to update internal values.
  17655. *
  17656. * @param {Texture} texture - The PMREM texture.
  17657. */
  17658. updateFromTexture( texture ) {
  17659. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17660. this._texture.value = texture;
  17661. this._width.value = cubeUVSize.texelWidth;
  17662. this._height.value = cubeUVSize.texelHeight;
  17663. this._maxMip.value = cubeUVSize.maxMip;
  17664. }
  17665. updateBefore( frame ) {
  17666. let pmrem = this._pmrem;
  17667. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17668. const texture = this._value;
  17669. if ( pmremVersion !== texture.pmremVersion ) {
  17670. if ( texture.isPMREMTexture === true ) {
  17671. pmrem = texture;
  17672. } else {
  17673. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17674. }
  17675. if ( pmrem !== null ) {
  17676. this._pmrem = pmrem;
  17677. this.updateFromTexture( pmrem );
  17678. }
  17679. }
  17680. }
  17681. setup( builder ) {
  17682. if ( this._generator === null ) {
  17683. this._generator = new PMREMGenerator( builder.renderer );
  17684. }
  17685. this.updateBefore( builder );
  17686. //
  17687. let uvNode = this.uvNode;
  17688. if ( uvNode === null && builder.context.getUV ) {
  17689. uvNode = builder.context.getUV( this );
  17690. }
  17691. //
  17692. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  17693. //
  17694. let levelNode = this.levelNode;
  17695. if ( levelNode === null && builder.context.getTextureLevel ) {
  17696. levelNode = builder.context.getTextureLevel( this );
  17697. }
  17698. //
  17699. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  17700. }
  17701. dispose() {
  17702. super.dispose();
  17703. if ( this._generator !== null ) this._generator.dispose();
  17704. }
  17705. }
  17706. /**
  17707. * Returns `true` if the given cube map image has been fully loaded.
  17708. *
  17709. * @private
  17710. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  17711. * @return {boolean} Whether the given cube map is ready or not.
  17712. */
  17713. function isCubeMapReady( image ) {
  17714. if ( image === null || image === undefined ) return false;
  17715. let count = 0;
  17716. const length = 6;
  17717. for ( let i = 0; i < length; i ++ ) {
  17718. if ( image[ i ] !== undefined ) count ++;
  17719. }
  17720. return count === length;
  17721. }
  17722. /**
  17723. * Returns `true` if the given equirectangular image has been fully loaded.
  17724. *
  17725. * @private
  17726. * @param {(Image|Object)} image - The equirectangular image.
  17727. * @return {boolean} Whether the given cube map is ready or not.
  17728. */
  17729. function isEquirectangularMapReady( image ) {
  17730. if ( image === null || image === undefined ) return false;
  17731. return image.height > 0;
  17732. }
  17733. /**
  17734. * TSL function for creating a PMREM node.
  17735. *
  17736. * @tsl
  17737. * @function
  17738. * @param {Texture} value - The input texture.
  17739. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  17740. * @param {?Node<float>} [levelNode=null] - The level node.
  17741. * @returns {PMREMNode}
  17742. */
  17743. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  17744. const _envNodeCache = new WeakMap();
  17745. /**
  17746. * Represents a physical model for Image-based lighting (IBL). The environment
  17747. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  17748. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  17749. *
  17750. * @augments LightingNode
  17751. */
  17752. class EnvironmentNode extends LightingNode {
  17753. static get type() {
  17754. return 'EnvironmentNode';
  17755. }
  17756. /**
  17757. * Constructs a new environment node.
  17758. *
  17759. * @param {Node} [envNode=null] - A node representing the environment.
  17760. */
  17761. constructor( envNode = null ) {
  17762. super();
  17763. /**
  17764. * A node representing the environment.
  17765. *
  17766. * @type {?Node}
  17767. * @default null
  17768. */
  17769. this.envNode = envNode;
  17770. }
  17771. setup( builder ) {
  17772. const { material } = builder;
  17773. let envNode = this.envNode;
  17774. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  17775. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  17776. let cacheEnvNode = _envNodeCache.get( value );
  17777. if ( cacheEnvNode === undefined ) {
  17778. cacheEnvNode = pmremTexture( value );
  17779. _envNodeCache.set( value, cacheEnvNode );
  17780. }
  17781. envNode = cacheEnvNode;
  17782. }
  17783. //
  17784. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  17785. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  17786. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  17787. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  17788. const isolateRadiance = cache( radiance );
  17789. const isolateIrradiance = cache( irradiance );
  17790. //
  17791. builder.context.radiance.addAssign( isolateRadiance );
  17792. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  17793. //
  17794. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  17795. if ( clearcoatRadiance ) {
  17796. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  17797. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  17798. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  17799. }
  17800. }
  17801. }
  17802. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  17803. let reflectVec = null;
  17804. return {
  17805. getUV: () => {
  17806. if ( reflectVec === null ) {
  17807. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  17808. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  17809. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  17810. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  17811. }
  17812. return reflectVec;
  17813. },
  17814. getTextureLevel: () => {
  17815. return roughnessNode;
  17816. }
  17817. };
  17818. };
  17819. const createIrradianceContext = ( normalWorldNode ) => {
  17820. return {
  17821. getUV: () => {
  17822. return normalWorldNode;
  17823. },
  17824. getTextureLevel: () => {
  17825. return float( 1.0 );
  17826. }
  17827. };
  17828. };
  17829. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  17830. /**
  17831. * Node material version of {@link MeshStandardMaterial}.
  17832. *
  17833. * @augments NodeMaterial
  17834. */
  17835. class MeshStandardNodeMaterial extends NodeMaterial {
  17836. static get type() {
  17837. return 'MeshStandardNodeMaterial';
  17838. }
  17839. /**
  17840. * Constructs a new mesh standard node material.
  17841. *
  17842. * @param {Object} [parameters] - The configuration parameter.
  17843. */
  17844. constructor( parameters ) {
  17845. super();
  17846. /**
  17847. * This flag can be used for type testing.
  17848. *
  17849. * @type {boolean}
  17850. * @readonly
  17851. * @default true
  17852. */
  17853. this.isMeshStandardNodeMaterial = true;
  17854. /**
  17855. * Set to `true` because standard materials react on lights.
  17856. *
  17857. * @type {boolean}
  17858. * @default true
  17859. */
  17860. this.lights = true;
  17861. /**
  17862. * The emissive color of standard materials is by default inferred from the `emissive`,
  17863. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  17864. * overwrite the default and define the emissive color with a node instead.
  17865. *
  17866. * If you don't want to overwrite the emissive color but modify the existing
  17867. * value instead, use {@link materialEmissive}.
  17868. *
  17869. * @type {?Node<vec3>}
  17870. * @default null
  17871. */
  17872. this.emissiveNode = null;
  17873. /**
  17874. * The metalness of standard materials is by default inferred from the `metalness`,
  17875. * and `metalnessMap` properties. This node property allows to
  17876. * overwrite the default and define the metalness with a node instead.
  17877. *
  17878. * If you don't want to overwrite the metalness but modify the existing
  17879. * value instead, use {@link materialMetalness}.
  17880. *
  17881. * @type {?Node<float>}
  17882. * @default null
  17883. */
  17884. this.metalnessNode = null;
  17885. /**
  17886. * The roughness of standard materials is by default inferred from the `roughness`,
  17887. * and `roughnessMap` properties. This node property allows to
  17888. * overwrite the default and define the roughness with a node instead.
  17889. *
  17890. * If you don't want to overwrite the roughness but modify the existing
  17891. * value instead, use {@link materialRoughness}.
  17892. *
  17893. * @type {?Node<float>}
  17894. * @default null
  17895. */
  17896. this.roughnessNode = null;
  17897. this.setDefaultValues( _defaultValues$6 );
  17898. this.setValues( parameters );
  17899. }
  17900. /**
  17901. * Overwritten since this type of material uses {@link EnvironmentNode}
  17902. * to implement the PBR (PMREM based) environment mapping. Besides, the
  17903. * method honors `Scene.environment`.
  17904. *
  17905. * @param {NodeBuilder} builder - The current node builder.
  17906. * @return {?EnvironmentNode<vec3>} The environment node.
  17907. */
  17908. setupEnvironment( builder ) {
  17909. let envNode = super.setupEnvironment( builder );
  17910. if ( envNode === null && builder.environmentNode ) {
  17911. envNode = builder.environmentNode;
  17912. }
  17913. return envNode ? new EnvironmentNode( envNode ) : null;
  17914. }
  17915. /**
  17916. * Setups the lighting model.
  17917. *
  17918. * @return {PhysicalLightingModel} The lighting model.
  17919. */
  17920. setupLightingModel( /*builder*/ ) {
  17921. return new PhysicalLightingModel();
  17922. }
  17923. /**
  17924. * Setups the specular related node variables.
  17925. */
  17926. setupSpecular() {
  17927. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  17928. specularColor.assign( specularColorNode );
  17929. specularF90.assign( 1.0 );
  17930. }
  17931. /**
  17932. * Setups the standard specific node variables.
  17933. *
  17934. * @param {NodeBuilder} builder - The current node builder.
  17935. */
  17936. setupVariants() {
  17937. // METALNESS
  17938. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  17939. metalness.assign( metalnessNode );
  17940. // ROUGHNESS
  17941. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  17942. roughnessNode = getRoughness( { roughness: roughnessNode } );
  17943. roughness.assign( roughnessNode );
  17944. // SPECULAR COLOR
  17945. this.setupSpecular();
  17946. // DIFFUSE COLOR
  17947. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  17948. }
  17949. copy( source ) {
  17950. this.emissiveNode = source.emissiveNode;
  17951. this.metalnessNode = source.metalnessNode;
  17952. this.roughnessNode = source.roughnessNode;
  17953. return super.copy( source );
  17954. }
  17955. }
  17956. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  17957. /**
  17958. * Node material version of {@link MeshPhysicalMaterial}.
  17959. *
  17960. * @augments MeshStandardNodeMaterial
  17961. */
  17962. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  17963. static get type() {
  17964. return 'MeshPhysicalNodeMaterial';
  17965. }
  17966. /**
  17967. * Constructs a new mesh physical node material.
  17968. *
  17969. * @param {Object} [parameters] - The configuration parameter.
  17970. */
  17971. constructor( parameters ) {
  17972. super();
  17973. /**
  17974. * This flag can be used for type testing.
  17975. *
  17976. * @type {boolean}
  17977. * @readonly
  17978. * @default true
  17979. */
  17980. this.isMeshPhysicalNodeMaterial = true;
  17981. /**
  17982. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  17983. * and `clearcoatMap` properties. This node property allows to overwrite the default
  17984. * and define the clearcoat with a node instead.
  17985. *
  17986. * If you don't want to overwrite the clearcoat but modify the existing
  17987. * value instead, use {@link materialClearcoat}.
  17988. *
  17989. * @type {?Node<float>}
  17990. * @default null
  17991. */
  17992. this.clearcoatNode = null;
  17993. /**
  17994. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  17995. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  17996. * and define the clearcoat roughness with a node instead.
  17997. *
  17998. * If you don't want to overwrite the clearcoat roughness but modify the existing
  17999. * value instead, use {@link materialClearcoatRoughness}.
  18000. *
  18001. * @type {?Node<float>}
  18002. * @default null
  18003. */
  18004. this.clearcoatRoughnessNode = null;
  18005. /**
  18006. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  18007. * property. This node property allows to overwrite the default
  18008. * and define the clearcoat normal with a node instead.
  18009. *
  18010. * If you don't want to overwrite the clearcoat normal but modify the existing
  18011. * value instead, use {@link materialClearcoatNormal}.
  18012. *
  18013. * @type {?Node<vec3>}
  18014. * @default null
  18015. */
  18016. this.clearcoatNormalNode = null;
  18017. /**
  18018. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  18019. * and `sheenColorMap` properties. This node property allows to overwrite the default
  18020. * and define the sheen with a node instead.
  18021. *
  18022. * If you don't want to overwrite the sheen but modify the existing
  18023. * value instead, use {@link materialSheen}.
  18024. *
  18025. * @type {?Node<vec3>}
  18026. * @default null
  18027. */
  18028. this.sheenNode = null;
  18029. /**
  18030. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18031. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18032. * and define the sheen roughness with a node instead.
  18033. *
  18034. * If you don't want to overwrite the sheen roughness but modify the existing
  18035. * value instead, use {@link materialSheenRoughness}.
  18036. *
  18037. * @type {?Node<float>}
  18038. * @default null
  18039. */
  18040. this.sheenRoughnessNode = null;
  18041. /**
  18042. * The iridescence of physical materials is by default inferred from the `iridescence`
  18043. * property. This node property allows to overwrite the default
  18044. * and define the iridescence with a node instead.
  18045. *
  18046. * If you don't want to overwrite the iridescence but modify the existing
  18047. * value instead, use {@link materialIridescence}.
  18048. *
  18049. * @type {?Node<float>}
  18050. * @default null
  18051. */
  18052. this.iridescenceNode = null;
  18053. /**
  18054. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18055. * property. This node property allows to overwrite the default
  18056. * and define the iridescence IOR with a node instead.
  18057. *
  18058. * If you don't want to overwrite the iridescence IOR but modify the existing
  18059. * value instead, use {@link materialIridescenceIOR}.
  18060. *
  18061. * @type {?Node<float>}
  18062. * @default null
  18063. */
  18064. this.iridescenceIORNode = null;
  18065. /**
  18066. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18067. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18068. * and define the iridescence thickness with a node instead.
  18069. *
  18070. * If you don't want to overwrite the iridescence thickness but modify the existing
  18071. * value instead, use {@link materialIridescenceThickness}.
  18072. *
  18073. * @type {?Node<float>}
  18074. * @default null
  18075. */
  18076. this.iridescenceThicknessNode = null;
  18077. /**
  18078. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18079. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18080. * and define the specular intensity with a node instead.
  18081. *
  18082. * If you don't want to overwrite the specular intensity but modify the existing
  18083. * value instead, use {@link materialSpecularIntensity}.
  18084. *
  18085. * @type {?Node<float>}
  18086. * @default null
  18087. */
  18088. this.specularIntensityNode = null;
  18089. /**
  18090. * The specular color of physical materials is by default inferred from the `specularColor`
  18091. * and `specularColorMap` properties. This node property allows to overwrite the default
  18092. * and define the specular color with a node instead.
  18093. *
  18094. * If you don't want to overwrite the specular color but modify the existing
  18095. * value instead, use {@link materialSpecularColor}.
  18096. *
  18097. * @type {?Node<vec3>}
  18098. * @default null
  18099. */
  18100. this.specularColorNode = null;
  18101. /**
  18102. * The ior of physical materials is by default inferred from the `ior`
  18103. * property. This node property allows to overwrite the default
  18104. * and define the ior with a node instead.
  18105. *
  18106. * If you don't want to overwrite the ior but modify the existing
  18107. * value instead, use {@link materialIOR}.
  18108. *
  18109. * @type {?Node<float>}
  18110. * @default null
  18111. */
  18112. this.iorNode = null;
  18113. /**
  18114. * The transmission of physical materials is by default inferred from the `transmission` and
  18115. * `transmissionMap` properties. This node property allows to overwrite the default
  18116. * and define the transmission with a node instead.
  18117. *
  18118. * If you don't want to overwrite the transmission but modify the existing
  18119. * value instead, use {@link materialTransmission}.
  18120. *
  18121. * @type {?Node<float>}
  18122. * @default null
  18123. */
  18124. this.transmissionNode = null;
  18125. /**
  18126. * The thickness of physical materials is by default inferred from the `thickness` and
  18127. * `thicknessMap` properties. This node property allows to overwrite the default
  18128. * and define the thickness with a node instead.
  18129. *
  18130. * If you don't want to overwrite the thickness but modify the existing
  18131. * value instead, use {@link materialThickness}.
  18132. *
  18133. * @type {?Node<float>}
  18134. * @default null
  18135. */
  18136. this.thicknessNode = null;
  18137. /**
  18138. * The attenuation distance of physical materials is by default inferred from the
  18139. * `attenuationDistance` property. This node property allows to overwrite the default
  18140. * and define the attenuation distance with a node instead.
  18141. *
  18142. * If you don't want to overwrite the attenuation distance but modify the existing
  18143. * value instead, use {@link materialAttenuationDistance}.
  18144. *
  18145. * @type {?Node<float>}
  18146. * @default null
  18147. */
  18148. this.attenuationDistanceNode = null;
  18149. /**
  18150. * The attenuation color of physical materials is by default inferred from the
  18151. * `attenuationColor` property. This node property allows to overwrite the default
  18152. * and define the attenuation color with a node instead.
  18153. *
  18154. * If you don't want to overwrite the attenuation color but modify the existing
  18155. * value instead, use {@link materialAttenuationColor}.
  18156. *
  18157. * @type {?Node<vec3>}
  18158. * @default null
  18159. */
  18160. this.attenuationColorNode = null;
  18161. /**
  18162. * The dispersion of physical materials is by default inferred from the
  18163. * `dispersion` property. This node property allows to overwrite the default
  18164. * and define the dispersion with a node instead.
  18165. *
  18166. * If you don't want to overwrite the dispersion but modify the existing
  18167. * value instead, use {@link materialDispersion}.
  18168. *
  18169. * @type {?Node<float>}
  18170. * @default null
  18171. */
  18172. this.dispersionNode = null;
  18173. /**
  18174. * The anisotropy of physical materials is by default inferred from the
  18175. * `anisotropy` property. This node property allows to overwrite the default
  18176. * and define the anisotropy with a node instead.
  18177. *
  18178. * If you don't want to overwrite the anisotropy but modify the existing
  18179. * value instead, use {@link materialAnisotropy}.
  18180. *
  18181. * @type {?Node<float>}
  18182. * @default null
  18183. */
  18184. this.anisotropyNode = null;
  18185. this.setDefaultValues( _defaultValues$5 );
  18186. this.setValues( parameters );
  18187. }
  18188. /**
  18189. * Whether the lighting model should use clearcoat or not.
  18190. *
  18191. * @type {boolean}
  18192. * @default true
  18193. */
  18194. get useClearcoat() {
  18195. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18196. }
  18197. /**
  18198. * Whether the lighting model should use iridescence or not.
  18199. *
  18200. * @type {boolean}
  18201. * @default true
  18202. */
  18203. get useIridescence() {
  18204. return this.iridescence > 0 || this.iridescenceNode !== null;
  18205. }
  18206. /**
  18207. * Whether the lighting model should use sheen or not.
  18208. *
  18209. * @type {boolean}
  18210. * @default true
  18211. */
  18212. get useSheen() {
  18213. return this.sheen > 0 || this.sheenNode !== null;
  18214. }
  18215. /**
  18216. * Whether the lighting model should use anisotropy or not.
  18217. *
  18218. * @type {boolean}
  18219. * @default true
  18220. */
  18221. get useAnisotropy() {
  18222. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18223. }
  18224. /**
  18225. * Whether the lighting model should use transmission or not.
  18226. *
  18227. * @type {boolean}
  18228. * @default true
  18229. */
  18230. get useTransmission() {
  18231. return this.transmission > 0 || this.transmissionNode !== null;
  18232. }
  18233. /**
  18234. * Whether the lighting model should use dispersion or not.
  18235. *
  18236. * @type {boolean}
  18237. * @default true
  18238. */
  18239. get useDispersion() {
  18240. return this.dispersion > 0 || this.dispersionNode !== null;
  18241. }
  18242. /**
  18243. * Setups the specular related node variables.
  18244. */
  18245. setupSpecular() {
  18246. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18247. ior.assign( iorNode );
  18248. 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 ) );
  18249. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18250. }
  18251. /**
  18252. * Setups the lighting model.
  18253. *
  18254. * @return {PhysicalLightingModel} The lighting model.
  18255. */
  18256. setupLightingModel( /*builder*/ ) {
  18257. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18258. }
  18259. /**
  18260. * Setups the physical specific node variables.
  18261. *
  18262. * @param {NodeBuilder} builder - The current node builder.
  18263. */
  18264. setupVariants( builder ) {
  18265. super.setupVariants( builder );
  18266. // CLEARCOAT
  18267. if ( this.useClearcoat ) {
  18268. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18269. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18270. clearcoat.assign( clearcoatNode );
  18271. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18272. }
  18273. // SHEEN
  18274. if ( this.useSheen ) {
  18275. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18276. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18277. sheen.assign( sheenNode );
  18278. sheenRoughness.assign( sheenRoughnessNode );
  18279. }
  18280. // IRIDESCENCE
  18281. if ( this.useIridescence ) {
  18282. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18283. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18284. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18285. iridescence.assign( iridescenceNode );
  18286. iridescenceIOR.assign( iridescenceIORNode );
  18287. iridescenceThickness.assign( iridescenceThicknessNode );
  18288. }
  18289. // ANISOTROPY
  18290. if ( this.useAnisotropy ) {
  18291. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18292. anisotropy.assign( anisotropyV.length() );
  18293. If( anisotropy.equal( 0.0 ), () => {
  18294. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18295. } ).Else( () => {
  18296. anisotropyV.divAssign( vec2( anisotropy ) );
  18297. anisotropy.assign( anisotropy.saturate() );
  18298. } );
  18299. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18300. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18301. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18302. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18303. }
  18304. // TRANSMISSION
  18305. if ( this.useTransmission ) {
  18306. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  18307. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  18308. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  18309. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  18310. transmission.assign( transmissionNode );
  18311. thickness.assign( thicknessNode );
  18312. attenuationDistance.assign( attenuationDistanceNode );
  18313. attenuationColor.assign( attenuationColorNode );
  18314. if ( this.useDispersion ) {
  18315. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  18316. dispersion.assign( dispersionNode );
  18317. }
  18318. }
  18319. }
  18320. /**
  18321. * Setups the clearcoat normal node.
  18322. *
  18323. * @return {Node<vec3>} The clearcoat normal.
  18324. */
  18325. setupClearcoatNormal() {
  18326. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  18327. }
  18328. setup( builder ) {
  18329. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18330. super.setup( builder );
  18331. }
  18332. copy( source ) {
  18333. this.clearcoatNode = source.clearcoatNode;
  18334. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18335. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18336. this.sheenNode = source.sheenNode;
  18337. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18338. this.iridescenceNode = source.iridescenceNode;
  18339. this.iridescenceIORNode = source.iridescenceIORNode;
  18340. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18341. this.specularIntensityNode = source.specularIntensityNode;
  18342. this.specularColorNode = source.specularColorNode;
  18343. this.transmissionNode = source.transmissionNode;
  18344. this.thicknessNode = source.thicknessNode;
  18345. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18346. this.attenuationColorNode = source.attenuationColorNode;
  18347. this.dispersionNode = source.dispersionNode;
  18348. this.anisotropyNode = source.anisotropyNode;
  18349. return super.copy( source );
  18350. }
  18351. }
  18352. /**
  18353. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18354. *
  18355. * @augments PhysicalLightingModel
  18356. */
  18357. class SSSLightingModel extends PhysicalLightingModel {
  18358. /**
  18359. * Constructs a new physical lighting model.
  18360. *
  18361. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18362. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18363. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18364. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18365. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18366. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18367. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18368. */
  18369. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18370. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18371. /**
  18372. * Whether the lighting model should use SSS or not.
  18373. *
  18374. * @type {boolean}
  18375. * @default false
  18376. */
  18377. this.useSSS = sss;
  18378. }
  18379. /**
  18380. * Extends the default implementation with a SSS term.
  18381. *
  18382. * 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/}
  18383. *
  18384. * @param {Object} input - The input data.
  18385. * @param {NodeBuilder} builder - The current node builder.
  18386. */
  18387. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18388. if ( this.useSSS === true ) {
  18389. const material = builder.material;
  18390. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18391. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18392. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18393. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18394. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18395. }
  18396. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18397. }
  18398. }
  18399. /**
  18400. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18401. * that implements a Subsurface scattering (SSS) term.
  18402. *
  18403. * @augments MeshPhysicalNodeMaterial
  18404. */
  18405. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18406. static get type() {
  18407. return 'MeshSSSNodeMaterial';
  18408. }
  18409. /**
  18410. * Constructs a new mesh SSS node material.
  18411. *
  18412. * @param {Object} [parameters] - The configuration parameter.
  18413. */
  18414. constructor( parameters ) {
  18415. super( parameters );
  18416. /**
  18417. * Represents the thickness color.
  18418. *
  18419. * @type {?Node<vec3>}
  18420. * @default null
  18421. */
  18422. this.thicknessColorNode = null;
  18423. /**
  18424. * Represents the distortion factor.
  18425. *
  18426. * @type {?Node<float>}
  18427. */
  18428. this.thicknessDistortionNode = float( 0.1 );
  18429. /**
  18430. * Represents the thickness ambient factor.
  18431. *
  18432. * @type {?Node<float>}
  18433. */
  18434. this.thicknessAmbientNode = float( 0.0 );
  18435. /**
  18436. * Represents the thickness attenuation.
  18437. *
  18438. * @type {?Node<float>}
  18439. */
  18440. this.thicknessAttenuationNode = float( .1 );
  18441. /**
  18442. * Represents the thickness power.
  18443. *
  18444. * @type {?Node<float>}
  18445. */
  18446. this.thicknessPowerNode = float( 2.0 );
  18447. /**
  18448. * Represents the thickness scale.
  18449. *
  18450. * @type {?Node<float>}
  18451. */
  18452. this.thicknessScaleNode = float( 10.0 );
  18453. }
  18454. /**
  18455. * Whether the lighting model should use SSS or not.
  18456. *
  18457. * @type {boolean}
  18458. * @default true
  18459. */
  18460. get useSSS() {
  18461. return this.thicknessColorNode !== null;
  18462. }
  18463. /**
  18464. * Setups the lighting model.
  18465. *
  18466. * @return {SSSLightingModel} The lighting model.
  18467. */
  18468. setupLightingModel( /*builder*/ ) {
  18469. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18470. }
  18471. copy( source ) {
  18472. this.thicknessColorNode = source.thicknessColorNode;
  18473. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18474. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18475. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18476. this.thicknessPowerNode = source.thicknessPowerNode;
  18477. this.thicknessScaleNode = source.thicknessScaleNode;
  18478. return super.copy( source );
  18479. }
  18480. }
  18481. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18482. // dotNL will be from -1.0 to 1.0
  18483. const dotNL = normal.dot( lightDirection );
  18484. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18485. if ( builder.material.gradientMap ) {
  18486. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18487. return vec3( gradientMap.r );
  18488. } else {
  18489. const fw = coord.fwidth().mul( 0.5 );
  18490. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18491. }
  18492. } );
  18493. /**
  18494. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18495. *
  18496. * @augments LightingModel
  18497. */
  18498. class ToonLightingModel extends LightingModel {
  18499. /**
  18500. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18501. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18502. *
  18503. * @param {Object} lightData - The light data.
  18504. * @param {NodeBuilder} builder - The current node builder.
  18505. */
  18506. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18507. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18508. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18509. }
  18510. /**
  18511. * Implements the indirect lighting.
  18512. *
  18513. * @param {NodeBuilder} builder - The current node builder.
  18514. */
  18515. indirect( builder ) {
  18516. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18517. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18518. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18519. }
  18520. }
  18521. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18522. /**
  18523. * Node material version of {@link MeshToonMaterial}.
  18524. *
  18525. * @augments NodeMaterial
  18526. */
  18527. class MeshToonNodeMaterial extends NodeMaterial {
  18528. static get type() {
  18529. return 'MeshToonNodeMaterial';
  18530. }
  18531. /**
  18532. * Constructs a new mesh toon node material.
  18533. *
  18534. * @param {Object} [parameters] - The configuration parameter.
  18535. */
  18536. constructor( parameters ) {
  18537. super();
  18538. /**
  18539. * This flag can be used for type testing.
  18540. *
  18541. * @type {boolean}
  18542. * @readonly
  18543. * @default true
  18544. */
  18545. this.isMeshToonNodeMaterial = true;
  18546. /**
  18547. * Set to `true` because toon materials react on lights.
  18548. *
  18549. * @type {boolean}
  18550. * @default true
  18551. */
  18552. this.lights = true;
  18553. this.setDefaultValues( _defaultValues$4 );
  18554. this.setValues( parameters );
  18555. }
  18556. /**
  18557. * Setups the lighting model.
  18558. *
  18559. * @return {ToonLightingModel} The lighting model.
  18560. */
  18561. setupLightingModel( /*builder*/ ) {
  18562. return new ToonLightingModel();
  18563. }
  18564. }
  18565. /**
  18566. * TSL function for creating a matcap uv node.
  18567. *
  18568. * Can be used to compute texture coordinates for projecting a
  18569. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18570. *
  18571. * @tsl
  18572. * @function
  18573. * @returns {Node<vec2>} The matcap UV coordinates.
  18574. */
  18575. const matcapUV = /*@__PURE__*/ Fn( () => {
  18576. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18577. const y = positionViewDirection.cross( x );
  18578. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18579. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18580. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18581. /**
  18582. * Node material version of {@link MeshMatcapMaterial}.
  18583. *
  18584. * @augments NodeMaterial
  18585. */
  18586. class MeshMatcapNodeMaterial extends NodeMaterial {
  18587. static get type() {
  18588. return 'MeshMatcapNodeMaterial';
  18589. }
  18590. /**
  18591. * Constructs a new mesh normal node material.
  18592. *
  18593. * @param {Object} [parameters] - The configuration parameter.
  18594. */
  18595. constructor( parameters ) {
  18596. super();
  18597. /**
  18598. * This flag can be used for type testing.
  18599. *
  18600. * @type {boolean}
  18601. * @readonly
  18602. * @default true
  18603. */
  18604. this.isMeshMatcapNodeMaterial = true;
  18605. this.setDefaultValues( _defaultValues$3 );
  18606. this.setValues( parameters );
  18607. }
  18608. /**
  18609. * Setups the matcap specific node variables.
  18610. *
  18611. * @param {NodeBuilder} builder - The current node builder.
  18612. */
  18613. setupVariants( builder ) {
  18614. const uv = matcapUV;
  18615. let matcapColor;
  18616. if ( builder.material.matcap ) {
  18617. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18618. } else {
  18619. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18620. }
  18621. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18622. }
  18623. }
  18624. /**
  18625. * Applies a rotation to the given position node.
  18626. *
  18627. * @augments TempNode
  18628. */
  18629. class RotateNode extends TempNode {
  18630. static get type() {
  18631. return 'RotateNode';
  18632. }
  18633. /**
  18634. * Constructs a new rotate node.
  18635. *
  18636. * @param {Node} positionNode - The position node.
  18637. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18638. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18639. */
  18640. constructor( positionNode, rotationNode ) {
  18641. super();
  18642. /**
  18643. * The position node.
  18644. *
  18645. * @type {Node}
  18646. */
  18647. this.positionNode = positionNode;
  18648. /**
  18649. * Represents the rotation that is applied to the position node.
  18650. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18651. *
  18652. * @type {Node}
  18653. */
  18654. this.rotationNode = rotationNode;
  18655. }
  18656. /**
  18657. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18658. *
  18659. * @param {NodeBuilder} builder - The current node builder.
  18660. * @return {string} The node's type.
  18661. */
  18662. getNodeType( builder ) {
  18663. return this.positionNode.getNodeType( builder );
  18664. }
  18665. setup( builder ) {
  18666. const { rotationNode, positionNode } = this;
  18667. const nodeType = this.getNodeType( builder );
  18668. if ( nodeType === 'vec2' ) {
  18669. const cosAngle = rotationNode.cos();
  18670. const sinAngle = rotationNode.sin();
  18671. const rotationMatrix = mat2(
  18672. cosAngle, sinAngle,
  18673. sinAngle.negate(), cosAngle
  18674. );
  18675. return rotationMatrix.mul( positionNode );
  18676. } else {
  18677. const rotation = rotationNode;
  18678. 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 ) );
  18679. 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 ) );
  18680. 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 ) );
  18681. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  18682. }
  18683. }
  18684. }
  18685. /**
  18686. * TSL function for creating a rotate node.
  18687. *
  18688. * @tsl
  18689. * @function
  18690. * @param {Node} positionNode - The position node.
  18691. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18692. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18693. * @returns {RotateNode}
  18694. */
  18695. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  18696. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  18697. /**
  18698. * Node material version of {@link SpriteMaterial}.
  18699. *
  18700. * @augments NodeMaterial
  18701. */
  18702. class SpriteNodeMaterial extends NodeMaterial {
  18703. static get type() {
  18704. return 'SpriteNodeMaterial';
  18705. }
  18706. /**
  18707. * Constructs a new sprite node material.
  18708. *
  18709. * @param {Object} [parameters] - The configuration parameter.
  18710. */
  18711. constructor( parameters ) {
  18712. super();
  18713. /**
  18714. * This flag can be used for type testing.
  18715. *
  18716. * @type {boolean}
  18717. * @readonly
  18718. * @default true
  18719. */
  18720. this.isSpriteNodeMaterial = true;
  18721. this._useSizeAttenuation = true;
  18722. /**
  18723. * This property makes it possible to define the position of the sprite with a
  18724. * node. That can be useful when the material is used with instanced rendering
  18725. * and node data are defined with an instanced attribute node:
  18726. * ```js
  18727. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  18728. * material.positionNode = instancedBufferAttribute( positionAttribute );
  18729. * ```
  18730. * Another possibility is to compute the instanced data with a compute shader:
  18731. * ```js
  18732. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  18733. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18734. * ```
  18735. *
  18736. * @type {?Node<vec2>}
  18737. * @default null
  18738. */
  18739. this.positionNode = null;
  18740. /**
  18741. * The rotation of sprite materials is by default inferred from the `rotation`,
  18742. * property. This node property allows to overwrite the default and define
  18743. * the rotation with a node instead.
  18744. *
  18745. * If you don't want to overwrite the rotation but modify the existing
  18746. * value instead, use {@link materialRotation}.
  18747. *
  18748. * @type {?Node<float>}
  18749. * @default null
  18750. */
  18751. this.rotationNode = null;
  18752. /**
  18753. * This node property provides an additional way to scale sprites next to
  18754. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  18755. * is multiplied with the scale value of this node in the vertex shader.
  18756. *
  18757. * @type {?Node<vec2>}
  18758. * @default null
  18759. */
  18760. this.scaleNode = null;
  18761. /**
  18762. * In Sprites, the transparent property is enabled by default.
  18763. *
  18764. * @type {boolean}
  18765. * @default true
  18766. */
  18767. this.transparent = true;
  18768. this.setDefaultValues( _defaultValues$2 );
  18769. this.setValues( parameters );
  18770. }
  18771. /**
  18772. * Setups the position node in view space. This method implements
  18773. * the sprite specific vertex shader.
  18774. *
  18775. * @param {NodeBuilder} builder - The current node builder.
  18776. * @return {Node<vec3>} The position in view space.
  18777. */
  18778. setupPositionView( builder ) {
  18779. const { object, camera } = builder;
  18780. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  18781. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  18782. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  18783. if ( scaleNode !== null ) {
  18784. scale = scale.mul( vec2( scaleNode ) );
  18785. }
  18786. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  18787. scale = scale.mul( mvPosition.z.negate() );
  18788. }
  18789. let alignedPosition = positionGeometry.xy;
  18790. if ( object.center && object.center.isVector2 === true ) {
  18791. const center = reference$1( 'center', 'vec2', object );
  18792. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  18793. }
  18794. alignedPosition = alignedPosition.mul( scale );
  18795. const rotation = float( rotationNode || materialRotation );
  18796. const rotatedPosition = rotate( alignedPosition, rotation );
  18797. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  18798. }
  18799. copy( source ) {
  18800. this.positionNode = source.positionNode;
  18801. this.rotationNode = source.rotationNode;
  18802. this.scaleNode = source.scaleNode;
  18803. return super.copy( source );
  18804. }
  18805. /**
  18806. * Whether to use size attenuation or not.
  18807. *
  18808. * @type {boolean}
  18809. * @default true
  18810. */
  18811. get sizeAttenuation() {
  18812. return this._useSizeAttenuation;
  18813. }
  18814. set sizeAttenuation( value ) {
  18815. if ( this._useSizeAttenuation !== value ) {
  18816. this._useSizeAttenuation = value;
  18817. this.needsUpdate = true;
  18818. }
  18819. }
  18820. }
  18821. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  18822. const _size$4 = /*@__PURE__*/ new Vector2();
  18823. /**
  18824. * Node material version of {@link PointsMaterial}.
  18825. *
  18826. * This material can be used in two ways:
  18827. *
  18828. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  18829. * with a pixel size of `1`, it's not possible to define a size.
  18830. *
  18831. * ```js
  18832. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  18833. * ```
  18834. *
  18835. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  18836. * see {@link PointsNodeMaterial#sizeNode}.
  18837. *
  18838. * ```js
  18839. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  18840. * ```
  18841. *
  18842. * @augments SpriteNodeMaterial
  18843. */
  18844. class PointsNodeMaterial extends SpriteNodeMaterial {
  18845. static get type() {
  18846. return 'PointsNodeMaterial';
  18847. }
  18848. /**
  18849. * Constructs a new points node material.
  18850. *
  18851. * @param {Object} [parameters] - The configuration parameter.
  18852. */
  18853. constructor( parameters ) {
  18854. super();
  18855. /**
  18856. * This node property provides an additional way to set the point size.
  18857. *
  18858. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  18859. * this node has no effect when the material is used with {@link Points} and a WebGPU
  18860. * backend. If an application wants to render points with a size larger than 1 pixel,
  18861. * the material should be used with {@link Sprite} and instancing.
  18862. *
  18863. * @type {?Node<vec2>}
  18864. * @default null
  18865. */
  18866. this.sizeNode = null;
  18867. /**
  18868. * This flag can be used for type testing.
  18869. *
  18870. * @type {boolean}
  18871. * @readonly
  18872. * @default true
  18873. */
  18874. this.isPointsNodeMaterial = true;
  18875. this.setDefaultValues( _defaultValues$1 );
  18876. this.setValues( parameters );
  18877. }
  18878. setupPositionView() {
  18879. const { positionNode } = this;
  18880. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  18881. }
  18882. setupVertexSprite( builder ) {
  18883. const { material, camera } = builder;
  18884. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  18885. let mvp = super.setupVertex( builder );
  18886. // skip further processing if the material is not a node material
  18887. if ( material.isNodeMaterial !== true ) {
  18888. return mvp;
  18889. }
  18890. // point size
  18891. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  18892. pointSize = pointSize.mul( screenDPR );
  18893. // size attenuation
  18894. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  18895. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  18896. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  18897. }
  18898. // scale
  18899. if ( scaleNode && scaleNode.isNode ) {
  18900. pointSize = pointSize.mul( vec2( scaleNode ) );
  18901. }
  18902. // compute offset
  18903. let offset = positionGeometry.xy;
  18904. // apply rotation
  18905. if ( rotationNode && rotationNode.isNode ) {
  18906. const rotation = float( rotationNode );
  18907. offset = rotate( offset, rotation );
  18908. }
  18909. // account for point size
  18910. offset = offset.mul( pointSize );
  18911. // scale by viewport size
  18912. offset = offset.div( viewportSize.div( 2 ) );
  18913. // compensate for the perspective divide
  18914. offset = offset.mul( mvp.w );
  18915. // add offset
  18916. mvp = mvp.add( vec4( offset, 0, 0 ) );
  18917. return mvp;
  18918. }
  18919. setupVertex( builder ) {
  18920. if ( builder.object.isPoints ) {
  18921. return super.setupVertex( builder );
  18922. } else {
  18923. return this.setupVertexSprite( builder );
  18924. }
  18925. }
  18926. /**
  18927. * Whether alpha to coverage should be used or not.
  18928. *
  18929. * @type {boolean}
  18930. * @default true
  18931. */
  18932. get alphaToCoverage() {
  18933. return this._useAlphaToCoverage;
  18934. }
  18935. set alphaToCoverage( value ) {
  18936. if ( this._useAlphaToCoverage !== value ) {
  18937. this._useAlphaToCoverage = value;
  18938. this.needsUpdate = true;
  18939. }
  18940. }
  18941. }
  18942. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  18943. const size = renderer.getSize( _size$4 ); // logical units
  18944. this.value = 0.5 * size.y;
  18945. } );
  18946. /**
  18947. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  18948. *
  18949. * @augments LightingModel
  18950. */
  18951. class ShadowMaskModel extends LightingModel {
  18952. /**
  18953. * Constructs a new shadow mask model.
  18954. */
  18955. constructor() {
  18956. super();
  18957. /**
  18958. * The shadow mask node.
  18959. *
  18960. * @type {Node}
  18961. */
  18962. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  18963. }
  18964. /**
  18965. * Only used to save the shadow mask.
  18966. *
  18967. * @param {Object} input - The input data.
  18968. */
  18969. direct( { lightNode } ) {
  18970. if ( lightNode.shadowNode !== null ) {
  18971. this.shadowNode.mulAssign( lightNode.shadowNode );
  18972. }
  18973. }
  18974. /**
  18975. * Uses the shadow mask to produce the final color.
  18976. *
  18977. * @param {NodeBuilder} builder - The current node builder.
  18978. */
  18979. finish( { context } ) {
  18980. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  18981. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  18982. }
  18983. }
  18984. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  18985. /**
  18986. * Node material version of {@link ShadowMaterial}.
  18987. *
  18988. * @augments NodeMaterial
  18989. */
  18990. class ShadowNodeMaterial extends NodeMaterial {
  18991. static get type() {
  18992. return 'ShadowNodeMaterial';
  18993. }
  18994. /**
  18995. * Constructs a new shadow node material.
  18996. *
  18997. * @param {Object} [parameters] - The configuration parameter.
  18998. */
  18999. constructor( parameters ) {
  19000. super();
  19001. /**
  19002. * This flag can be used for type testing.
  19003. *
  19004. * @type {boolean}
  19005. * @readonly
  19006. * @default true
  19007. */
  19008. this.isShadowNodeMaterial = true;
  19009. /**
  19010. * Set to `true` because so it's possible to implement
  19011. * the shadow mask effect.
  19012. *
  19013. * @type {boolean}
  19014. * @default true
  19015. */
  19016. this.lights = true;
  19017. /**
  19018. * Overwritten since shadow materials are transparent
  19019. * by default.
  19020. *
  19021. * @type {boolean}
  19022. * @default true
  19023. */
  19024. this.transparent = true;
  19025. this.setDefaultValues( _defaultValues );
  19026. this.setValues( parameters );
  19027. }
  19028. /**
  19029. * Setups the lighting model.
  19030. *
  19031. * @return {ShadowMaskModel} The lighting model.
  19032. */
  19033. setupLightingModel( /*builder*/ ) {
  19034. return new ShadowMaskModel();
  19035. }
  19036. }
  19037. const scatteringDensity = property( 'vec3' );
  19038. const linearDepthRay = property( 'vec3' );
  19039. const outgoingRayLight = property( 'vec3' );
  19040. /**
  19041. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19042. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19043. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19044. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19045. *
  19046. * @augments LightingModel
  19047. */
  19048. class VolumetricLightingModel extends LightingModel {
  19049. constructor() {
  19050. super();
  19051. }
  19052. start( builder ) {
  19053. const { material, context } = builder;
  19054. const startPos = property( 'vec3' );
  19055. const endPos = property( 'vec3' );
  19056. // This approach dynamically changes the direction of the ray,
  19057. // 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.
  19058. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19059. startPos.assign( cameraPosition );
  19060. endPos.assign( positionWorld );
  19061. } ).Else( () => {
  19062. startPos.assign( positionWorld );
  19063. endPos.assign( cameraPosition );
  19064. } );
  19065. //
  19066. const viewVector = endPos.sub( startPos );
  19067. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19068. const stepSize = viewVector.length().div( steps ).toVar();
  19069. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19070. const distTravelled = float( 0.0 ).toVar();
  19071. const transmittance = vec3( 1 ).toVar();
  19072. if ( material.offsetNode ) {
  19073. // reduce banding
  19074. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19075. }
  19076. Loop( steps, () => {
  19077. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19078. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19079. if ( material.depthNode !== null ) {
  19080. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19081. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19082. }
  19083. context.positionWorld = positionRay;
  19084. context.shadowPositionWorld = positionRay;
  19085. context.positionView = positionViewRay;
  19086. scatteringDensity.assign( 0 );
  19087. let scatteringNode;
  19088. if ( material.scatteringNode ) {
  19089. scatteringNode = material.scatteringNode( {
  19090. positionRay
  19091. } );
  19092. }
  19093. super.start( builder );
  19094. if ( scatteringNode ) {
  19095. scatteringDensity.mulAssign( scatteringNode );
  19096. }
  19097. // beer's law
  19098. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19099. transmittance.mulAssign( falloff );
  19100. // move along the ray
  19101. distTravelled.addAssign( stepSize );
  19102. } );
  19103. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19104. }
  19105. scatteringLight( lightColor, builder ) {
  19106. const sceneDepthNode = builder.context.sceneDepthNode;
  19107. if ( sceneDepthNode ) {
  19108. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19109. scatteringDensity.addAssign( lightColor );
  19110. } );
  19111. } else {
  19112. scatteringDensity.addAssign( lightColor );
  19113. }
  19114. }
  19115. direct( { lightNode, lightColor }, builder ) {
  19116. // Ignore lights with infinite distance
  19117. if ( lightNode.light.distance === undefined ) return;
  19118. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19119. const directLight = lightColor.xyz.toVar();
  19120. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19121. this.scatteringLight( directLight, builder );
  19122. }
  19123. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19124. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19125. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19126. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19127. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19128. const P = builder.context.positionView;
  19129. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19130. this.scatteringLight( directLight, builder );
  19131. }
  19132. finish( builder ) {
  19133. builder.context.outgoingLight.assign( outgoingRayLight );
  19134. }
  19135. }
  19136. /**
  19137. * Volume node material.
  19138. *
  19139. * @augments NodeMaterial
  19140. */
  19141. class VolumeNodeMaterial extends NodeMaterial {
  19142. static get type() {
  19143. return 'VolumeNodeMaterial';
  19144. }
  19145. /**
  19146. * Constructs a new volume node material.
  19147. *
  19148. * @param {Object} [parameters] - The configuration parameter.
  19149. */
  19150. constructor( parameters ) {
  19151. super();
  19152. /**
  19153. * This flag can be used for type testing.
  19154. *
  19155. * @type {boolean}
  19156. * @readonly
  19157. * @default true
  19158. */
  19159. this.isVolumeNodeMaterial = true;
  19160. /**
  19161. * Number of steps used for raymarching.
  19162. *
  19163. * @type {number}
  19164. * @default 25
  19165. */
  19166. this.steps = 25;
  19167. /**
  19168. * Offsets the distance a ray has been traveled through a volume.
  19169. * Can be used to implement dithering to reduce banding.
  19170. *
  19171. * @type {Node<float>}
  19172. * @default null
  19173. */
  19174. this.offsetNode = null;
  19175. /**
  19176. * Node used for scattering calculations.
  19177. *
  19178. * @type {Function|FunctionNode<vec4>}
  19179. * @default null
  19180. */
  19181. this.scatteringNode = null;
  19182. this.lights = true;
  19183. this.transparent = true;
  19184. this.side = BackSide;
  19185. this.depthTest = false;
  19186. this.depthWrite = false;
  19187. this.setValues( parameters );
  19188. }
  19189. setupLightingModel() {
  19190. return new VolumetricLightingModel();
  19191. }
  19192. }
  19193. /**
  19194. * This module manages the internal animation loop of the renderer.
  19195. *
  19196. * @private
  19197. */
  19198. class Animation {
  19199. /**
  19200. * Constructs a new animation loop management component.
  19201. *
  19202. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19203. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19204. */
  19205. constructor( nodes, info ) {
  19206. /**
  19207. * Renderer component for managing nodes related logic.
  19208. *
  19209. * @type {Nodes}
  19210. */
  19211. this.nodes = nodes;
  19212. /**
  19213. * Renderer component for managing metrics and monitoring data.
  19214. *
  19215. * @type {Info}
  19216. */
  19217. this.info = info;
  19218. /**
  19219. * A reference to the context from `requestAnimationFrame()` can
  19220. * be called (usually `window`).
  19221. *
  19222. * @type {?(Window|XRSession)}
  19223. */
  19224. this._context = typeof self !== 'undefined' ? self : null;
  19225. /**
  19226. * The user-defined animation loop.
  19227. *
  19228. * @type {?Function}
  19229. * @default null
  19230. */
  19231. this._animationLoop = null;
  19232. /**
  19233. * The requestId which is returned from the `requestAnimationFrame()` call.
  19234. * Can be used to cancel the stop the animation loop.
  19235. *
  19236. * @type {?number}
  19237. * @default null
  19238. */
  19239. this._requestId = null;
  19240. }
  19241. /**
  19242. * Starts the internal animation loop.
  19243. */
  19244. start() {
  19245. const update = ( time, xrFrame ) => {
  19246. this._requestId = this._context.requestAnimationFrame( update );
  19247. if ( this.info.autoReset === true ) this.info.reset();
  19248. this.nodes.nodeFrame.update();
  19249. this.info.frame = this.nodes.nodeFrame.frameId;
  19250. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19251. };
  19252. update();
  19253. }
  19254. /**
  19255. * Stops the internal animation loop.
  19256. */
  19257. stop() {
  19258. this._context.cancelAnimationFrame( this._requestId );
  19259. this._requestId = null;
  19260. }
  19261. /**
  19262. * Returns the user-level animation loop.
  19263. *
  19264. * @return {?Function} The animation loop.
  19265. */
  19266. getAnimationLoop() {
  19267. return this._animationLoop;
  19268. }
  19269. /**
  19270. * Defines the user-level animation loop.
  19271. *
  19272. * @param {?Function} callback - The animation loop.
  19273. */
  19274. setAnimationLoop( callback ) {
  19275. this._animationLoop = callback;
  19276. }
  19277. /**
  19278. * Returns the animation context.
  19279. *
  19280. * @return {Window|XRSession} The animation context.
  19281. */
  19282. getContext() {
  19283. return this._context;
  19284. }
  19285. /**
  19286. * Defines the context in which `requestAnimationFrame()` is executed.
  19287. *
  19288. * @param {Window|XRSession} context - The context to set.
  19289. */
  19290. setContext( context ) {
  19291. this._context = context;
  19292. }
  19293. /**
  19294. * Frees all internal resources and stops the animation loop.
  19295. */
  19296. dispose() {
  19297. this.stop();
  19298. }
  19299. }
  19300. /**
  19301. * Data structure for the renderer. It allows defining values
  19302. * with chained, hierarchical keys. Keys are meant to be
  19303. * objects since the module internally works with Weak Maps
  19304. * for performance reasons.
  19305. *
  19306. * @private
  19307. */
  19308. class ChainMap {
  19309. /**
  19310. * Constructs a new Chain Map.
  19311. */
  19312. constructor() {
  19313. /**
  19314. * The root Weak Map.
  19315. *
  19316. * @type {WeakMap<Object, WeakMap>}
  19317. */
  19318. this.weakMap = new WeakMap();
  19319. }
  19320. /**
  19321. * Returns the value for the given array of keys.
  19322. *
  19323. * @param {Array<Object>} keys - List of keys.
  19324. * @return {any} The value. Returns `undefined` if no value was found.
  19325. */
  19326. get( keys ) {
  19327. let map = this.weakMap;
  19328. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19329. map = map.get( keys[ i ] );
  19330. if ( map === undefined ) return undefined;
  19331. }
  19332. return map.get( keys[ keys.length - 1 ] );
  19333. }
  19334. /**
  19335. * Sets the value for the given keys.
  19336. *
  19337. * @param {Array<Object>} keys - List of keys.
  19338. * @param {any} value - The value to set.
  19339. * @return {ChainMap} A reference to this Chain Map.
  19340. */
  19341. set( keys, value ) {
  19342. let map = this.weakMap;
  19343. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19344. const key = keys[ i ];
  19345. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  19346. map = map.get( key );
  19347. }
  19348. map.set( keys[ keys.length - 1 ], value );
  19349. return this;
  19350. }
  19351. /**
  19352. * Deletes a value for the given keys.
  19353. *
  19354. * @param {Array<Object>} keys - The keys.
  19355. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19356. */
  19357. delete( keys ) {
  19358. let map = this.weakMap;
  19359. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19360. map = map.get( keys[ i ] );
  19361. if ( map === undefined ) return false;
  19362. }
  19363. return map.delete( keys[ keys.length - 1 ] );
  19364. }
  19365. }
  19366. let _id$9 = 0;
  19367. function getKeys( obj ) {
  19368. const keys = Object.keys( obj );
  19369. let proto = Object.getPrototypeOf( obj );
  19370. while ( proto ) {
  19371. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19372. for ( const key in descriptors ) {
  19373. if ( descriptors[ key ] !== undefined ) {
  19374. const descriptor = descriptors[ key ];
  19375. if ( descriptor && typeof descriptor.get === 'function' ) {
  19376. keys.push( key );
  19377. }
  19378. }
  19379. }
  19380. proto = Object.getPrototypeOf( proto );
  19381. }
  19382. return keys;
  19383. }
  19384. /**
  19385. * A render object is the renderer's representation of single entity that gets drawn
  19386. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19387. * scene since render objects also depend from the used material, the current render context
  19388. * and the current scene's lighting.
  19389. *
  19390. * In general, the basic process of the renderer is:
  19391. *
  19392. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19393. * - Process the render lists by calling one or more render commands for each render item.
  19394. * - For each render command, request a render object and perform the draw.
  19395. *
  19396. * The module provides an interface to get data required for the draw command like the actual
  19397. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19398. * creating render objects should only be done when necessary.
  19399. *
  19400. * @private
  19401. */
  19402. class RenderObject {
  19403. /**
  19404. * Constructs a new render object.
  19405. *
  19406. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19407. * @param {Geometries} geometries - Renderer component for managing geometries.
  19408. * @param {Renderer} renderer - The renderer.
  19409. * @param {Object3D} object - The 3D object.
  19410. * @param {Material} material - The 3D object's material.
  19411. * @param {Scene} scene - The scene the 3D object belongs to.
  19412. * @param {Camera} camera - The camera the object should be rendered with.
  19413. * @param {LightsNode} lightsNode - The lights node.
  19414. * @param {RenderContext} renderContext - The render context.
  19415. * @param {ClippingContext} clippingContext - The clipping context.
  19416. */
  19417. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19418. this.id = _id$9 ++;
  19419. /**
  19420. * Renderer component for managing nodes related logic.
  19421. *
  19422. * @type {Nodes}
  19423. * @private
  19424. */
  19425. this._nodes = nodes;
  19426. /**
  19427. * Renderer component for managing geometries.
  19428. *
  19429. * @type {Geometries}
  19430. * @private
  19431. */
  19432. this._geometries = geometries;
  19433. /**
  19434. * The renderer.
  19435. *
  19436. * @type {Renderer}
  19437. */
  19438. this.renderer = renderer;
  19439. /**
  19440. * The 3D object.
  19441. *
  19442. * @type {Object3D}
  19443. */
  19444. this.object = object;
  19445. /**
  19446. * The 3D object's material.
  19447. *
  19448. * @type {Material}
  19449. */
  19450. this.material = material;
  19451. /**
  19452. * The scene the 3D object belongs to.
  19453. *
  19454. * @type {Scene}
  19455. */
  19456. this.scene = scene;
  19457. /**
  19458. * The camera the 3D object should be rendered with.
  19459. *
  19460. * @type {Camera}
  19461. */
  19462. this.camera = camera;
  19463. /**
  19464. * The lights node.
  19465. *
  19466. * @type {LightsNode}
  19467. */
  19468. this.lightsNode = lightsNode;
  19469. /**
  19470. * The render context.
  19471. *
  19472. * @type {RenderContext}
  19473. */
  19474. this.context = renderContext;
  19475. /**
  19476. * The 3D object's geometry.
  19477. *
  19478. * @type {BufferGeometry}
  19479. */
  19480. this.geometry = object.geometry;
  19481. /**
  19482. * The render object's version.
  19483. *
  19484. * @type {number}
  19485. */
  19486. this.version = material.version;
  19487. /**
  19488. * The draw range of the geometry.
  19489. *
  19490. * @type {?Object}
  19491. * @default null
  19492. */
  19493. this.drawRange = null;
  19494. /**
  19495. * An array holding the buffer attributes
  19496. * of the render object. This entails attribute
  19497. * definitions on geometry and node level.
  19498. *
  19499. * @type {?Array<BufferAttribute>}
  19500. * @default null
  19501. */
  19502. this.attributes = null;
  19503. /**
  19504. * An object holding the version of the
  19505. * attributes. The keys are the attribute names
  19506. * and the values are the attribute versions.
  19507. *
  19508. * @type {?Object<string, number>}
  19509. * @default null
  19510. */
  19511. this.attributesId = null;
  19512. /**
  19513. * A reference to a render pipeline the render
  19514. * object is processed with.
  19515. *
  19516. * @type {RenderPipeline}
  19517. * @default null
  19518. */
  19519. this.pipeline = null;
  19520. /**
  19521. * Only relevant for objects using
  19522. * multiple materials. This represents a group entry
  19523. * from the respective `BufferGeometry`.
  19524. *
  19525. * @type {?{start: number, count: number}}
  19526. * @default null
  19527. */
  19528. this.group = null;
  19529. /**
  19530. * An array holding the vertex buffers which can
  19531. * be buffer attributes but also interleaved buffers.
  19532. *
  19533. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19534. * @default null
  19535. */
  19536. this.vertexBuffers = null;
  19537. /**
  19538. * The parameters for the draw command.
  19539. *
  19540. * @type {?Object}
  19541. * @default null
  19542. */
  19543. this.drawParams = null;
  19544. /**
  19545. * If this render object is used inside a render bundle,
  19546. * this property points to the respective bundle group.
  19547. *
  19548. * @type {?BundleGroup}
  19549. * @default null
  19550. */
  19551. this.bundle = null;
  19552. /**
  19553. * The clipping context.
  19554. *
  19555. * @type {ClippingContext}
  19556. */
  19557. this.clippingContext = clippingContext;
  19558. /**
  19559. * The clipping context's cache key.
  19560. *
  19561. * @type {string}
  19562. */
  19563. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19564. /**
  19565. * The initial node cache key.
  19566. *
  19567. * @type {number}
  19568. */
  19569. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19570. /**
  19571. * The initial cache key.
  19572. *
  19573. * @type {number}
  19574. */
  19575. this.initialCacheKey = this.getCacheKey();
  19576. /**
  19577. * The node builder state.
  19578. *
  19579. * @type {?NodeBuilderState}
  19580. * @private
  19581. * @default null
  19582. */
  19583. this._nodeBuilderState = null;
  19584. /**
  19585. * An array of bindings.
  19586. *
  19587. * @type {?Array<BindGroup>}
  19588. * @private
  19589. * @default null
  19590. */
  19591. this._bindings = null;
  19592. /**
  19593. * Reference to the node material observer.
  19594. *
  19595. * @type {?NodeMaterialObserver}
  19596. * @private
  19597. * @default null
  19598. */
  19599. this._monitor = null;
  19600. /**
  19601. * An event listener which is defined by `RenderObjects`. It performs
  19602. * clean up tasks when `dispose()` on this render object.
  19603. *
  19604. * @method
  19605. */
  19606. this.onDispose = null;
  19607. /**
  19608. * This flag can be used for type testing.
  19609. *
  19610. * @type {boolean}
  19611. * @readonly
  19612. * @default true
  19613. */
  19614. this.isRenderObject = true;
  19615. /**
  19616. * An event listener which is executed when `dispose()` is called on
  19617. * the material of this render object.
  19618. *
  19619. * @method
  19620. */
  19621. this.onMaterialDispose = () => {
  19622. this.dispose();
  19623. };
  19624. /**
  19625. * An event listener which is executed when `dispose()` is called on
  19626. * the geometry of this render object.
  19627. *
  19628. * @method
  19629. */
  19630. this.onGeometryDispose = () => {
  19631. // clear geometry cache attributes
  19632. this.attributes = null;
  19633. this.attributesId = null;
  19634. };
  19635. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19636. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19637. }
  19638. /**
  19639. * Updates the clipping context.
  19640. *
  19641. * @param {ClippingContext} context - The clipping context to set.
  19642. */
  19643. updateClipping( context ) {
  19644. this.clippingContext = context;
  19645. }
  19646. /**
  19647. * Whether the clipping requires an update or not.
  19648. *
  19649. * @type {boolean}
  19650. * @readonly
  19651. */
  19652. get clippingNeedsUpdate() {
  19653. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19654. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19655. return true;
  19656. }
  19657. /**
  19658. * The number of clipping planes defined in context of hardware clipping.
  19659. *
  19660. * @type {number}
  19661. * @readonly
  19662. */
  19663. get hardwareClippingPlanes() {
  19664. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19665. }
  19666. /**
  19667. * Returns the node builder state of this render object.
  19668. *
  19669. * @return {NodeBuilderState} The node builder state.
  19670. */
  19671. getNodeBuilderState() {
  19672. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  19673. }
  19674. /**
  19675. * Returns the node material observer of this render object.
  19676. *
  19677. * @return {NodeMaterialObserver} The node material observer.
  19678. */
  19679. getMonitor() {
  19680. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  19681. }
  19682. /**
  19683. * Returns an array of bind groups of this render object.
  19684. *
  19685. * @return {Array<BindGroup>} The bindings.
  19686. */
  19687. getBindings() {
  19688. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  19689. }
  19690. /**
  19691. * Returns a binding group by group name of this render object.
  19692. *
  19693. * @param {string} name - The name of the binding group.
  19694. * @return {?BindGroup} The bindings.
  19695. */
  19696. getBindingGroup( name ) {
  19697. for ( const bindingGroup of this.getBindings() ) {
  19698. if ( bindingGroup.name === name ) {
  19699. return bindingGroup;
  19700. }
  19701. }
  19702. }
  19703. /**
  19704. * Returns the index of the render object's geometry.
  19705. *
  19706. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19707. */
  19708. getIndex() {
  19709. return this._geometries.getIndex( this );
  19710. }
  19711. /**
  19712. * Returns the indirect buffer attribute.
  19713. *
  19714. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19715. */
  19716. getIndirect() {
  19717. return this._geometries.getIndirect( this );
  19718. }
  19719. /**
  19720. * Returns an array that acts as a key for identifying the render object in a chain map.
  19721. *
  19722. * @return {Array<Object>} An array with object references.
  19723. */
  19724. getChainArray() {
  19725. return [ this.object, this.material, this.context, this.lightsNode ];
  19726. }
  19727. /**
  19728. * This method is used when the geometry of a 3D object has been exchanged and the
  19729. * respective render object now requires an update.
  19730. *
  19731. * @param {BufferGeometry} geometry - The geometry to set.
  19732. */
  19733. setGeometry( geometry ) {
  19734. this.geometry = geometry;
  19735. this.attributes = null;
  19736. this.attributesId = null;
  19737. }
  19738. /**
  19739. * Returns the buffer attributes of the render object. The returned array holds
  19740. * attribute definitions on geometry and node level.
  19741. *
  19742. * @return {Array<BufferAttribute>} An array with buffer attributes.
  19743. */
  19744. getAttributes() {
  19745. if ( this.attributes !== null ) return this.attributes;
  19746. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  19747. const geometry = this.geometry;
  19748. const attributes = [];
  19749. const vertexBuffers = new Set();
  19750. const attributesId = {};
  19751. for ( const nodeAttribute of nodeAttributes ) {
  19752. let attribute;
  19753. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  19754. // node attribute
  19755. attribute = nodeAttribute.node.attribute;
  19756. } else {
  19757. // geometry attribute
  19758. attribute = geometry.getAttribute( nodeAttribute.name );
  19759. attributesId[ nodeAttribute.name ] = attribute.version;
  19760. }
  19761. if ( attribute === undefined ) continue;
  19762. attributes.push( attribute );
  19763. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  19764. vertexBuffers.add( bufferAttribute );
  19765. }
  19766. this.attributes = attributes;
  19767. this.attributesId = attributesId;
  19768. this.vertexBuffers = Array.from( vertexBuffers.values() );
  19769. return attributes;
  19770. }
  19771. /**
  19772. * Returns the vertex buffers of the render object.
  19773. *
  19774. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  19775. */
  19776. getVertexBuffers() {
  19777. if ( this.vertexBuffers === null ) this.getAttributes();
  19778. return this.vertexBuffers;
  19779. }
  19780. /**
  19781. * Returns the draw parameters for the render object.
  19782. *
  19783. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  19784. */
  19785. getDrawParameters() {
  19786. const { object, material, geometry, group, drawRange } = this;
  19787. const drawParams = this.drawParams || ( this.drawParams = {
  19788. vertexCount: 0,
  19789. firstVertex: 0,
  19790. instanceCount: 0,
  19791. firstInstance: 0
  19792. } );
  19793. const index = this.getIndex();
  19794. const hasIndex = ( index !== null );
  19795. let instanceCount = 1;
  19796. if ( geometry.isInstancedBufferGeometry === true ) {
  19797. instanceCount = geometry.instanceCount;
  19798. } else if ( object.count !== undefined ) {
  19799. instanceCount = Math.max( 0, object.count );
  19800. }
  19801. if ( instanceCount === 0 ) return null;
  19802. drawParams.instanceCount = instanceCount;
  19803. if ( object.isBatchedMesh === true ) return drawParams;
  19804. let rangeFactor = 1;
  19805. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  19806. rangeFactor = 2;
  19807. }
  19808. let firstVertex = drawRange.start * rangeFactor;
  19809. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  19810. if ( group !== null ) {
  19811. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  19812. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  19813. }
  19814. const position = geometry.attributes.position;
  19815. let itemCount = Infinity;
  19816. if ( hasIndex ) {
  19817. itemCount = index.count;
  19818. } else if ( position !== undefined && position !== null ) {
  19819. itemCount = position.count;
  19820. }
  19821. firstVertex = Math.max( firstVertex, 0 );
  19822. lastVertex = Math.min( lastVertex, itemCount );
  19823. const count = lastVertex - firstVertex;
  19824. if ( count < 0 || count === Infinity ) return null;
  19825. drawParams.vertexCount = count;
  19826. drawParams.firstVertex = firstVertex;
  19827. return drawParams;
  19828. }
  19829. /**
  19830. * Returns the render object's geometry cache key.
  19831. *
  19832. * The geometry cache key is part of the material cache key.
  19833. *
  19834. * @return {string} The geometry cache key.
  19835. */
  19836. getGeometryCacheKey() {
  19837. const { geometry } = this;
  19838. let cacheKey = '';
  19839. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  19840. const attribute = geometry.attributes[ name ];
  19841. cacheKey += name + ',';
  19842. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  19843. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  19844. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  19845. if ( attribute.normalized ) cacheKey += 'n,';
  19846. }
  19847. // structural equality isn't sufficient for morph targets since the
  19848. // data are maintained in textures. only if the targets are all equal
  19849. // the texture and thus the instance of `MorphNode` can be shared.
  19850. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  19851. const targets = geometry.morphAttributes[ name ];
  19852. cacheKey += 'morph-' + name + ',';
  19853. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  19854. const attribute = targets[ i ];
  19855. cacheKey += attribute.id + ',';
  19856. }
  19857. }
  19858. if ( geometry.index ) {
  19859. cacheKey += 'index,';
  19860. }
  19861. return cacheKey;
  19862. }
  19863. /**
  19864. * Returns the render object's material cache key.
  19865. *
  19866. * The material cache key is part of the render object cache key.
  19867. *
  19868. * @return {number} The material cache key.
  19869. */
  19870. getMaterialCacheKey() {
  19871. const { object, material, renderer } = this;
  19872. let cacheKey = material.customProgramCacheKey();
  19873. for ( const property of getKeys( material ) ) {
  19874. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  19875. const value = material[ property ];
  19876. let valueKey;
  19877. if ( value !== null ) {
  19878. // some material values require a formatting
  19879. const type = typeof value;
  19880. if ( type === 'number' ) {
  19881. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  19882. } else if ( type === 'object' ) {
  19883. valueKey = '{';
  19884. if ( value.isTexture ) {
  19885. valueKey += value.mapping;
  19886. // WebGPU must honor the sampler data because they are part of the bindings
  19887. if ( renderer.backend.isWebGPUBackend === true ) {
  19888. valueKey += value.magFilter;
  19889. valueKey += value.minFilter;
  19890. valueKey += value.wrapS;
  19891. valueKey += value.wrapT;
  19892. valueKey += value.wrapR;
  19893. }
  19894. }
  19895. valueKey += '}';
  19896. } else {
  19897. valueKey = String( value );
  19898. }
  19899. } else {
  19900. valueKey = String( value );
  19901. }
  19902. cacheKey += /*property + ':' +*/ valueKey + ',';
  19903. }
  19904. cacheKey += this.clippingContextCacheKey + ',';
  19905. if ( object.geometry ) {
  19906. cacheKey += this.getGeometryCacheKey();
  19907. }
  19908. if ( object.skeleton ) {
  19909. cacheKey += object.skeleton.bones.length + ',';
  19910. }
  19911. if ( object.isBatchedMesh ) {
  19912. cacheKey += object._matricesTexture.uuid + ',';
  19913. if ( object._colorsTexture !== null ) {
  19914. cacheKey += object._colorsTexture.uuid + ',';
  19915. }
  19916. }
  19917. if ( object.isInstancedMesh || object.count > 1 ) {
  19918. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  19919. cacheKey += object.uuid + ',';
  19920. }
  19921. cacheKey += object.receiveShadow + ',';
  19922. return hashString( cacheKey );
  19923. }
  19924. /**
  19925. * Whether the geometry requires an update or not.
  19926. *
  19927. * @type {boolean}
  19928. * @readonly
  19929. */
  19930. get needsGeometryUpdate() {
  19931. if ( this.geometry.id !== this.object.geometry.id ) return true;
  19932. if ( this.attributes !== null ) {
  19933. const attributesId = this.attributesId;
  19934. for ( const name in attributesId ) {
  19935. const attribute = this.geometry.getAttribute( name );
  19936. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  19937. return true;
  19938. }
  19939. }
  19940. }
  19941. return false;
  19942. }
  19943. /**
  19944. * Whether the render object requires an update or not.
  19945. *
  19946. * Note: There are two distinct places where render objects are checked for an update.
  19947. *
  19948. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  19949. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  19950. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  19951. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  19952. * a need for a refresh due to material, geometry or object related value changes.
  19953. *
  19954. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  19955. * that performs the 'needsUpdate' check.
  19956. *
  19957. * @type {boolean}
  19958. * @readonly
  19959. */
  19960. get needsUpdate() {
  19961. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  19962. }
  19963. /**
  19964. * Returns the dynamic cache key which represents a key that is computed per draw command.
  19965. *
  19966. * @return {number} The cache key.
  19967. */
  19968. getDynamicCacheKey() {
  19969. let cacheKey = 0;
  19970. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  19971. // the renderer is inside a shadow pass.
  19972. if ( this.material.isShadowPassMaterial !== true ) {
  19973. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  19974. }
  19975. if ( this.camera.isArrayCamera ) {
  19976. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  19977. }
  19978. if ( this.object.receiveShadow ) {
  19979. cacheKey = hash$1( cacheKey, 1 );
  19980. }
  19981. return cacheKey;
  19982. }
  19983. /**
  19984. * Returns the render object's cache key.
  19985. *
  19986. * @return {number} The cache key.
  19987. */
  19988. getCacheKey() {
  19989. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  19990. }
  19991. /**
  19992. * Frees internal resources.
  19993. */
  19994. dispose() {
  19995. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  19996. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  19997. this.onDispose();
  19998. }
  19999. }
  20000. const _chainKeys$5 = [];
  20001. /**
  20002. * This module manages the render objects of the renderer.
  20003. *
  20004. * @private
  20005. */
  20006. class RenderObjects {
  20007. /**
  20008. * Constructs a new render object management component.
  20009. *
  20010. * @param {Renderer} renderer - The renderer.
  20011. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20012. * @param {Geometries} geometries - Renderer component for managing geometries.
  20013. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20014. * @param {Bindings} bindings - Renderer component for managing bindings.
  20015. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20016. */
  20017. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  20018. /**
  20019. * The renderer.
  20020. *
  20021. * @type {Renderer}
  20022. */
  20023. this.renderer = renderer;
  20024. /**
  20025. * Renderer component for managing nodes related logic.
  20026. *
  20027. * @type {Nodes}
  20028. */
  20029. this.nodes = nodes;
  20030. /**
  20031. * Renderer component for managing geometries.
  20032. *
  20033. * @type {Geometries}
  20034. */
  20035. this.geometries = geometries;
  20036. /**
  20037. * Renderer component for managing pipelines.
  20038. *
  20039. * @type {Pipelines}
  20040. */
  20041. this.pipelines = pipelines;
  20042. /**
  20043. * Renderer component for managing bindings.
  20044. *
  20045. * @type {Bindings}
  20046. */
  20047. this.bindings = bindings;
  20048. /**
  20049. * Renderer component for managing metrics and monitoring data.
  20050. *
  20051. * @type {Info}
  20052. */
  20053. this.info = info;
  20054. /**
  20055. * A dictionary that manages render contexts in chain maps
  20056. * for each pass ID.
  20057. *
  20058. * @type {Object<string,ChainMap>}
  20059. */
  20060. this.chainMaps = {};
  20061. }
  20062. /**
  20063. * Returns a render object for the given object and state data.
  20064. *
  20065. * @param {Object3D} object - The 3D object.
  20066. * @param {Material} material - The 3D object's material.
  20067. * @param {Scene} scene - The scene the 3D object belongs to.
  20068. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20069. * @param {LightsNode} lightsNode - The lights node.
  20070. * @param {RenderContext} renderContext - The render context.
  20071. * @param {ClippingContext} clippingContext - The clipping context.
  20072. * @param {string} [passId] - An optional ID for identifying the pass.
  20073. * @return {RenderObject} The render object.
  20074. */
  20075. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20076. const chainMap = this.getChainMap( passId );
  20077. // reuse chainArray
  20078. _chainKeys$5[ 0 ] = object;
  20079. _chainKeys$5[ 1 ] = material;
  20080. _chainKeys$5[ 2 ] = renderContext;
  20081. _chainKeys$5[ 3 ] = lightsNode;
  20082. let renderObject = chainMap.get( _chainKeys$5 );
  20083. if ( renderObject === undefined ) {
  20084. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20085. chainMap.set( _chainKeys$5, renderObject );
  20086. } else {
  20087. renderObject.updateClipping( clippingContext );
  20088. if ( renderObject.needsGeometryUpdate ) {
  20089. renderObject.setGeometry( object.geometry );
  20090. }
  20091. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20092. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20093. renderObject.dispose();
  20094. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20095. } else {
  20096. renderObject.version = material.version;
  20097. }
  20098. }
  20099. }
  20100. _chainKeys$5.length = 0;
  20101. return renderObject;
  20102. }
  20103. /**
  20104. * Returns a chain map for the given pass ID.
  20105. *
  20106. * @param {string} [passId='default'] - The pass ID.
  20107. * @return {ChainMap} The chain map.
  20108. */
  20109. getChainMap( passId = 'default' ) {
  20110. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20111. }
  20112. /**
  20113. * Frees internal resources.
  20114. */
  20115. dispose() {
  20116. this.chainMaps = {};
  20117. }
  20118. /**
  20119. * Factory method for creating render objects with the given list of parameters.
  20120. *
  20121. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20122. * @param {Geometries} geometries - Renderer component for managing geometries.
  20123. * @param {Renderer} renderer - The renderer.
  20124. * @param {Object3D} object - The 3D object.
  20125. * @param {Material} material - The object's material.
  20126. * @param {Scene} scene - The scene the 3D object belongs to.
  20127. * @param {Camera} camera - The camera the object should be rendered with.
  20128. * @param {LightsNode} lightsNode - The lights node.
  20129. * @param {RenderContext} renderContext - The render context.
  20130. * @param {ClippingContext} clippingContext - The clipping context.
  20131. * @param {string} [passId] - An optional ID for identifying the pass.
  20132. * @return {RenderObject} The render object.
  20133. */
  20134. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20135. const chainMap = this.getChainMap( passId );
  20136. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  20137. renderObject.onDispose = () => {
  20138. this.pipelines.delete( renderObject );
  20139. this.bindings.delete( renderObject );
  20140. this.nodes.delete( renderObject );
  20141. chainMap.delete( renderObject.getChainArray() );
  20142. };
  20143. return renderObject;
  20144. }
  20145. }
  20146. /**
  20147. * Data structure for the renderer. It is intended to manage
  20148. * data of objects in dictionaries.
  20149. *
  20150. * @private
  20151. */
  20152. class DataMap {
  20153. /**
  20154. * Constructs a new data map.
  20155. */
  20156. constructor() {
  20157. /**
  20158. * `DataMap` internally uses a weak map
  20159. * to manage its data.
  20160. *
  20161. * @type {WeakMap<Object, Object>}
  20162. */
  20163. this.data = new WeakMap();
  20164. }
  20165. /**
  20166. * Returns the dictionary for the given object.
  20167. *
  20168. * @param {Object} object - The object.
  20169. * @return {Object} The dictionary.
  20170. */
  20171. get( object ) {
  20172. let map = this.data.get( object );
  20173. if ( map === undefined ) {
  20174. map = {};
  20175. this.data.set( object, map );
  20176. }
  20177. return map;
  20178. }
  20179. /**
  20180. * Deletes the dictionary for the given object.
  20181. *
  20182. * @param {Object} object - The object.
  20183. * @return {?Object} The deleted dictionary.
  20184. */
  20185. delete( object ) {
  20186. let map = null;
  20187. if ( this.data.has( object ) ) {
  20188. map = this.data.get( object );
  20189. this.data.delete( object );
  20190. }
  20191. return map;
  20192. }
  20193. /**
  20194. * Returns `true` if the given object has a dictionary defined.
  20195. *
  20196. * @param {Object} object - The object to test.
  20197. * @return {boolean} Whether a dictionary is defined or not.
  20198. */
  20199. has( object ) {
  20200. return this.data.has( object );
  20201. }
  20202. /**
  20203. * Frees internal resources.
  20204. */
  20205. dispose() {
  20206. this.data = new WeakMap();
  20207. }
  20208. }
  20209. const AttributeType = {
  20210. VERTEX: 1,
  20211. INDEX: 2,
  20212. STORAGE: 3,
  20213. INDIRECT: 4
  20214. };
  20215. // size of a chunk in bytes (STD140 layout)
  20216. const GPU_CHUNK_BYTES = 16;
  20217. // @TODO: Move to src/constants.js
  20218. const BlendColorFactor = 211;
  20219. const OneMinusBlendColorFactor = 212;
  20220. /**
  20221. * This renderer module manages geometry attributes.
  20222. *
  20223. * @private
  20224. * @augments DataMap
  20225. */
  20226. class Attributes extends DataMap {
  20227. /**
  20228. * Constructs a new attribute management component.
  20229. *
  20230. * @param {Backend} backend - The renderer's backend.
  20231. */
  20232. constructor( backend ) {
  20233. super();
  20234. /**
  20235. * The renderer's backend.
  20236. *
  20237. * @type {Backend}
  20238. */
  20239. this.backend = backend;
  20240. }
  20241. /**
  20242. * Deletes the data for the given attribute.
  20243. *
  20244. * @param {BufferAttribute} attribute - The attribute.
  20245. * @return {?Object} The deleted attribute data.
  20246. */
  20247. delete( attribute ) {
  20248. const attributeData = super.delete( attribute );
  20249. if ( attributeData !== null ) {
  20250. this.backend.destroyAttribute( attribute );
  20251. }
  20252. return attributeData;
  20253. }
  20254. /**
  20255. * Updates the given attribute. This method creates attribute buffers
  20256. * for new attributes and updates data for existing ones.
  20257. *
  20258. * @param {BufferAttribute} attribute - The attribute to update.
  20259. * @param {number} type - The attribute type.
  20260. */
  20261. update( attribute, type ) {
  20262. const data = this.get( attribute );
  20263. if ( data.version === undefined ) {
  20264. if ( type === AttributeType.VERTEX ) {
  20265. this.backend.createAttribute( attribute );
  20266. } else if ( type === AttributeType.INDEX ) {
  20267. this.backend.createIndexAttribute( attribute );
  20268. } else if ( type === AttributeType.STORAGE ) {
  20269. this.backend.createStorageAttribute( attribute );
  20270. } else if ( type === AttributeType.INDIRECT ) {
  20271. this.backend.createIndirectStorageAttribute( attribute );
  20272. }
  20273. data.version = this._getBufferAttribute( attribute ).version;
  20274. } else {
  20275. const bufferAttribute = this._getBufferAttribute( attribute );
  20276. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20277. this.backend.updateAttribute( attribute );
  20278. data.version = bufferAttribute.version;
  20279. }
  20280. }
  20281. }
  20282. /**
  20283. * Utility method for handling interleaved buffer attributes correctly.
  20284. * To process them, their `InterleavedBuffer` is returned.
  20285. *
  20286. * @param {BufferAttribute} attribute - The attribute.
  20287. * @return {BufferAttribute|InterleavedBuffer}
  20288. */
  20289. _getBufferAttribute( attribute ) {
  20290. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20291. return attribute;
  20292. }
  20293. }
  20294. /**
  20295. * Returns the wireframe version for the given geometry.
  20296. *
  20297. * @private
  20298. * @function
  20299. * @param {BufferGeometry} geometry - The geometry.
  20300. * @return {number} The version.
  20301. */
  20302. function getWireframeVersion( geometry ) {
  20303. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  20304. }
  20305. /**
  20306. * Returns a wireframe index attribute for the given geometry.
  20307. *
  20308. * @private
  20309. * @function
  20310. * @param {BufferGeometry} geometry - The geometry.
  20311. * @return {BufferAttribute} The wireframe index attribute.
  20312. */
  20313. function getWireframeIndex( geometry ) {
  20314. const indices = [];
  20315. const geometryIndex = geometry.index;
  20316. const geometryPosition = geometry.attributes.position;
  20317. if ( geometryIndex !== null ) {
  20318. const array = geometryIndex.array;
  20319. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  20320. const a = array[ i + 0 ];
  20321. const b = array[ i + 1 ];
  20322. const c = array[ i + 2 ];
  20323. indices.push( a, b, b, c, c, a );
  20324. }
  20325. } else {
  20326. const array = geometryPosition.array;
  20327. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  20328. const a = i + 0;
  20329. const b = i + 1;
  20330. const c = i + 2;
  20331. indices.push( a, b, b, c, c, a );
  20332. }
  20333. }
  20334. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  20335. attribute.version = getWireframeVersion( geometry );
  20336. return attribute;
  20337. }
  20338. /**
  20339. * This renderer module manages geometries.
  20340. *
  20341. * @private
  20342. * @augments DataMap
  20343. */
  20344. class Geometries extends DataMap {
  20345. /**
  20346. * Constructs a new geometry management component.
  20347. *
  20348. * @param {Attributes} attributes - Renderer component for managing attributes.
  20349. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20350. */
  20351. constructor( attributes, info ) {
  20352. super();
  20353. /**
  20354. * Renderer component for managing attributes.
  20355. *
  20356. * @type {Attributes}
  20357. */
  20358. this.attributes = attributes;
  20359. /**
  20360. * Renderer component for managing metrics and monitoring data.
  20361. *
  20362. * @type {Info}
  20363. */
  20364. this.info = info;
  20365. /**
  20366. * Weak Map for managing attributes for wireframe rendering.
  20367. *
  20368. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20369. */
  20370. this.wireframes = new WeakMap();
  20371. /**
  20372. * This Weak Map is used to make sure buffer attributes are
  20373. * updated only once per render call.
  20374. *
  20375. * @type {WeakMap<BufferAttribute,number>}
  20376. */
  20377. this.attributeCall = new WeakMap();
  20378. }
  20379. /**
  20380. * Returns `true` if the given render object has an initialized geometry.
  20381. *
  20382. * @param {RenderObject} renderObject - The render object.
  20383. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20384. */
  20385. has( renderObject ) {
  20386. const geometry = renderObject.geometry;
  20387. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20388. }
  20389. /**
  20390. * Prepares the geometry of the given render object for rendering.
  20391. *
  20392. * @param {RenderObject} renderObject - The render object.
  20393. */
  20394. updateForRender( renderObject ) {
  20395. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20396. this.updateAttributes( renderObject );
  20397. }
  20398. /**
  20399. * Initializes the geometry of the given render object.
  20400. *
  20401. * @param {RenderObject} renderObject - The render object.
  20402. */
  20403. initGeometry( renderObject ) {
  20404. const geometry = renderObject.geometry;
  20405. const geometryData = this.get( geometry );
  20406. geometryData.initialized = true;
  20407. this.info.memory.geometries ++;
  20408. const onDispose = () => {
  20409. this.info.memory.geometries --;
  20410. const index = geometry.index;
  20411. const geometryAttributes = renderObject.getAttributes();
  20412. if ( index !== null ) {
  20413. this.attributes.delete( index );
  20414. }
  20415. for ( const geometryAttribute of geometryAttributes ) {
  20416. this.attributes.delete( geometryAttribute );
  20417. }
  20418. const wireframeAttribute = this.wireframes.get( geometry );
  20419. if ( wireframeAttribute !== undefined ) {
  20420. this.attributes.delete( wireframeAttribute );
  20421. }
  20422. geometry.removeEventListener( 'dispose', onDispose );
  20423. };
  20424. geometry.addEventListener( 'dispose', onDispose );
  20425. }
  20426. /**
  20427. * Updates the geometry attributes of the given render object.
  20428. *
  20429. * @param {RenderObject} renderObject - The render object.
  20430. */
  20431. updateAttributes( renderObject ) {
  20432. // attributes
  20433. const attributes = renderObject.getAttributes();
  20434. for ( const attribute of attributes ) {
  20435. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20436. this.updateAttribute( attribute, AttributeType.STORAGE );
  20437. } else {
  20438. this.updateAttribute( attribute, AttributeType.VERTEX );
  20439. }
  20440. }
  20441. // indexes
  20442. const index = this.getIndex( renderObject );
  20443. if ( index !== null ) {
  20444. this.updateAttribute( index, AttributeType.INDEX );
  20445. }
  20446. // indirect
  20447. const indirect = renderObject.geometry.indirect;
  20448. if ( indirect !== null ) {
  20449. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20450. }
  20451. }
  20452. /**
  20453. * Updates the given attribute.
  20454. *
  20455. * @param {BufferAttribute} attribute - The attribute to update.
  20456. * @param {number} type - The attribute type.
  20457. */
  20458. updateAttribute( attribute, type ) {
  20459. const callId = this.info.render.calls;
  20460. if ( ! attribute.isInterleavedBufferAttribute ) {
  20461. if ( this.attributeCall.get( attribute ) !== callId ) {
  20462. this.attributes.update( attribute, type );
  20463. this.attributeCall.set( attribute, callId );
  20464. }
  20465. } else {
  20466. if ( this.attributeCall.get( attribute ) === undefined ) {
  20467. this.attributes.update( attribute, type );
  20468. this.attributeCall.set( attribute, callId );
  20469. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20470. this.attributes.update( attribute, type );
  20471. this.attributeCall.set( attribute.data, callId );
  20472. this.attributeCall.set( attribute, callId );
  20473. }
  20474. }
  20475. }
  20476. /**
  20477. * Returns the indirect buffer attribute of the given render object.
  20478. *
  20479. * @param {RenderObject} renderObject - The render object.
  20480. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20481. */
  20482. getIndirect( renderObject ) {
  20483. return renderObject.geometry.indirect;
  20484. }
  20485. /**
  20486. * Returns the index of the given render object's geometry. This is implemented
  20487. * in a method to return a wireframe index if necessary.
  20488. *
  20489. * @param {RenderObject} renderObject - The render object.
  20490. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20491. */
  20492. getIndex( renderObject ) {
  20493. const { geometry, material } = renderObject;
  20494. let index = geometry.index;
  20495. if ( material.wireframe === true ) {
  20496. const wireframes = this.wireframes;
  20497. let wireframeAttribute = wireframes.get( geometry );
  20498. if ( wireframeAttribute === undefined ) {
  20499. wireframeAttribute = getWireframeIndex( geometry );
  20500. wireframes.set( geometry, wireframeAttribute );
  20501. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20502. this.attributes.delete( wireframeAttribute );
  20503. wireframeAttribute = getWireframeIndex( geometry );
  20504. wireframes.set( geometry, wireframeAttribute );
  20505. }
  20506. index = wireframeAttribute;
  20507. }
  20508. return index;
  20509. }
  20510. }
  20511. /**
  20512. * This renderer module provides a series of statistical information
  20513. * about the GPU memory and the rendering process. Useful for debugging
  20514. * and monitoring.
  20515. */
  20516. class Info {
  20517. /**
  20518. * Constructs a new info component.
  20519. */
  20520. constructor() {
  20521. /**
  20522. * Whether frame related metrics should automatically
  20523. * be resetted or not. This property should be set to `false`
  20524. * by apps which manage their own animation loop. They must
  20525. * then call `renderer.info.reset()` once per frame manually.
  20526. *
  20527. * @type {boolean}
  20528. * @default true
  20529. */
  20530. this.autoReset = true;
  20531. /**
  20532. * The current frame ID. This ID is managed
  20533. * by `NodeFrame`.
  20534. *
  20535. * @type {number}
  20536. * @readonly
  20537. * @default 0
  20538. */
  20539. this.frame = 0;
  20540. /**
  20541. * The number of render calls since the
  20542. * app has been started.
  20543. *
  20544. * @type {number}
  20545. * @readonly
  20546. * @default 0
  20547. */
  20548. this.calls = 0;
  20549. /**
  20550. * Render related metrics.
  20551. *
  20552. * @type {Object}
  20553. * @readonly
  20554. * @property {number} calls - The number of render calls since the app has been started.
  20555. * @property {number} frameCalls - The number of render calls of the current frame.
  20556. * @property {number} drawCalls - The number of draw calls of the current frame.
  20557. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20558. * @property {number} points - The number of rendered point primitives of the current frame.
  20559. * @property {number} lines - The number of rendered line primitives of the current frame.
  20560. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  20561. */
  20562. this.render = {
  20563. calls: 0,
  20564. frameCalls: 0,
  20565. drawCalls: 0,
  20566. triangles: 0,
  20567. points: 0,
  20568. lines: 0,
  20569. timestamp: 0,
  20570. };
  20571. /**
  20572. * Compute related metrics.
  20573. *
  20574. * @type {Object}
  20575. * @readonly
  20576. * @property {number} calls - The number of compute calls since the app has been started.
  20577. * @property {number} frameCalls - The number of compute calls of the current frame.
  20578. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20579. */
  20580. this.compute = {
  20581. calls: 0,
  20582. frameCalls: 0,
  20583. timestamp: 0
  20584. };
  20585. /**
  20586. * Memory related metrics.
  20587. *
  20588. * @type {Object}
  20589. * @readonly
  20590. * @property {number} geometries - The number of active geometries.
  20591. * @property {number} frameCalls - The number of active textures.
  20592. */
  20593. this.memory = {
  20594. geometries: 0,
  20595. textures: 0
  20596. };
  20597. }
  20598. /**
  20599. * This method should be executed per draw call and updates the corresponding metrics.
  20600. *
  20601. * @param {Object3D} object - The 3D object that is going to be rendered.
  20602. * @param {number} count - The vertex or index count.
  20603. * @param {number} instanceCount - The instance count.
  20604. */
  20605. update( object, count, instanceCount ) {
  20606. this.render.drawCalls ++;
  20607. if ( object.isMesh || object.isSprite ) {
  20608. this.render.triangles += instanceCount * ( count / 3 );
  20609. } else if ( object.isPoints ) {
  20610. this.render.points += instanceCount * count;
  20611. } else if ( object.isLineSegments ) {
  20612. this.render.lines += instanceCount * ( count / 2 );
  20613. } else if ( object.isLine ) {
  20614. this.render.lines += instanceCount * ( count - 1 );
  20615. } else {
  20616. error( 'WebGPUInfo: Unknown object type.' );
  20617. }
  20618. }
  20619. /**
  20620. * Resets frame related metrics.
  20621. */
  20622. reset() {
  20623. this.render.drawCalls = 0;
  20624. this.render.frameCalls = 0;
  20625. this.compute.frameCalls = 0;
  20626. this.render.triangles = 0;
  20627. this.render.points = 0;
  20628. this.render.lines = 0;
  20629. }
  20630. /**
  20631. * Performs a complete reset of the object.
  20632. */
  20633. dispose() {
  20634. this.reset();
  20635. this.calls = 0;
  20636. this.render.calls = 0;
  20637. this.compute.calls = 0;
  20638. this.render.timestamp = 0;
  20639. this.compute.timestamp = 0;
  20640. this.memory.geometries = 0;
  20641. this.memory.textures = 0;
  20642. }
  20643. }
  20644. /**
  20645. * Abstract class for representing pipelines.
  20646. *
  20647. * @private
  20648. * @abstract
  20649. */
  20650. class Pipeline {
  20651. /**
  20652. * Constructs a new pipeline.
  20653. *
  20654. * @param {string} cacheKey - The pipeline's cache key.
  20655. */
  20656. constructor( cacheKey ) {
  20657. /**
  20658. * The pipeline's cache key.
  20659. *
  20660. * @type {string}
  20661. */
  20662. this.cacheKey = cacheKey;
  20663. /**
  20664. * How often the pipeline is currently in use.
  20665. *
  20666. * @type {number}
  20667. * @default 0
  20668. */
  20669. this.usedTimes = 0;
  20670. }
  20671. }
  20672. /**
  20673. * Class for representing render pipelines.
  20674. *
  20675. * @private
  20676. * @augments Pipeline
  20677. */
  20678. class RenderPipeline extends Pipeline {
  20679. /**
  20680. * Constructs a new render pipeline.
  20681. *
  20682. * @param {string} cacheKey - The pipeline's cache key.
  20683. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  20684. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  20685. */
  20686. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  20687. super( cacheKey );
  20688. /**
  20689. * The pipeline's vertex shader.
  20690. *
  20691. * @type {ProgrammableStage}
  20692. */
  20693. this.vertexProgram = vertexProgram;
  20694. /**
  20695. * The pipeline's fragment shader.
  20696. *
  20697. * @type {ProgrammableStage}
  20698. */
  20699. this.fragmentProgram = fragmentProgram;
  20700. }
  20701. }
  20702. /**
  20703. * Class for representing compute pipelines.
  20704. *
  20705. * @private
  20706. * @augments Pipeline
  20707. */
  20708. class ComputePipeline extends Pipeline {
  20709. /**
  20710. * Constructs a new render pipeline.
  20711. *
  20712. * @param {string} cacheKey - The pipeline's cache key.
  20713. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  20714. */
  20715. constructor( cacheKey, computeProgram ) {
  20716. super( cacheKey );
  20717. /**
  20718. * The pipeline's compute shader.
  20719. *
  20720. * @type {ProgrammableStage}
  20721. */
  20722. this.computeProgram = computeProgram;
  20723. /**
  20724. * This flag can be used for type testing.
  20725. *
  20726. * @type {boolean}
  20727. * @readonly
  20728. * @default true
  20729. */
  20730. this.isComputePipeline = true;
  20731. }
  20732. }
  20733. let _id$8 = 0;
  20734. /**
  20735. * Class for representing programmable stages which are vertex,
  20736. * fragment or compute shaders. Unlike fixed-function states (like blending),
  20737. * they represent the programmable part of a pipeline.
  20738. *
  20739. * @private
  20740. */
  20741. class ProgrammableStage {
  20742. /**
  20743. * Constructs a new programmable stage.
  20744. *
  20745. * @param {string} code - The shader code.
  20746. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  20747. * @param {string} name - The name of the shader.
  20748. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20749. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20750. */
  20751. constructor( code, stage, name, transforms = null, attributes = null ) {
  20752. /**
  20753. * The id of the programmable stage.
  20754. *
  20755. * @type {number}
  20756. */
  20757. this.id = _id$8 ++;
  20758. /**
  20759. * The shader code.
  20760. *
  20761. * @type {string}
  20762. */
  20763. this.code = code;
  20764. /**
  20765. * The type of stage.
  20766. *
  20767. * @type {string}
  20768. */
  20769. this.stage = stage;
  20770. /**
  20771. * The name of the stage.
  20772. * This is used for debugging purposes.
  20773. *
  20774. * @type {string}
  20775. */
  20776. this.name = name;
  20777. /**
  20778. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20779. *
  20780. * @type {?Array<Object>}
  20781. */
  20782. this.transforms = transforms;
  20783. /**
  20784. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20785. *
  20786. * @type {?Array<Object>}
  20787. */
  20788. this.attributes = attributes;
  20789. /**
  20790. * How often the programmable stage is currently in use.
  20791. *
  20792. * @type {number}
  20793. * @default 0
  20794. */
  20795. this.usedTimes = 0;
  20796. }
  20797. }
  20798. /**
  20799. * This renderer module manages the pipelines of the renderer.
  20800. *
  20801. * @private
  20802. * @augments DataMap
  20803. */
  20804. class Pipelines extends DataMap {
  20805. /**
  20806. * Constructs a new pipeline management component.
  20807. *
  20808. * @param {Backend} backend - The renderer's backend.
  20809. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20810. */
  20811. constructor( backend, nodes ) {
  20812. super();
  20813. /**
  20814. * The renderer's backend.
  20815. *
  20816. * @type {Backend}
  20817. */
  20818. this.backend = backend;
  20819. /**
  20820. * Renderer component for managing nodes related logic.
  20821. *
  20822. * @type {Nodes}
  20823. */
  20824. this.nodes = nodes;
  20825. /**
  20826. * A references to the bindings management component.
  20827. * This reference will be set inside the `Bindings`
  20828. * constructor.
  20829. *
  20830. * @type {?Bindings}
  20831. * @default null
  20832. */
  20833. this.bindings = null;
  20834. /**
  20835. * Internal cache for maintaining pipelines.
  20836. * The key of the map is a cache key, the value the pipeline.
  20837. *
  20838. * @type {Map<string,Pipeline>}
  20839. */
  20840. this.caches = new Map();
  20841. /**
  20842. * This dictionary maintains for each shader stage type (vertex,
  20843. * fragment and compute) the programmable stage objects which
  20844. * represent the actual shader code.
  20845. *
  20846. * @type {Object<string,Map<string, ProgrammableStage>>}
  20847. */
  20848. this.programs = {
  20849. vertex: new Map(),
  20850. fragment: new Map(),
  20851. compute: new Map()
  20852. };
  20853. }
  20854. /**
  20855. * Returns a compute pipeline for the given compute node.
  20856. *
  20857. * @param {Node} computeNode - The compute node.
  20858. * @param {Array<BindGroup>} bindings - The bindings.
  20859. * @return {ComputePipeline} The compute pipeline.
  20860. */
  20861. getForCompute( computeNode, bindings ) {
  20862. const { backend } = this;
  20863. const data = this.get( computeNode );
  20864. if ( this._needsComputeUpdate( computeNode ) ) {
  20865. const previousPipeline = data.pipeline;
  20866. if ( previousPipeline ) {
  20867. previousPipeline.usedTimes --;
  20868. previousPipeline.computeProgram.usedTimes --;
  20869. }
  20870. // get shader
  20871. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  20872. // programmable stage
  20873. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  20874. if ( stageCompute === undefined ) {
  20875. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  20876. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  20877. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  20878. backend.createProgram( stageCompute );
  20879. }
  20880. // determine compute pipeline
  20881. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  20882. let pipeline = this.caches.get( cacheKey );
  20883. if ( pipeline === undefined ) {
  20884. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20885. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  20886. }
  20887. // keep track of all used times
  20888. pipeline.usedTimes ++;
  20889. stageCompute.usedTimes ++;
  20890. //
  20891. data.version = computeNode.version;
  20892. data.pipeline = pipeline;
  20893. }
  20894. return data.pipeline;
  20895. }
  20896. /**
  20897. * Returns a render pipeline for the given render object.
  20898. *
  20899. * @param {RenderObject} renderObject - The render object.
  20900. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20901. * @return {RenderPipeline} The render pipeline.
  20902. */
  20903. getForRender( renderObject, promises = null ) {
  20904. const { backend } = this;
  20905. const data = this.get( renderObject );
  20906. if ( this._needsRenderUpdate( renderObject ) ) {
  20907. const previousPipeline = data.pipeline;
  20908. if ( previousPipeline ) {
  20909. previousPipeline.usedTimes --;
  20910. previousPipeline.vertexProgram.usedTimes --;
  20911. previousPipeline.fragmentProgram.usedTimes --;
  20912. }
  20913. // get shader
  20914. const nodeBuilderState = renderObject.getNodeBuilderState();
  20915. const name = renderObject.material ? renderObject.material.name : '';
  20916. // programmable stages
  20917. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  20918. if ( stageVertex === undefined ) {
  20919. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  20920. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  20921. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  20922. backend.createProgram( stageVertex );
  20923. }
  20924. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  20925. if ( stageFragment === undefined ) {
  20926. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  20927. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  20928. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  20929. backend.createProgram( stageFragment );
  20930. }
  20931. // determine render pipeline
  20932. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20933. let pipeline = this.caches.get( cacheKey );
  20934. if ( pipeline === undefined ) {
  20935. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20936. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  20937. } else {
  20938. renderObject.pipeline = pipeline;
  20939. }
  20940. // keep track of all used times
  20941. pipeline.usedTimes ++;
  20942. stageVertex.usedTimes ++;
  20943. stageFragment.usedTimes ++;
  20944. //
  20945. data.pipeline = pipeline;
  20946. }
  20947. return data.pipeline;
  20948. }
  20949. /**
  20950. * Deletes the pipeline for the given render object.
  20951. *
  20952. * @param {RenderObject} object - The render object.
  20953. * @return {?Object} The deleted dictionary.
  20954. */
  20955. delete( object ) {
  20956. const pipeline = this.get( object ).pipeline;
  20957. if ( pipeline ) {
  20958. // pipeline
  20959. pipeline.usedTimes --;
  20960. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  20961. // programs
  20962. if ( pipeline.isComputePipeline ) {
  20963. pipeline.computeProgram.usedTimes --;
  20964. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  20965. } else {
  20966. pipeline.fragmentProgram.usedTimes --;
  20967. pipeline.vertexProgram.usedTimes --;
  20968. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  20969. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  20970. }
  20971. }
  20972. return super.delete( object );
  20973. }
  20974. /**
  20975. * Frees internal resources.
  20976. */
  20977. dispose() {
  20978. super.dispose();
  20979. this.caches = new Map();
  20980. this.programs = {
  20981. vertex: new Map(),
  20982. fragment: new Map(),
  20983. compute: new Map()
  20984. };
  20985. }
  20986. /**
  20987. * Updates the pipeline for the given render object.
  20988. *
  20989. * @param {RenderObject} renderObject - The render object.
  20990. */
  20991. updateForRender( renderObject ) {
  20992. this.getForRender( renderObject );
  20993. }
  20994. /**
  20995. * Returns a compute pipeline for the given parameters.
  20996. *
  20997. * @private
  20998. * @param {Node} computeNode - The compute node.
  20999. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21000. * @param {string} cacheKey - The cache key.
  21001. * @param {Array<BindGroup>} bindings - The bindings.
  21002. * @return {ComputePipeline} The compute pipeline.
  21003. */
  21004. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  21005. // check for existing pipeline
  21006. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  21007. let pipeline = this.caches.get( cacheKey );
  21008. if ( pipeline === undefined ) {
  21009. pipeline = new ComputePipeline( cacheKey, stageCompute );
  21010. this.caches.set( cacheKey, pipeline );
  21011. this.backend.createComputePipeline( pipeline, bindings );
  21012. }
  21013. return pipeline;
  21014. }
  21015. /**
  21016. * Returns a render pipeline for the given parameters.
  21017. *
  21018. * @private
  21019. * @param {RenderObject} renderObject - The render object.
  21020. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21021. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21022. * @param {string} cacheKey - The cache key.
  21023. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21024. * @return {ComputePipeline} The compute pipeline.
  21025. */
  21026. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21027. // check for existing pipeline
  21028. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21029. let pipeline = this.caches.get( cacheKey );
  21030. if ( pipeline === undefined ) {
  21031. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21032. this.caches.set( cacheKey, pipeline );
  21033. renderObject.pipeline = pipeline;
  21034. // The `promises` array is `null` by default and only set to an empty array when
  21035. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21036. // pending promises that resolve when the render pipelines are ready for rendering.
  21037. this.backend.createRenderPipeline( renderObject, promises );
  21038. }
  21039. return pipeline;
  21040. }
  21041. /**
  21042. * Computes a cache key representing a compute pipeline.
  21043. *
  21044. * @private
  21045. * @param {Node} computeNode - The compute node.
  21046. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21047. * @return {string} The cache key.
  21048. */
  21049. _getComputeCacheKey( computeNode, stageCompute ) {
  21050. return computeNode.id + ',' + stageCompute.id;
  21051. }
  21052. /**
  21053. * Computes a cache key representing a render pipeline.
  21054. *
  21055. * @private
  21056. * @param {RenderObject} renderObject - The render object.
  21057. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21058. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21059. * @return {string} The cache key.
  21060. */
  21061. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21062. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21063. }
  21064. /**
  21065. * Releases the given pipeline.
  21066. *
  21067. * @private
  21068. * @param {Pipeline} pipeline - The pipeline to release.
  21069. */
  21070. _releasePipeline( pipeline ) {
  21071. this.caches.delete( pipeline.cacheKey );
  21072. }
  21073. /**
  21074. * Releases the shader program.
  21075. *
  21076. * @private
  21077. * @param {Object} program - The shader program to release.
  21078. */
  21079. _releaseProgram( program ) {
  21080. const code = program.code;
  21081. const stage = program.stage;
  21082. this.programs[ stage ].delete( code );
  21083. }
  21084. /**
  21085. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21086. *
  21087. * @private
  21088. * @param {Node} computeNode - The compute node.
  21089. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21090. */
  21091. _needsComputeUpdate( computeNode ) {
  21092. const data = this.get( computeNode );
  21093. return data.pipeline === undefined || data.version !== computeNode.version;
  21094. }
  21095. /**
  21096. * Returns `true` if the render pipeline for the given render object requires an update.
  21097. *
  21098. * @private
  21099. * @param {RenderObject} renderObject - The render object.
  21100. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21101. */
  21102. _needsRenderUpdate( renderObject ) {
  21103. const data = this.get( renderObject );
  21104. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21105. }
  21106. }
  21107. /**
  21108. * This renderer module manages the bindings of the renderer.
  21109. *
  21110. * @private
  21111. * @augments DataMap
  21112. */
  21113. class Bindings extends DataMap {
  21114. /**
  21115. * Constructs a new bindings management component.
  21116. *
  21117. * @param {Backend} backend - The renderer's backend.
  21118. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21119. * @param {Textures} textures - Renderer component for managing textures.
  21120. * @param {Attributes} attributes - Renderer component for managing attributes.
  21121. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21122. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21123. */
  21124. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  21125. super();
  21126. /**
  21127. * The renderer's backend.
  21128. *
  21129. * @type {Backend}
  21130. */
  21131. this.backend = backend;
  21132. /**
  21133. * Renderer component for managing textures.
  21134. *
  21135. * @type {Textures}
  21136. */
  21137. this.textures = textures;
  21138. /**
  21139. * Renderer component for managing pipelines.
  21140. *
  21141. * @type {Pipelines}
  21142. */
  21143. this.pipelines = pipelines;
  21144. /**
  21145. * Renderer component for managing attributes.
  21146. *
  21147. * @type {Attributes}
  21148. */
  21149. this.attributes = attributes;
  21150. /**
  21151. * Renderer component for managing nodes related logic.
  21152. *
  21153. * @type {Nodes}
  21154. */
  21155. this.nodes = nodes;
  21156. /**
  21157. * Renderer component for managing metrics and monitoring data.
  21158. *
  21159. * @type {Info}
  21160. */
  21161. this.info = info;
  21162. this.pipelines.bindings = this; // assign bindings to pipelines
  21163. }
  21164. /**
  21165. * Returns the bind groups for the given render object.
  21166. *
  21167. * @param {RenderObject} renderObject - The render object.
  21168. * @return {Array<BindGroup>} The bind groups.
  21169. */
  21170. getForRender( renderObject ) {
  21171. const bindings = renderObject.getBindings();
  21172. for ( const bindGroup of bindings ) {
  21173. const groupData = this.get( bindGroup );
  21174. if ( groupData.bindGroup === undefined ) {
  21175. // each object defines an array of bindings (ubos, textures, samplers etc.)
  21176. this._init( bindGroup );
  21177. this.backend.createBindings( bindGroup, bindings, 0 );
  21178. groupData.bindGroup = bindGroup;
  21179. }
  21180. }
  21181. return bindings;
  21182. }
  21183. /**
  21184. * Returns the bind groups for the given compute node.
  21185. *
  21186. * @param {Node} computeNode - The compute node.
  21187. * @return {Array<BindGroup>} The bind groups.
  21188. */
  21189. getForCompute( computeNode ) {
  21190. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21191. for ( const bindGroup of bindings ) {
  21192. const groupData = this.get( bindGroup );
  21193. if ( groupData.bindGroup === undefined ) {
  21194. this._init( bindGroup );
  21195. this.backend.createBindings( bindGroup, bindings, 0 );
  21196. groupData.bindGroup = bindGroup;
  21197. }
  21198. }
  21199. return bindings;
  21200. }
  21201. /**
  21202. * Updates the bindings for the given compute node.
  21203. *
  21204. * @param {Node} computeNode - The compute node.
  21205. */
  21206. updateForCompute( computeNode ) {
  21207. this._updateBindings( this.getForCompute( computeNode ) );
  21208. }
  21209. /**
  21210. * Updates the bindings for the given render object.
  21211. *
  21212. * @param {RenderObject} renderObject - The render object.
  21213. */
  21214. updateForRender( renderObject ) {
  21215. this._updateBindings( this.getForRender( renderObject ) );
  21216. }
  21217. /**
  21218. * Deletes the bindings for the given compute node.
  21219. *
  21220. * @param {Node} computeNode - The compute node.
  21221. */
  21222. deleteForCompute( computeNode ) {
  21223. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21224. for ( const bindGroup of bindings ) {
  21225. this.delete( bindGroup );
  21226. }
  21227. }
  21228. /**
  21229. * Updates the given array of bindings.
  21230. *
  21231. * @param {Array<BindGroup>} bindings - The bind groups.
  21232. */
  21233. _updateBindings( bindings ) {
  21234. for ( const bindGroup of bindings ) {
  21235. this._update( bindGroup, bindings );
  21236. }
  21237. }
  21238. /**
  21239. * Initializes the given bind group.
  21240. *
  21241. * @param {BindGroup} bindGroup - The bind group to initialize.
  21242. */
  21243. _init( bindGroup ) {
  21244. for ( const binding of bindGroup.bindings ) {
  21245. if ( binding.isSampledTexture ) {
  21246. this.textures.updateTexture( binding.texture );
  21247. } else if ( binding.isStorageBuffer ) {
  21248. const attribute = binding.attribute;
  21249. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21250. this.attributes.update( attribute, attributeType );
  21251. }
  21252. }
  21253. }
  21254. /**
  21255. * Updates the given bind group.
  21256. *
  21257. * @param {BindGroup} bindGroup - The bind group to update.
  21258. * @param {Array<BindGroup>} bindings - The bind groups.
  21259. */
  21260. _update( bindGroup, bindings ) {
  21261. const { backend } = this;
  21262. let needsBindingsUpdate = false;
  21263. let cacheBindings = true;
  21264. let cacheIndex = 0;
  21265. let version = 0;
  21266. // iterate over all bindings and check if buffer updates or a new binding group is required
  21267. for ( const binding of bindGroup.bindings ) {
  21268. if ( binding.isNodeUniformsGroup ) {
  21269. const updated = this.nodes.updateGroup( binding );
  21270. // every uniforms group is a uniform buffer. So if no update is required,
  21271. // we move one with the next binding. Otherwise the next if block will update the group.
  21272. if ( updated === false ) continue;
  21273. }
  21274. if ( binding.isStorageBuffer ) {
  21275. const attribute = binding.attribute;
  21276. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21277. this.attributes.update( attribute, attributeType );
  21278. }
  21279. if ( binding.isUniformBuffer ) {
  21280. const updated = binding.update();
  21281. if ( updated ) {
  21282. backend.updateBinding( binding );
  21283. }
  21284. } else if ( binding.isSampledTexture ) {
  21285. const updated = binding.update();
  21286. // get the texture data after the update, to sync the texture reference from node
  21287. const texture = binding.texture;
  21288. const texturesTextureData = this.textures.get( texture );
  21289. if ( updated ) {
  21290. // version: update the texture data or create a new one
  21291. this.textures.updateTexture( texture );
  21292. // generation: update the bindings if a new texture has been created
  21293. if ( binding.generation !== texturesTextureData.generation ) {
  21294. binding.generation = texturesTextureData.generation;
  21295. needsBindingsUpdate = true;
  21296. cacheBindings = false;
  21297. }
  21298. }
  21299. const textureData = backend.get( texture );
  21300. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  21301. cacheBindings = false;
  21302. } else {
  21303. cacheIndex = cacheIndex * 10 + texture.id;
  21304. version += texture.version;
  21305. }
  21306. if ( texture.isStorageTexture === true ) {
  21307. const textureData = this.get( texture );
  21308. if ( binding.store === true ) {
  21309. textureData.needsMipmap = true;
  21310. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  21311. this.backend.generateMipmaps( texture );
  21312. textureData.needsMipmap = false;
  21313. }
  21314. }
  21315. } else if ( binding.isSampler ) {
  21316. binding.update();
  21317. }
  21318. }
  21319. if ( needsBindingsUpdate === true ) {
  21320. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  21321. }
  21322. }
  21323. }
  21324. /**
  21325. * Default sorting function for opaque render items.
  21326. *
  21327. * @private
  21328. * @function
  21329. * @param {Object} a - The first render item.
  21330. * @param {Object} b - The second render item.
  21331. * @return {number} A numeric value which defines the sort order.
  21332. */
  21333. function painterSortStable( a, b ) {
  21334. if ( a.groupOrder !== b.groupOrder ) {
  21335. return a.groupOrder - b.groupOrder;
  21336. } else if ( a.renderOrder !== b.renderOrder ) {
  21337. return a.renderOrder - b.renderOrder;
  21338. } else if ( a.z !== b.z ) {
  21339. return a.z - b.z;
  21340. } else {
  21341. return a.id - b.id;
  21342. }
  21343. }
  21344. /**
  21345. * Default sorting function for transparent render items.
  21346. *
  21347. * @private
  21348. * @function
  21349. * @param {Object} a - The first render item.
  21350. * @param {Object} b - The second render item.
  21351. * @return {number} A numeric value which defines the sort order.
  21352. */
  21353. function reversePainterSortStable( a, b ) {
  21354. if ( a.groupOrder !== b.groupOrder ) {
  21355. return a.groupOrder - b.groupOrder;
  21356. } else if ( a.renderOrder !== b.renderOrder ) {
  21357. return a.renderOrder - b.renderOrder;
  21358. } else if ( a.z !== b.z ) {
  21359. return b.z - a.z;
  21360. } else {
  21361. return a.id - b.id;
  21362. }
  21363. }
  21364. /**
  21365. * Returns `true` if the given transparent material requires a double pass.
  21366. *
  21367. * @private
  21368. * @function
  21369. * @param {Material} material - The transparent material.
  21370. * @return {boolean} Whether the given material requires a double pass or not.
  21371. */
  21372. function needsDoublePass( material ) {
  21373. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  21374. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21375. }
  21376. /**
  21377. * When the renderer analyzes the scene at the beginning of a render call,
  21378. * it stores 3D object for further processing in render lists. Depending on the
  21379. * properties of a 3D objects (like their transformation or material state), the
  21380. * objects are maintained in ordered lists for the actual rendering.
  21381. *
  21382. * Render lists are unique per scene and camera combination.
  21383. *
  21384. * @private
  21385. * @augments Pipeline
  21386. */
  21387. class RenderList {
  21388. /**
  21389. * Constructs a render list.
  21390. *
  21391. * @param {Lighting} lighting - The lighting management component.
  21392. * @param {Scene} scene - The scene.
  21393. * @param {Camera} camera - The camera the scene is rendered with.
  21394. */
  21395. constructor( lighting, scene, camera ) {
  21396. /**
  21397. * 3D objects are transformed into render items and stored in this array.
  21398. *
  21399. * @type {Array<Object>}
  21400. */
  21401. this.renderItems = [];
  21402. /**
  21403. * The current render items index.
  21404. *
  21405. * @type {number}
  21406. * @default 0
  21407. */
  21408. this.renderItemsIndex = 0;
  21409. /**
  21410. * A list with opaque render items.
  21411. *
  21412. * @type {Array<Object>}
  21413. */
  21414. this.opaque = [];
  21415. /**
  21416. * A list with transparent render items which require
  21417. * double pass rendering (e.g. transmissive objects).
  21418. *
  21419. * @type {Array<Object>}
  21420. */
  21421. this.transparentDoublePass = [];
  21422. /**
  21423. * A list with transparent render items.
  21424. *
  21425. * @type {Array<Object>}
  21426. */
  21427. this.transparent = [];
  21428. /**
  21429. * A list with transparent render bundle data.
  21430. *
  21431. * @type {Array<Object>}
  21432. */
  21433. this.bundles = [];
  21434. /**
  21435. * The render list's lights node. This node is later
  21436. * relevant for the actual analytical light nodes which
  21437. * compute the scene's lighting in the shader.
  21438. *
  21439. * @type {LightsNode}
  21440. */
  21441. this.lightsNode = lighting.getNode( scene, camera );
  21442. /**
  21443. * The scene's lights stored in an array. This array
  21444. * is used to setup the lights node.
  21445. *
  21446. * @type {Array<Light>}
  21447. */
  21448. this.lightsArray = [];
  21449. /**
  21450. * The scene.
  21451. *
  21452. * @type {Scene}
  21453. */
  21454. this.scene = scene;
  21455. /**
  21456. * The camera the scene is rendered with.
  21457. *
  21458. * @type {Camera}
  21459. */
  21460. this.camera = camera;
  21461. /**
  21462. * How many objects perform occlusion query tests.
  21463. *
  21464. * @type {number}
  21465. * @default 0
  21466. */
  21467. this.occlusionQueryCount = 0;
  21468. }
  21469. /**
  21470. * This method is called right at the beginning of a render call
  21471. * before the scene is analyzed. It prepares the internal data
  21472. * structures for the upcoming render lists generation.
  21473. *
  21474. * @return {RenderList} A reference to this render list.
  21475. */
  21476. begin() {
  21477. this.renderItemsIndex = 0;
  21478. this.opaque.length = 0;
  21479. this.transparentDoublePass.length = 0;
  21480. this.transparent.length = 0;
  21481. this.bundles.length = 0;
  21482. this.lightsArray.length = 0;
  21483. this.occlusionQueryCount = 0;
  21484. return this;
  21485. }
  21486. /**
  21487. * Returns a render item for the giving render item state. The state is defined
  21488. * by a series of object-related parameters.
  21489. *
  21490. * The method avoids object creation by holding render items and reusing them in
  21491. * subsequent render calls (just with different property values).
  21492. *
  21493. * @param {Object3D} object - The 3D object.
  21494. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21495. * @param {Material} material - The 3D object's material.
  21496. * @param {number} groupOrder - The current group order.
  21497. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21498. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21499. * @param {ClippingContext} clippingContext - The current clipping context.
  21500. * @return {Object} The render item.
  21501. */
  21502. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21503. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21504. if ( renderItem === undefined ) {
  21505. renderItem = {
  21506. id: object.id,
  21507. object: object,
  21508. geometry: geometry,
  21509. material: material,
  21510. groupOrder: groupOrder,
  21511. renderOrder: object.renderOrder,
  21512. z: z,
  21513. group: group,
  21514. clippingContext: clippingContext
  21515. };
  21516. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21517. } else {
  21518. renderItem.id = object.id;
  21519. renderItem.object = object;
  21520. renderItem.geometry = geometry;
  21521. renderItem.material = material;
  21522. renderItem.groupOrder = groupOrder;
  21523. renderItem.renderOrder = object.renderOrder;
  21524. renderItem.z = z;
  21525. renderItem.group = group;
  21526. renderItem.clippingContext = clippingContext;
  21527. }
  21528. this.renderItemsIndex ++;
  21529. return renderItem;
  21530. }
  21531. /**
  21532. * Pushes the given object as a render item to the internal render lists.
  21533. * The selected lists depend on the object properties.
  21534. *
  21535. * @param {Object3D} object - The 3D object.
  21536. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21537. * @param {Material} material - The 3D object's material.
  21538. * @param {number} groupOrder - The current group order.
  21539. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21540. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21541. * @param {ClippingContext} clippingContext - The current clipping context.
  21542. */
  21543. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21544. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21545. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21546. if ( material.transparent === true || material.transmission > 0 ) {
  21547. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21548. this.transparent.push( renderItem );
  21549. } else {
  21550. this.opaque.push( renderItem );
  21551. }
  21552. }
  21553. /**
  21554. * Inserts the given object as a render item at the start of the internal render lists.
  21555. * The selected lists depend on the object properties.
  21556. *
  21557. * @param {Object3D} object - The 3D object.
  21558. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21559. * @param {Material} material - The 3D object's material.
  21560. * @param {number} groupOrder - The current group order.
  21561. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21562. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21563. * @param {ClippingContext} clippingContext - The current clipping context.
  21564. */
  21565. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21566. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21567. if ( material.transparent === true || material.transmission > 0 ) {
  21568. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21569. this.transparent.unshift( renderItem );
  21570. } else {
  21571. this.opaque.unshift( renderItem );
  21572. }
  21573. }
  21574. /**
  21575. * Pushes render bundle group data into the render list.
  21576. *
  21577. * @param {Object} group - Bundle group data.
  21578. */
  21579. pushBundle( group ) {
  21580. this.bundles.push( group );
  21581. }
  21582. /**
  21583. * Pushes a light into the render list.
  21584. *
  21585. * @param {Light} light - The light.
  21586. */
  21587. pushLight( light ) {
  21588. this.lightsArray.push( light );
  21589. }
  21590. /**
  21591. * Sorts the internal render lists.
  21592. *
  21593. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  21594. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  21595. */
  21596. sort( customOpaqueSort, customTransparentSort ) {
  21597. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  21598. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  21599. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  21600. }
  21601. /**
  21602. * This method performs finalizing tasks right after the render lists
  21603. * have been generated.
  21604. */
  21605. finish() {
  21606. // update lights
  21607. this.lightsNode.setLights( this.lightsArray );
  21608. // Clear references from inactive renderItems in the list
  21609. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  21610. const renderItem = this.renderItems[ i ];
  21611. if ( renderItem.id === null ) break;
  21612. renderItem.id = null;
  21613. renderItem.object = null;
  21614. renderItem.geometry = null;
  21615. renderItem.material = null;
  21616. renderItem.groupOrder = null;
  21617. renderItem.renderOrder = null;
  21618. renderItem.z = null;
  21619. renderItem.group = null;
  21620. renderItem.clippingContext = null;
  21621. }
  21622. }
  21623. }
  21624. const _chainKeys$4 = [];
  21625. /**
  21626. * This renderer module manages the render lists which are unique
  21627. * per scene and camera combination.
  21628. *
  21629. * @private
  21630. */
  21631. class RenderLists {
  21632. /**
  21633. * Constructs a render lists management component.
  21634. *
  21635. * @param {Lighting} lighting - The lighting management component.
  21636. */
  21637. constructor( lighting ) {
  21638. /**
  21639. * The lighting management component.
  21640. *
  21641. * @type {Lighting}
  21642. */
  21643. this.lighting = lighting;
  21644. /**
  21645. * The internal chain map which holds the render lists.
  21646. *
  21647. * @type {ChainMap}
  21648. */
  21649. this.lists = new ChainMap();
  21650. }
  21651. /**
  21652. * Returns a render list for the given scene and camera.
  21653. *
  21654. * @param {Scene} scene - The scene.
  21655. * @param {Camera} camera - The camera.
  21656. * @return {RenderList} The render list.
  21657. */
  21658. get( scene, camera ) {
  21659. const lists = this.lists;
  21660. _chainKeys$4[ 0 ] = scene;
  21661. _chainKeys$4[ 1 ] = camera;
  21662. let list = lists.get( _chainKeys$4 );
  21663. if ( list === undefined ) {
  21664. list = new RenderList( this.lighting, scene, camera );
  21665. lists.set( _chainKeys$4, list );
  21666. }
  21667. _chainKeys$4.length = 0;
  21668. return list;
  21669. }
  21670. /**
  21671. * Frees all internal resources.
  21672. */
  21673. dispose() {
  21674. this.lists = new ChainMap();
  21675. }
  21676. }
  21677. let _id$7 = 0;
  21678. /**
  21679. * Any render or compute command is executed in a specific context that defines
  21680. * the state of the renderer and its backend. Typical examples for such context
  21681. * data are the current clear values or data from the active framebuffer. This
  21682. * module is used to represent these contexts as objects.
  21683. *
  21684. * @private
  21685. */
  21686. class RenderContext {
  21687. /**
  21688. * Constructs a new render context.
  21689. */
  21690. constructor() {
  21691. /**
  21692. * The context's ID.
  21693. *
  21694. * @type {number}
  21695. */
  21696. this.id = _id$7 ++;
  21697. /**
  21698. * Whether the current active framebuffer has a color attachment.
  21699. *
  21700. * @type {boolean}
  21701. * @default true
  21702. */
  21703. this.color = true;
  21704. /**
  21705. * Whether the color attachment should be cleared or not.
  21706. *
  21707. * @type {boolean}
  21708. * @default true
  21709. */
  21710. this.clearColor = true;
  21711. /**
  21712. * The clear color value.
  21713. *
  21714. * @type {Object}
  21715. * @default true
  21716. */
  21717. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  21718. /**
  21719. * Whether the current active framebuffer has a depth attachment.
  21720. *
  21721. * @type {boolean}
  21722. * @default true
  21723. */
  21724. this.depth = true;
  21725. /**
  21726. * Whether the depth attachment should be cleared or not.
  21727. *
  21728. * @type {boolean}
  21729. * @default true
  21730. */
  21731. this.clearDepth = true;
  21732. /**
  21733. * The clear depth value.
  21734. *
  21735. * @type {number}
  21736. * @default 1
  21737. */
  21738. this.clearDepthValue = 1;
  21739. /**
  21740. * Whether the current active framebuffer has a stencil attachment.
  21741. *
  21742. * @type {boolean}
  21743. * @default false
  21744. */
  21745. this.stencil = false;
  21746. /**
  21747. * Whether the stencil attachment should be cleared or not.
  21748. *
  21749. * @type {boolean}
  21750. * @default true
  21751. */
  21752. this.clearStencil = true;
  21753. /**
  21754. * The clear stencil value.
  21755. *
  21756. * @type {number}
  21757. * @default 1
  21758. */
  21759. this.clearStencilValue = 1;
  21760. /**
  21761. * By default the viewport encloses the entire framebuffer If a smaller
  21762. * viewport is manually defined, this property is to `true` by the renderer.
  21763. *
  21764. * @type {boolean}
  21765. * @default false
  21766. */
  21767. this.viewport = false;
  21768. /**
  21769. * The viewport value. This value is in physical pixels meaning it incorporates
  21770. * the renderer's pixel ratio. The viewport property of render targets or
  21771. * the renderer is in logical pixels.
  21772. *
  21773. * @type {Vector4}
  21774. */
  21775. this.viewportValue = new Vector4();
  21776. /**
  21777. * When the scissor test is active and scissor rectangle smaller than the
  21778. * framebuffers dimensions, this property is to `true` by the renderer.
  21779. *
  21780. * @type {boolean}
  21781. * @default false
  21782. */
  21783. this.scissor = false;
  21784. /**
  21785. * The scissor rectangle.
  21786. *
  21787. * @type {Vector4}
  21788. */
  21789. this.scissorValue = new Vector4();
  21790. /**
  21791. * The active render target.
  21792. *
  21793. * @type {?RenderTarget}
  21794. * @default null
  21795. */
  21796. this.renderTarget = null;
  21797. /**
  21798. * The textures of the active render target.
  21799. * `null` when no render target is set.
  21800. *
  21801. * @type {?Array<Texture>}
  21802. * @default null
  21803. */
  21804. this.textures = null;
  21805. /**
  21806. * The depth texture of the active render target.
  21807. * `null` when no render target is set.
  21808. *
  21809. * @type {?DepthTexture}
  21810. * @default null
  21811. */
  21812. this.depthTexture = null;
  21813. /**
  21814. * The active cube face.
  21815. *
  21816. * @type {number}
  21817. * @default 0
  21818. */
  21819. this.activeCubeFace = 0;
  21820. /**
  21821. * The active mipmap level.
  21822. *
  21823. * @type {number}
  21824. * @default 0
  21825. */
  21826. this.activeMipmapLevel = 0;
  21827. /**
  21828. * The number of MSAA samples. This value is always `1` when
  21829. * MSAA isn't used.
  21830. *
  21831. * @type {number}
  21832. * @default 1
  21833. */
  21834. this.sampleCount = 1;
  21835. /**
  21836. * The active render target's width in physical pixels.
  21837. *
  21838. * @type {number}
  21839. * @default 0
  21840. */
  21841. this.width = 0;
  21842. /**
  21843. * The active render target's height in physical pixels.
  21844. *
  21845. * @type {number}
  21846. * @default 0
  21847. */
  21848. this.height = 0;
  21849. /**
  21850. * The occlusion query count.
  21851. *
  21852. * @type {number}
  21853. * @default 0
  21854. */
  21855. this.occlusionQueryCount = 0;
  21856. /**
  21857. * The current clipping context.
  21858. *
  21859. * @type {?ClippingContext}
  21860. * @default null
  21861. */
  21862. this.clippingContext = null;
  21863. /**
  21864. * This flag can be used for type testing.
  21865. *
  21866. * @type {boolean}
  21867. * @readonly
  21868. * @default true
  21869. */
  21870. this.isRenderContext = true;
  21871. }
  21872. /**
  21873. * Returns the cache key of this render context.
  21874. *
  21875. * @return {number} The cache key.
  21876. */
  21877. getCacheKey() {
  21878. return getCacheKey( this );
  21879. }
  21880. }
  21881. /**
  21882. * Computes a cache key for the given render context. This key
  21883. * should identify the render target state so it is possible to
  21884. * configure the correct attachments in the respective backend.
  21885. *
  21886. * @param {RenderContext} renderContext - The render context.
  21887. * @return {number} The cache key.
  21888. */
  21889. function getCacheKey( renderContext ) {
  21890. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  21891. const values = [ activeCubeFace, activeMipmapLevel ];
  21892. for ( const texture of textures ) {
  21893. values.push( texture.id );
  21894. }
  21895. return hashArray( values );
  21896. }
  21897. const _chainKeys$3 = [];
  21898. const _defaultScene = /*@__PURE__*/ new Scene();
  21899. const _defaultCamera = /*@__PURE__*/ new Camera();
  21900. /**
  21901. * This module manages the render contexts of the renderer.
  21902. *
  21903. * @private
  21904. */
  21905. class RenderContexts {
  21906. /**
  21907. * Constructs a new render context management component.
  21908. */
  21909. constructor() {
  21910. /**
  21911. * A dictionary that manages render contexts in chain maps
  21912. * for each attachment state.
  21913. *
  21914. * @type {Object<string,ChainMap>}
  21915. */
  21916. this.chainMaps = {};
  21917. }
  21918. /**
  21919. * Returns a render context for the given scene, camera and render target.
  21920. *
  21921. * @param {Scene} scene - The scene.
  21922. * @param {Camera} camera - The camera that is used to render the scene.
  21923. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21924. * @return {RenderContext} The render context.
  21925. */
  21926. get( scene, camera, renderTarget = null ) {
  21927. _chainKeys$3[ 0 ] = scene;
  21928. _chainKeys$3[ 1 ] = camera;
  21929. let attachmentState;
  21930. if ( renderTarget === null ) {
  21931. attachmentState = 'default';
  21932. } else {
  21933. const format = renderTarget.texture.format;
  21934. const count = renderTarget.textures.length;
  21935. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  21936. }
  21937. const chainMap = this._getChainMap( attachmentState );
  21938. let renderState = chainMap.get( _chainKeys$3 );
  21939. if ( renderState === undefined ) {
  21940. renderState = new RenderContext();
  21941. chainMap.set( _chainKeys$3, renderState );
  21942. }
  21943. _chainKeys$3.length = 0;
  21944. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21945. return renderState;
  21946. }
  21947. /**
  21948. * Returns a render context intended for clear operations.
  21949. *
  21950. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21951. * @return {RenderContext} The render context.
  21952. */
  21953. getForClear( renderTarget = null ) {
  21954. return this.get( _defaultScene, _defaultCamera, renderTarget );
  21955. }
  21956. /**
  21957. * Returns a chain map for the given attachment state.
  21958. *
  21959. * @private
  21960. * @param {string} attachmentState - The attachment state.
  21961. * @return {ChainMap} The chain map.
  21962. */
  21963. _getChainMap( attachmentState ) {
  21964. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  21965. }
  21966. /**
  21967. * Frees internal resources.
  21968. */
  21969. dispose() {
  21970. this.chainMaps = {};
  21971. }
  21972. }
  21973. const _size$3 = /*@__PURE__*/ new Vector3();
  21974. /**
  21975. * This module manages the textures of the renderer.
  21976. *
  21977. * @private
  21978. * @augments DataMap
  21979. */
  21980. class Textures extends DataMap {
  21981. /**
  21982. * Constructs a new texture management component.
  21983. *
  21984. * @param {Renderer} renderer - The renderer.
  21985. * @param {Backend} backend - The renderer's backend.
  21986. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21987. */
  21988. constructor( renderer, backend, info ) {
  21989. super();
  21990. /**
  21991. * The renderer.
  21992. *
  21993. * @type {Renderer}
  21994. */
  21995. this.renderer = renderer;
  21996. /**
  21997. * The backend.
  21998. *
  21999. * @type {Backend}
  22000. */
  22001. this.backend = backend;
  22002. /**
  22003. * Renderer component for managing metrics and monitoring data.
  22004. *
  22005. * @type {Info}
  22006. */
  22007. this.info = info;
  22008. }
  22009. /**
  22010. * Updates the given render target. Based on the given render target configuration,
  22011. * it updates the texture states representing the attachments of the framebuffer.
  22012. *
  22013. * @param {RenderTarget} renderTarget - The render target to update.
  22014. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  22015. */
  22016. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  22017. const renderTargetData = this.get( renderTarget );
  22018. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  22019. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  22020. const textures = renderTarget.textures;
  22021. const size = this.getSize( textures[ 0 ] );
  22022. const mipWidth = size.width >> activeMipmapLevel;
  22023. const mipHeight = size.height >> activeMipmapLevel;
  22024. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  22025. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  22026. let textureNeedsUpdate = false;
  22027. if ( depthTexture === undefined && useDepthTexture ) {
  22028. depthTexture = new DepthTexture();
  22029. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  22030. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  22031. depthTexture.image.width = mipWidth;
  22032. depthTexture.image.height = mipHeight;
  22033. depthTexture.image.depth = size.depth;
  22034. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22035. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22036. }
  22037. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22038. textureNeedsUpdate = true;
  22039. if ( depthTexture ) {
  22040. depthTexture.needsUpdate = true;
  22041. depthTexture.image.width = mipWidth;
  22042. depthTexture.image.height = mipHeight;
  22043. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22044. }
  22045. }
  22046. renderTargetData.width = size.width;
  22047. renderTargetData.height = size.height;
  22048. renderTargetData.textures = textures;
  22049. renderTargetData.depthTexture = depthTexture || null;
  22050. renderTargetData.depth = renderTarget.depthBuffer;
  22051. renderTargetData.stencil = renderTarget.stencilBuffer;
  22052. renderTargetData.renderTarget = renderTarget;
  22053. if ( renderTargetData.sampleCount !== sampleCount ) {
  22054. textureNeedsUpdate = true;
  22055. if ( depthTexture ) {
  22056. depthTexture.needsUpdate = true;
  22057. }
  22058. renderTargetData.sampleCount = sampleCount;
  22059. }
  22060. //
  22061. const options = { sampleCount };
  22062. // XR render targets require no texture updates
  22063. if ( renderTarget.isXRRenderTarget !== true ) {
  22064. for ( let i = 0; i < textures.length; i ++ ) {
  22065. const texture = textures[ i ];
  22066. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22067. this.updateTexture( texture, options );
  22068. }
  22069. if ( depthTexture ) {
  22070. this.updateTexture( depthTexture, options );
  22071. }
  22072. }
  22073. // dispose handler
  22074. if ( renderTargetData.initialized !== true ) {
  22075. renderTargetData.initialized = true;
  22076. // dispose
  22077. const onDispose = () => {
  22078. renderTarget.removeEventListener( 'dispose', onDispose );
  22079. for ( let i = 0; i < textures.length; i ++ ) {
  22080. this._destroyTexture( textures[ i ] );
  22081. }
  22082. if ( depthTexture ) {
  22083. this._destroyTexture( depthTexture );
  22084. }
  22085. this.delete( renderTarget );
  22086. this.backend.delete( renderTarget );
  22087. };
  22088. renderTarget.addEventListener( 'dispose', onDispose );
  22089. }
  22090. }
  22091. /**
  22092. * Updates the given texture. Depending on the texture state, this method
  22093. * triggers the upload of texture data to the GPU memory. If the texture data are
  22094. * not yet ready for the upload, it uses default texture data for as a placeholder.
  22095. *
  22096. * @param {Texture} texture - The texture to update.
  22097. * @param {Object} [options={}] - The options.
  22098. */
  22099. updateTexture( texture, options = {} ) {
  22100. const textureData = this.get( texture );
  22101. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  22102. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  22103. const backend = this.backend;
  22104. if ( isRenderTarget && textureData.initialized === true ) {
  22105. // it's an update
  22106. backend.destroySampler( texture );
  22107. backend.destroyTexture( texture );
  22108. }
  22109. //
  22110. if ( texture.isFramebufferTexture ) {
  22111. const renderTarget = this.renderer.getRenderTarget();
  22112. if ( renderTarget ) {
  22113. texture.type = renderTarget.texture.type;
  22114. } else {
  22115. texture.type = UnsignedByteType;
  22116. }
  22117. }
  22118. //
  22119. const { width, height, depth } = this.getSize( texture );
  22120. options.width = width;
  22121. options.height = height;
  22122. options.depth = depth;
  22123. options.needsMipmaps = this.needsMipmaps( texture );
  22124. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  22125. // TODO: Uniformly handle mipmap definitions
  22126. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  22127. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  22128. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  22129. //
  22130. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  22131. backend.createSampler( texture );
  22132. backend.createTexture( texture, options );
  22133. textureData.generation = texture.version;
  22134. } else {
  22135. const needsCreate = textureData.initialized !== true;
  22136. if ( needsCreate ) backend.createSampler( texture );
  22137. if ( texture.version > 0 ) {
  22138. const image = texture.image;
  22139. if ( image === undefined ) {
  22140. warn( 'Renderer: Texture marked for update but image is undefined.' );
  22141. } else if ( image.complete === false ) {
  22142. warn( 'Renderer: Texture marked for update but image is incomplete.' );
  22143. } else {
  22144. if ( texture.images ) {
  22145. const images = [];
  22146. for ( const image of texture.images ) {
  22147. images.push( image );
  22148. }
  22149. options.images = images;
  22150. } else {
  22151. options.image = image;
  22152. }
  22153. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  22154. backend.createTexture( texture, options );
  22155. textureData.isDefaultTexture = false;
  22156. textureData.generation = texture.version;
  22157. }
  22158. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  22159. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  22160. if ( texture.onUpdate ) texture.onUpdate( texture );
  22161. }
  22162. } else {
  22163. // async update
  22164. backend.createDefaultTexture( texture );
  22165. textureData.isDefaultTexture = true;
  22166. textureData.generation = texture.version;
  22167. }
  22168. }
  22169. // dispose handler
  22170. if ( textureData.initialized !== true ) {
  22171. textureData.initialized = true;
  22172. textureData.generation = texture.version;
  22173. //
  22174. this.info.memory.textures ++;
  22175. //
  22176. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  22177. warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  22178. }
  22179. // dispose
  22180. const onDispose = () => {
  22181. texture.removeEventListener( 'dispose', onDispose );
  22182. this._destroyTexture( texture );
  22183. };
  22184. texture.addEventListener( 'dispose', onDispose );
  22185. }
  22186. //
  22187. textureData.version = texture.version;
  22188. }
  22189. /**
  22190. * Computes the size of the given texture and writes the result
  22191. * into the target vector. This vector is also returned by the
  22192. * method.
  22193. *
  22194. * If no texture data are available for the compute yet, the method
  22195. * returns default size values.
  22196. *
  22197. * @param {Texture} texture - The texture to compute the size for.
  22198. * @param {Vector3} target - The target vector.
  22199. * @return {Vector3} The target vector.
  22200. */
  22201. getSize( texture, target = _size$3 ) {
  22202. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22203. if ( image ) {
  22204. if ( image.image !== undefined ) image = image.image;
  22205. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22206. target.width = image.videoWidth || 1;
  22207. target.height = image.videoHeight || 1;
  22208. target.depth = 1;
  22209. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( image instanceof VideoFrame ) ) {
  22210. target.width = image.displayWidth || 1;
  22211. target.height = image.displayHeight || 1;
  22212. target.depth = 1;
  22213. } else {
  22214. target.width = image.width || 1;
  22215. target.height = image.height || 1;
  22216. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22217. }
  22218. } else {
  22219. target.width = target.height = target.depth = 1;
  22220. }
  22221. return target;
  22222. }
  22223. /**
  22224. * Computes the number of mipmap levels for the given texture.
  22225. *
  22226. * @param {Texture} texture - The texture.
  22227. * @param {number} width - The texture's width.
  22228. * @param {number} height - The texture's height.
  22229. * @return {number} The number of mipmap levels.
  22230. */
  22231. getMipLevels( texture, width, height ) {
  22232. let mipLevelCount;
  22233. if ( texture.mipmaps.length > 0 ) {
  22234. mipLevelCount = texture.mipmaps.length;
  22235. } else {
  22236. if ( texture.isCompressedTexture === true ) {
  22237. // it is not possible to compute mipmaps for compressed textures. So
  22238. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22239. // level of 1
  22240. mipLevelCount = 1;
  22241. } else {
  22242. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22243. }
  22244. }
  22245. return mipLevelCount;
  22246. }
  22247. /**
  22248. * Returns `true` if the given texture makes use of mipmapping.
  22249. *
  22250. * @param {Texture} texture - The texture.
  22251. * @return {boolean} Whether mipmaps are required or not.
  22252. */
  22253. needsMipmaps( texture ) {
  22254. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  22255. }
  22256. /**
  22257. * Frees internal resource when the given texture isn't
  22258. * required anymore.
  22259. *
  22260. * @param {Texture} texture - The texture to destroy.
  22261. */
  22262. _destroyTexture( texture ) {
  22263. if ( this.has( texture ) === true ) {
  22264. // if a texture is not ready for use, it falls back to a default texture so it's possible
  22265. // to use it for rendering. If a texture in this state is disposed, it's important to
  22266. // not destroy/delete the underlying GPU texture object since it is cached and shared with
  22267. // other textures.
  22268. const isDefaultTexture = this.get( texture ).isDefaultTexture;
  22269. this.backend.destroySampler( texture );
  22270. this.backend.destroyTexture( texture, isDefaultTexture );
  22271. this.delete( texture );
  22272. this.info.memory.textures --;
  22273. }
  22274. }
  22275. }
  22276. /**
  22277. * A four-component version of {@link Color} which is internally
  22278. * used by the renderer to represents clear color with alpha as
  22279. * one object.
  22280. *
  22281. * @private
  22282. * @augments Color
  22283. */
  22284. class Color4 extends Color {
  22285. /**
  22286. * Constructs a new four-component color.
  22287. * You can also pass a single THREE.Color, hex or
  22288. * string argument to this constructor.
  22289. *
  22290. * @param {number|string} [r=1] - The red value.
  22291. * @param {number} [g=1] - The green value.
  22292. * @param {number} [b=1] - The blue value.
  22293. * @param {number} [a=1] - The alpha value.
  22294. */
  22295. constructor( r, g, b, a = 1 ) {
  22296. super( r, g, b );
  22297. this.a = a;
  22298. }
  22299. /**
  22300. * Overwrites the default to honor alpha.
  22301. * You can also pass a single THREE.Color, hex or
  22302. * string argument to this method.
  22303. *
  22304. * @param {number|string|Color} r - The red value.
  22305. * @param {number} [g] - The green value.
  22306. * @param {number} [b] - The blue value.
  22307. * @param {number} [a=1] - The alpha value.
  22308. * @return {Color4} A reference to this object.
  22309. */
  22310. set( r, g, b, a = 1 ) {
  22311. this.a = a;
  22312. return super.set( r, g, b );
  22313. }
  22314. /**
  22315. * Overwrites the default to honor alpha.
  22316. *
  22317. * @param {Color4} color - The color to copy.
  22318. * @return {Color4} A reference to this object.
  22319. */
  22320. copy( color ) {
  22321. if ( color.a !== undefined ) this.a = color.a;
  22322. return super.copy( color );
  22323. }
  22324. /**
  22325. * Overwrites the default to honor alpha.
  22326. *
  22327. * @return {Color4} The cloned color.
  22328. */
  22329. clone() {
  22330. return new this.constructor( this.r, this.g, this.b, this.a );
  22331. }
  22332. }
  22333. /**
  22334. * Special version of {@link PropertyNode} which is used for parameters.
  22335. *
  22336. * @augments PropertyNode
  22337. */
  22338. class ParameterNode extends PropertyNode {
  22339. static get type() {
  22340. return 'ParameterNode';
  22341. }
  22342. /**
  22343. * Constructs a new parameter node.
  22344. *
  22345. * @param {string} nodeType - The type of the node.
  22346. * @param {?string} [name=null] - The name of the parameter in the shader.
  22347. */
  22348. constructor( nodeType, name = null ) {
  22349. super( nodeType, name );
  22350. /**
  22351. * This flag can be used for type testing.
  22352. *
  22353. * @type {boolean}
  22354. * @readonly
  22355. * @default true
  22356. */
  22357. this.isParameterNode = true;
  22358. }
  22359. /**
  22360. * Gets the type of a member variable in the parameter node.
  22361. *
  22362. * @param {NodeBuilder} builder - The node builder.
  22363. * @param {string} name - The name of the member variable.
  22364. * @returns {string}
  22365. */
  22366. getMemberType( builder, name ) {
  22367. const type = this.getNodeType( builder );
  22368. const struct = builder.getStructTypeNode( type );
  22369. let memberType;
  22370. if ( struct !== null ) {
  22371. memberType = struct.getMemberType( builder, name );
  22372. } else {
  22373. error( `TSL: Member "${ name }" not found in struct "${ type }".` );
  22374. memberType = 'float';
  22375. }
  22376. return memberType;
  22377. }
  22378. getHash() {
  22379. return this.uuid;
  22380. }
  22381. generate() {
  22382. return this.name;
  22383. }
  22384. }
  22385. /**
  22386. * TSL function for creating a parameter node.
  22387. *
  22388. * @tsl
  22389. * @function
  22390. * @param {string} type - The type of the node.
  22391. * @param {?string} name - The name of the parameter in the shader.
  22392. * @returns {ParameterNode}
  22393. */
  22394. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  22395. /**
  22396. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  22397. * They are usually needed in cases like `If`, `Else`.
  22398. *
  22399. * @augments Node
  22400. */
  22401. class StackNode extends Node {
  22402. static get type() {
  22403. return 'StackNode';
  22404. }
  22405. /**
  22406. * Constructs a new stack node.
  22407. *
  22408. * @param {?StackNode} [parent=null] - The parent stack node.
  22409. */
  22410. constructor( parent = null ) {
  22411. super();
  22412. /**
  22413. * List of nodes.
  22414. *
  22415. * @type {Array<Node>}
  22416. */
  22417. this.nodes = [];
  22418. /**
  22419. * The output node.
  22420. *
  22421. * @type {?Node}
  22422. * @default null
  22423. */
  22424. this.outputNode = null;
  22425. /**
  22426. * The parent stack node.
  22427. *
  22428. * @type {?StackNode}
  22429. * @default null
  22430. */
  22431. this.parent = parent;
  22432. /**
  22433. * The current conditional node.
  22434. *
  22435. * @private
  22436. * @type {ConditionalNode}
  22437. * @default null
  22438. */
  22439. this._currentCond = null;
  22440. /**
  22441. * The expression node. Only
  22442. * relevant for Switch/Case.
  22443. *
  22444. * @private
  22445. * @type {Node}
  22446. * @default null
  22447. */
  22448. this._expressionNode = null;
  22449. /**
  22450. * This flag can be used for type testing.
  22451. *
  22452. * @type {boolean}
  22453. * @readonly
  22454. * @default true
  22455. */
  22456. this.isStackNode = true;
  22457. }
  22458. getNodeType( builder ) {
  22459. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  22460. }
  22461. getMemberType( builder, name ) {
  22462. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  22463. }
  22464. /**
  22465. * Adds a node to this stack.
  22466. *
  22467. * @param {Node} node - The node to add.
  22468. * @return {StackNode} A reference to this stack node.
  22469. */
  22470. add( node ) {
  22471. if ( node.isNode !== true ) {
  22472. error( 'TSL: Invalid node added to stack.' );
  22473. return this;
  22474. }
  22475. this.nodes.push( node );
  22476. return this;
  22477. }
  22478. /**
  22479. * Represent an `if` statement in TSL.
  22480. *
  22481. * @param {Node} boolNode - Represents the condition.
  22482. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22483. * @return {StackNode} A reference to this stack node.
  22484. */
  22485. If( boolNode, method ) {
  22486. const methodNode = new ShaderNode( method );
  22487. this._currentCond = select( boolNode, methodNode );
  22488. return this.add( this._currentCond );
  22489. }
  22490. /**
  22491. * Represent an `elseif` statement in TSL.
  22492. *
  22493. * @param {Node} boolNode - Represents the condition.
  22494. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22495. * @return {StackNode} A reference to this stack node.
  22496. */
  22497. ElseIf( boolNode, method ) {
  22498. const methodNode = new ShaderNode( method );
  22499. const ifNode = select( boolNode, methodNode );
  22500. this._currentCond.elseNode = ifNode;
  22501. this._currentCond = ifNode;
  22502. return this;
  22503. }
  22504. /**
  22505. * Represent an `else` statement in TSL.
  22506. *
  22507. * @param {Function} method - TSL code which is executed in the `else` case.
  22508. * @return {StackNode} A reference to this stack node.
  22509. */
  22510. Else( method ) {
  22511. this._currentCond.elseNode = new ShaderNode( method );
  22512. return this;
  22513. }
  22514. /**
  22515. * Represents a `switch` statement in TSL.
  22516. *
  22517. * @param {any} expression - Represents the expression.
  22518. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22519. * @return {StackNode} A reference to this stack node.
  22520. */
  22521. Switch( expression ) {
  22522. this._expressionNode = nodeObject( expression );
  22523. return this;
  22524. }
  22525. /**
  22526. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22527. * The last parameter must be the callback method that should be executed in the `true` case.
  22528. *
  22529. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22530. * @return {StackNode} A reference to this stack node.
  22531. */
  22532. Case( ...params ) {
  22533. const caseNodes = [];
  22534. // extract case nodes from the parameter list
  22535. if ( params.length >= 2 ) {
  22536. for ( let i = 0; i < params.length - 1; i ++ ) {
  22537. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22538. }
  22539. } else {
  22540. error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22541. }
  22542. // extract method
  22543. const method = params[ params.length - 1 ];
  22544. const methodNode = new ShaderNode( method );
  22545. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22546. let caseNode = caseNodes[ 0 ];
  22547. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22548. caseNode = caseNode.or( caseNodes[ i ] );
  22549. }
  22550. // build condition
  22551. const condNode = select( caseNode, methodNode );
  22552. if ( this._currentCond === null ) {
  22553. this._currentCond = condNode;
  22554. return this.add( this._currentCond );
  22555. } else {
  22556. this._currentCond.elseNode = condNode;
  22557. this._currentCond = condNode;
  22558. return this;
  22559. }
  22560. }
  22561. /**
  22562. * Represents the default code block of a Switch/Case statement.
  22563. *
  22564. * @param {Function} method - TSL code which is executed in the `else` case.
  22565. * @return {StackNode} A reference to this stack node.
  22566. */
  22567. Default( method ) {
  22568. this.Else( method );
  22569. return this;
  22570. }
  22571. setup( builder ) {
  22572. const nodeProperties = builder.getNodeProperties( this );
  22573. let index = 0;
  22574. for ( const childNode of this.getChildren() ) {
  22575. if ( childNode.isVarNode && childNode.intent === true ) {
  22576. const properties = builder.getNodeProperties( childNode );
  22577. if ( properties.assign !== true ) {
  22578. continue;
  22579. }
  22580. }
  22581. nodeProperties[ 'node' + index ++ ] = childNode;
  22582. }
  22583. // return a outputNode if exists or null
  22584. return nodeProperties.outputNode || null;
  22585. }
  22586. get hasOutput() {
  22587. return this.outputNode && this.outputNode.isNode;
  22588. }
  22589. build( builder, ...params ) {
  22590. const previousBuildStack = builder.currentStack;
  22591. const previousStack = getCurrentStack();
  22592. setCurrentStack( this );
  22593. builder.currentStack = this;
  22594. const buildStage = builder.buildStage;
  22595. for ( const node of this.nodes ) {
  22596. if ( node.isVarNode && node.intent === true ) {
  22597. const properties = builder.getNodeProperties( node );
  22598. if ( properties.assign !== true ) {
  22599. continue;
  22600. }
  22601. }
  22602. if ( buildStage === 'setup' ) {
  22603. node.build( builder );
  22604. } else if ( buildStage === 'analyze' ) {
  22605. node.build( builder, this );
  22606. } else if ( buildStage === 'generate' ) {
  22607. const stages = builder.getDataFromNode( node, 'any' ).stages;
  22608. const parents = stages && stages[ builder.shaderStage ];
  22609. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  22610. continue; // skip var nodes that are only used in .toVarying()
  22611. }
  22612. node.build( builder, 'void' );
  22613. }
  22614. }
  22615. //
  22616. let result;
  22617. if ( this.hasOutput ) {
  22618. result = this.outputNode.build( builder, ...params );
  22619. } else {
  22620. result = super.build( builder, ...params );
  22621. }
  22622. setCurrentStack( previousStack );
  22623. builder.currentStack = previousBuildStack;
  22624. return result;
  22625. }
  22626. }
  22627. /**
  22628. * TSL function for creating a stack node.
  22629. *
  22630. * @tsl
  22631. * @function
  22632. * @param {?StackNode} [parent=null] - The parent stack node.
  22633. * @returns {StackNode}
  22634. */
  22635. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  22636. /**
  22637. * Generates a layout for struct members.
  22638. * This function takes an object representing struct members and returns an array of member layouts.
  22639. * Each member layout includes the member's name, type, and whether it is atomic.
  22640. *
  22641. * @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.
  22642. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  22643. */
  22644. function getMembersLayout( members ) {
  22645. return Object.entries( members ).map( ( [ name, value ] ) => {
  22646. if ( typeof value === 'string' ) {
  22647. return { name, type: value, atomic: false };
  22648. }
  22649. return { name, type: value.type, atomic: value.atomic || false };
  22650. } );
  22651. }
  22652. /**
  22653. * Represents a struct type node in the node-based system.
  22654. * This class is used to define and manage the layout and types of struct members.
  22655. * It extends the base Node class and provides methods to get the length of the struct,
  22656. * retrieve member types, and generate the struct type for a builder.
  22657. *
  22658. * @augments Node
  22659. */
  22660. class StructTypeNode extends Node {
  22661. static get type() {
  22662. return 'StructTypeNode';
  22663. }
  22664. /**
  22665. * Creates an instance of StructTypeNode.
  22666. *
  22667. * @param {Object} membersLayout - The layout of the members for the struct.
  22668. * @param {?string} [name=null] - The optional name of the struct.
  22669. */
  22670. constructor( membersLayout, name = null ) {
  22671. super( 'struct' );
  22672. /**
  22673. * The layout of the members for the struct
  22674. *
  22675. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  22676. */
  22677. this.membersLayout = getMembersLayout( membersLayout );
  22678. /**
  22679. * The name of the struct.
  22680. *
  22681. * @type {?string}
  22682. * @default null
  22683. */
  22684. this.name = name;
  22685. /**
  22686. * This flag can be used for type testing.
  22687. *
  22688. * @type {boolean}
  22689. * @readonly
  22690. * @default true
  22691. */
  22692. this.isStructLayoutNode = true;
  22693. }
  22694. /**
  22695. * Returns the length of the struct.
  22696. * The length is calculated by summing the lengths of the struct's members.
  22697. *
  22698. * @returns {number} The length of the struct.
  22699. */
  22700. getLength() {
  22701. const GPU_CHUNK_BYTES = 8;
  22702. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  22703. let offset = 0; // global buffer offset in bytes
  22704. for ( const member of this.membersLayout ) {
  22705. const type = member.type;
  22706. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  22707. const boundary = getByteBoundaryFromType( type );
  22708. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  22709. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  22710. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  22711. offset += chunkPadding;
  22712. // Check for chunk overflow
  22713. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  22714. // Add padding to the end of the chunk
  22715. offset += ( GPU_CHUNK_BYTES - chunkStart );
  22716. }
  22717. offset += itemSize;
  22718. }
  22719. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  22720. }
  22721. getMemberType( builder, name ) {
  22722. const member = this.membersLayout.find( m => m.name === name );
  22723. return member ? member.type : 'void';
  22724. }
  22725. getNodeType( builder ) {
  22726. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22727. return structType.name;
  22728. }
  22729. setup( builder ) {
  22730. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22731. builder.addInclude( this );
  22732. }
  22733. generate( builder ) {
  22734. return this.getNodeType( builder );
  22735. }
  22736. }
  22737. /**
  22738. * StructNode allows to create custom structures with multiple members.
  22739. * This can also be used to define structures in attribute and uniform data.
  22740. *
  22741. * ```js
  22742. * // Define a custom struct
  22743. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  22744. *
  22745. * // Create a new instance of the struct
  22746. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  22747. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  22748. *
  22749. * // Access the struct members
  22750. * const min = bb.get( 'min' );
  22751. *
  22752. * // Assign a new value to a member
  22753. * min.assign( vec3() );
  22754. * ```
  22755. * @augments Node
  22756. */
  22757. class StructNode extends Node {
  22758. static get type() {
  22759. return 'StructNode';
  22760. }
  22761. constructor( structTypeNode, values ) {
  22762. super( 'vec3' );
  22763. this.structTypeNode = structTypeNode;
  22764. this.values = values;
  22765. this.isStructNode = true;
  22766. }
  22767. getNodeType( builder ) {
  22768. return this.structTypeNode.getNodeType( builder );
  22769. }
  22770. getMemberType( builder, name ) {
  22771. return this.structTypeNode.getMemberType( builder, name );
  22772. }
  22773. generate( builder ) {
  22774. const nodeVar = builder.getVarFromNode( this );
  22775. const structType = nodeVar.type;
  22776. const propertyName = builder.getPropertyName( nodeVar );
  22777. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  22778. return nodeVar.name;
  22779. }
  22780. }
  22781. /**
  22782. * TSL function for creating a struct node.
  22783. *
  22784. * @tsl
  22785. * @function
  22786. * @param {Object} membersLayout - The layout of the struct members.
  22787. * @param {?string} [name=null] - The name of the struct.
  22788. * @returns {Function} The struct function.
  22789. */
  22790. const struct = ( membersLayout, name = null ) => {
  22791. const structLayout = new StructTypeNode( membersLayout, name );
  22792. const struct = ( ...params ) => {
  22793. let values = null;
  22794. if ( params.length > 0 ) {
  22795. if ( params[ 0 ].isNode ) {
  22796. values = {};
  22797. const names = Object.keys( membersLayout );
  22798. for ( let i = 0; i < params.length; i ++ ) {
  22799. values[ names[ i ] ] = params[ i ];
  22800. }
  22801. } else {
  22802. values = params[ 0 ];
  22803. }
  22804. }
  22805. return nodeObject( new StructNode( structLayout, values ) );
  22806. };
  22807. struct.layout = structLayout;
  22808. struct.isStruct = true;
  22809. return struct;
  22810. };
  22811. /**
  22812. * This node can be used to define multiple outputs in a shader programs.
  22813. *
  22814. * @augments Node
  22815. */
  22816. class OutputStructNode extends Node {
  22817. static get type() {
  22818. return 'OutputStructNode';
  22819. }
  22820. /**
  22821. * Constructs a new output struct node. The constructor can be invoked with an
  22822. * arbitrary number of nodes representing the members.
  22823. *
  22824. * @param {...Node} members - A parameter list of nodes.
  22825. */
  22826. constructor( ...members ) {
  22827. super();
  22828. /**
  22829. * An array of nodes which defines the output.
  22830. *
  22831. * @type {Array<Node>}
  22832. */
  22833. this.members = members;
  22834. /**
  22835. * This flag can be used for type testing.
  22836. *
  22837. * @type {boolean}
  22838. * @readonly
  22839. * @default true
  22840. */
  22841. this.isOutputStructNode = true;
  22842. }
  22843. getNodeType( builder ) {
  22844. const properties = builder.getNodeProperties( this );
  22845. if ( properties.membersLayout === undefined ) {
  22846. const members = this.members;
  22847. const membersLayout = [];
  22848. for ( let i = 0; i < members.length; i ++ ) {
  22849. const name = 'm' + i;
  22850. const type = members[ i ].getNodeType( builder );
  22851. membersLayout.push( { name, type, index: i } );
  22852. }
  22853. properties.membersLayout = membersLayout;
  22854. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  22855. }
  22856. return properties.structType.name;
  22857. }
  22858. generate( builder ) {
  22859. const propertyName = builder.getOutputStructName();
  22860. const members = this.members;
  22861. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  22862. for ( let i = 0; i < members.length; i ++ ) {
  22863. const snippet = members[ i ].build( builder );
  22864. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  22865. }
  22866. return propertyName;
  22867. }
  22868. }
  22869. /**
  22870. * TSL function for creating an output struct node.
  22871. *
  22872. * @tsl
  22873. * @function
  22874. * @param {...Node} members - A parameter list of nodes.
  22875. * @returns {OutputStructNode}
  22876. */
  22877. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  22878. /**
  22879. * Returns the MRT texture index for the given name.
  22880. *
  22881. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  22882. * @param {string} name - The name of the MRT texture which index is requested.
  22883. * @return {number} The texture index.
  22884. */
  22885. function getTextureIndex( textures, name ) {
  22886. for ( let i = 0; i < textures.length; i ++ ) {
  22887. if ( textures[ i ].name === name ) {
  22888. return i;
  22889. }
  22890. }
  22891. return -1;
  22892. }
  22893. /**
  22894. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  22895. * post-processing is shown below:
  22896. * ```js
  22897. * const mrtNode = mrt( {
  22898. * output: output,
  22899. * normal: normalView
  22900. * } ) );
  22901. * ```
  22902. * The MRT output is defined as a dictionary.
  22903. *
  22904. * @augments OutputStructNode
  22905. */
  22906. class MRTNode extends OutputStructNode {
  22907. static get type() {
  22908. return 'MRTNode';
  22909. }
  22910. /**
  22911. * Constructs a new output struct node.
  22912. *
  22913. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22914. */
  22915. constructor( outputNodes ) {
  22916. super();
  22917. /**
  22918. * A dictionary representing the MRT outputs. The key
  22919. * is the name of the output, the value the node which produces
  22920. * the output result.
  22921. *
  22922. * @type {Object<string, Node>}
  22923. */
  22924. this.outputNodes = outputNodes;
  22925. /**
  22926. * This flag can be used for type testing.
  22927. *
  22928. * @type {boolean}
  22929. * @readonly
  22930. * @default true
  22931. */
  22932. this.isMRTNode = true;
  22933. }
  22934. /**
  22935. * Returns `true` if the MRT node has an output with the given name.
  22936. *
  22937. * @param {string} name - The name of the output.
  22938. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  22939. */
  22940. has( name ) {
  22941. return this.outputNodes[ name ] !== undefined;
  22942. }
  22943. /**
  22944. * Returns the output node for the given name.
  22945. *
  22946. * @param {string} name - The name of the output.
  22947. * @return {Node} The output node.
  22948. */
  22949. get( name ) {
  22950. return this.outputNodes[ name ];
  22951. }
  22952. /**
  22953. * Merges the outputs of the given MRT node with the outputs of this node.
  22954. *
  22955. * @param {MRTNode} mrtNode - The MRT to merge.
  22956. * @return {MRTNode} A new MRT node with merged outputs..
  22957. */
  22958. merge( mrtNode ) {
  22959. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  22960. return mrt( outputs );
  22961. }
  22962. setup( builder ) {
  22963. const outputNodes = this.outputNodes;
  22964. const mrt = builder.renderer.getRenderTarget();
  22965. const members = [];
  22966. const textures = mrt.textures;
  22967. for ( const name in outputNodes ) {
  22968. const index = getTextureIndex( textures, name );
  22969. members[ index ] = vec4( outputNodes[ name ] );
  22970. }
  22971. this.members = members;
  22972. return super.setup( builder );
  22973. }
  22974. }
  22975. /**
  22976. * TSL function for creating a MRT node.
  22977. *
  22978. * @tsl
  22979. * @function
  22980. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22981. * @returns {MRTNode}
  22982. */
  22983. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  22984. /**
  22985. * This node represents an operation that reinterprets the bit representation of a value
  22986. * in one type as a value in another type.
  22987. *
  22988. * @augments TempNode
  22989. */
  22990. class BitcastNode extends TempNode {
  22991. static get type() {
  22992. return 'BitcastNode';
  22993. }
  22994. /**
  22995. * Constructs a new bitcast node.
  22996. *
  22997. * @param {Node} valueNode - The value to convert.
  22998. * @param {string} conversionType - The type to convert to.
  22999. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  23000. */
  23001. constructor( valueNode, conversionType, inputType = null ) {
  23002. super();
  23003. /**
  23004. * The data to bitcast to a new type.
  23005. *
  23006. * @type {Node}
  23007. */
  23008. this.valueNode = valueNode;
  23009. /**
  23010. * The type the value will be converted to.
  23011. *
  23012. * @type {string}
  23013. */
  23014. this.conversionType = conversionType;
  23015. /**
  23016. * The expected input data type of the bitcast operation.
  23017. *
  23018. *
  23019. * @type {string}
  23020. * @default null
  23021. */
  23022. this.inputType = inputType;
  23023. /**
  23024. * This flag can be used for type testing.
  23025. *
  23026. * @type {boolean}
  23027. * @readonly
  23028. * @default true
  23029. */
  23030. this.isBitcastNode = true;
  23031. }
  23032. getNodeType( builder ) {
  23033. // GLSL aliasing
  23034. if ( this.inputType !== null ) {
  23035. const valueType = this.valueNode.getNodeType( builder );
  23036. const valueLength = builder.getTypeLength( valueType );
  23037. return builder.getTypeFromLength( valueLength, this.conversionType );
  23038. }
  23039. return this.conversionType;
  23040. }
  23041. generate( builder ) {
  23042. const type = this.getNodeType( builder );
  23043. let inputType = '';
  23044. if ( this.inputType !== null ) {
  23045. const valueType = this.valueNode.getNodeType( builder );
  23046. const valueTypeLength = builder.getTypeLength( valueType );
  23047. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  23048. } else {
  23049. inputType = this.valueNode.getNodeType( builder );
  23050. }
  23051. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  23052. }
  23053. }
  23054. /**
  23055. * Reinterpret the bit representation of a value in one type as a value in another type.
  23056. *
  23057. * @tsl
  23058. * @function
  23059. * @param {Node | number} x - The parameter.
  23060. * @param {string} y - The new type.
  23061. * @returns {Node}
  23062. */
  23063. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  23064. /**
  23065. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  23066. *
  23067. * @tsl
  23068. * @function
  23069. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23070. * @returns {BitcastNode}
  23071. */
  23072. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  23073. /**
  23074. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  23075. *
  23076. * @tsl
  23077. * @function
  23078. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23079. * @returns {BitcastNode}
  23080. */
  23081. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  23082. /**
  23083. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  23084. *
  23085. * @tsl
  23086. * @function
  23087. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  23088. * @returns {BitcastNode}
  23089. */
  23090. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  23091. /**
  23092. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  23093. *
  23094. * @tsl
  23095. * @function
  23096. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  23097. * @returns {BitcastNode}
  23098. */
  23099. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  23100. /**
  23101. * Generates a hash value in the range `[0, 1]` from the given seed.
  23102. *
  23103. * @tsl
  23104. * @function
  23105. * @param {Node<float>} seed - The seed.
  23106. * @return {Node<float>} The hash value.
  23107. */
  23108. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  23109. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  23110. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  23111. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  23112. const result = word.shiftRight( 22 ).bitXor( word );
  23113. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  23114. } );
  23115. /**
  23116. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23117. * The corners are mapped to `0` and the center to `1`.
  23118. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23119. *
  23120. * @tsl
  23121. * @function
  23122. * @param {Node<float>} x - The value to remap.
  23123. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  23124. * @return {Node<float>} The remapped value.
  23125. */
  23126. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  23127. /**
  23128. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23129. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  23130. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23131. *
  23132. * @tsl
  23133. * @function
  23134. * @param {Node<float>} x - The value to remap.
  23135. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  23136. * @return {Node<float>} The remapped value.
  23137. */
  23138. 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 ) );
  23139. /**
  23140. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23141. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  23142. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23143. *
  23144. * @tsl
  23145. * @function
  23146. * @param {Node<float>} x - The value to remap.
  23147. * @param {Node<float>} a - First control parameter.
  23148. * @param {Node<float>} b - Second control parameter.
  23149. * @return {Node<float>} The remapped value.
  23150. */
  23151. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  23152. /**
  23153. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  23154. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23155. *
  23156. * @tsl
  23157. * @function
  23158. * @param {Node<float>} x - The value to compute the sin for.
  23159. * @param {Node<float>} k - Controls the amount of bounces.
  23160. * @return {Node<float>} The result value.
  23161. */
  23162. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  23163. // https://github.com/cabbibo/glsl-tri-noise-3d
  23164. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  23165. return x.fract().sub( .5 ).abs();
  23166. } ).setLayout( {
  23167. name: 'tri',
  23168. type: 'float',
  23169. inputs: [
  23170. { name: 'x', type: 'float' }
  23171. ]
  23172. } );
  23173. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  23174. 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. ) ) ) ) );
  23175. } ).setLayout( {
  23176. name: 'tri3',
  23177. type: 'vec3',
  23178. inputs: [
  23179. { name: 'p', type: 'vec3' }
  23180. ]
  23181. } );
  23182. /**
  23183. * Generates a noise value from the given position, speed and time parameters.
  23184. *
  23185. * @tsl
  23186. * @function
  23187. * @param {Node<vec3>} position - The position.
  23188. * @param {Node<float>} speed - The speed.
  23189. * @param {Node<float>} time - The time.
  23190. * @return {Node<float>} The generated noise.
  23191. */
  23192. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  23193. const p = vec3( position ).toVar();
  23194. const z = float( 1.4 ).toVar();
  23195. const rz = float( 0.0 ).toVar();
  23196. const bp = vec3( p ).toVar();
  23197. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  23198. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  23199. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  23200. bp.mulAssign( 1.8 );
  23201. z.mulAssign( 1.5 );
  23202. p.mulAssign( 1.2 );
  23203. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  23204. rz.addAssign( t.div( z ) );
  23205. bp.addAssign( 0.14 );
  23206. } );
  23207. return rz;
  23208. } ).setLayout( {
  23209. name: 'triNoise3D',
  23210. type: 'float',
  23211. inputs: [
  23212. { name: 'position', type: 'vec3' },
  23213. { name: 'speed', type: 'float' },
  23214. { name: 'time', type: 'float' }
  23215. ]
  23216. } );
  23217. /**
  23218. * This class allows to define multiple overloaded versions
  23219. * of the same function. Depending on the parameters of the function
  23220. * call, the node picks the best-fit overloaded version.
  23221. *
  23222. * @augments Node
  23223. */
  23224. class FunctionOverloadingNode extends Node {
  23225. static get type() {
  23226. return 'FunctionOverloadingNode';
  23227. }
  23228. /**
  23229. * Constructs a new function overloading node.
  23230. *
  23231. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23232. * @param {...Node} parametersNodes - A list of parameter nodes.
  23233. */
  23234. constructor( functionNodes = [], ...parametersNodes ) {
  23235. super();
  23236. /**
  23237. * Array of `Fn` function definitions.
  23238. *
  23239. * @type {Array<Function>}
  23240. */
  23241. this.functionNodes = functionNodes;
  23242. /**
  23243. * A list of parameter nodes.
  23244. *
  23245. * @type {Array<Node>}
  23246. */
  23247. this.parametersNodes = parametersNodes;
  23248. /**
  23249. * The selected overloaded function call.
  23250. *
  23251. * @private
  23252. * @type {ShaderCallNodeInternal}
  23253. */
  23254. this._candidateFnCall = null;
  23255. /**
  23256. * This node is marked as global.
  23257. *
  23258. * @type {boolean}
  23259. * @default true
  23260. */
  23261. this.global = true;
  23262. }
  23263. /**
  23264. * This method is overwritten since the node type is inferred from
  23265. * the function's return type.
  23266. *
  23267. * @param {NodeBuilder} builder - The current node builder.
  23268. * @return {string} The node type.
  23269. */
  23270. getNodeType() {
  23271. return this.functionNodes[ 0 ].shaderNode.layout.type;
  23272. }
  23273. setup( builder ) {
  23274. const params = this.parametersNodes;
  23275. let candidateFnCall = this._candidateFnCall;
  23276. if ( candidateFnCall === null ) {
  23277. let candidateFn = null;
  23278. let candidateScore = -1;
  23279. for ( const functionNode of this.functionNodes ) {
  23280. const shaderNode = functionNode.shaderNode;
  23281. const layout = shaderNode.layout;
  23282. if ( layout === null ) {
  23283. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  23284. }
  23285. const inputs = layout.inputs;
  23286. if ( params.length === inputs.length ) {
  23287. let score = 0;
  23288. for ( let i = 0; i < params.length; i ++ ) {
  23289. const param = params[ i ];
  23290. const input = inputs[ i ];
  23291. if ( param.getNodeType( builder ) === input.type ) {
  23292. score ++;
  23293. } else {
  23294. score = 0;
  23295. }
  23296. }
  23297. if ( score > candidateScore ) {
  23298. candidateFn = functionNode;
  23299. candidateScore = score;
  23300. }
  23301. }
  23302. }
  23303. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  23304. }
  23305. return candidateFnCall;
  23306. }
  23307. }
  23308. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  23309. /**
  23310. * TSL function for creating a function overloading node.
  23311. *
  23312. * @tsl
  23313. * @function
  23314. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23315. * @returns {FunctionOverloadingNode}
  23316. */
  23317. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  23318. /**
  23319. * Represents the elapsed time in seconds.
  23320. *
  23321. * @tsl
  23322. * @type {UniformNode<float>}
  23323. */
  23324. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  23325. /**
  23326. * Represents the delta time in seconds.
  23327. *
  23328. * @tsl
  23329. * @type {UniformNode<float>}
  23330. */
  23331. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  23332. /**
  23333. * Represents the current frame ID.
  23334. *
  23335. * @tsl
  23336. * @type {UniformNode<uint>}
  23337. */
  23338. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  23339. /**
  23340. * Generates a sine wave oscillation based on a timer.
  23341. *
  23342. * @tsl
  23343. * @function
  23344. * @param {Node<float>} t - The timer to generate the oscillation with.
  23345. * @return {Node<float>} The oscillation node.
  23346. */
  23347. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  23348. /**
  23349. * Generates a square wave oscillation based on a timer.
  23350. *
  23351. * @tsl
  23352. * @function
  23353. * @param {Node<float>} t - The timer to generate the oscillation with.
  23354. * @return {Node<float>} The oscillation node.
  23355. */
  23356. const oscSquare = ( t = time ) => t.fract().round();
  23357. /**
  23358. * Generates a triangle wave oscillation based on a timer.
  23359. *
  23360. * @tsl
  23361. * @function
  23362. * @param {Node<float>} t - The timer to generate the oscillation with.
  23363. * @return {Node<float>} The oscillation node.
  23364. */
  23365. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  23366. /**
  23367. * Generates a sawtooth wave oscillation based on a timer.
  23368. *
  23369. * @tsl
  23370. * @function
  23371. * @param {Node<float>} t - The timer to generate the oscillation with.
  23372. * @return {Node<float>} The oscillation node.
  23373. */
  23374. const oscSawtooth = ( t = time ) => t.fract();
  23375. /**
  23376. * Rotates the given uv coordinates around a center point
  23377. *
  23378. * @tsl
  23379. * @function
  23380. * @param {Node<vec2>} uv - The uv coordinates.
  23381. * @param {Node<float>} rotation - The rotation defined in radians.
  23382. * @param {Node<vec2>} center - The center of rotation
  23383. * @return {Node<vec2>} The rotated uv coordinates.
  23384. */
  23385. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  23386. return rotate( uv.sub( center ), rotation ).add( center );
  23387. } );
  23388. /**
  23389. * Applies a spherical warping effect to the given uv coordinates.
  23390. *
  23391. * @tsl
  23392. * @function
  23393. * @param {Node<vec2>} uv - The uv coordinates.
  23394. * @param {Node<float>} strength - The strength of the effect.
  23395. * @param {Node<vec2>} center - The center point
  23396. * @return {Node<vec2>} The updated uv coordinates.
  23397. */
  23398. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  23399. const delta = uv.sub( center );
  23400. const delta2 = delta.dot( delta );
  23401. const delta4 = delta2.mul( delta2 );
  23402. const deltaOffset = delta4.mul( strength );
  23403. return uv.add( delta.mul( deltaOffset ) );
  23404. } );
  23405. /**
  23406. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  23407. * oriented always towards the camera.
  23408. *
  23409. * ```js
  23410. * material.vertexNode = billboarding();
  23411. * ```
  23412. *
  23413. * @tsl
  23414. * @function
  23415. * @param {Object} config - The configuration object.
  23416. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  23417. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  23418. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  23419. * @return {Node<vec3>} The updated vertex position in clip space.
  23420. */
  23421. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  23422. let worldMatrix;
  23423. if ( position !== null ) {
  23424. worldMatrix = modelWorldMatrix.toVar();
  23425. worldMatrix[ 3 ][ 0 ] = position.x;
  23426. worldMatrix[ 3 ][ 1 ] = position.y;
  23427. worldMatrix[ 3 ][ 2 ] = position.z;
  23428. } else {
  23429. worldMatrix = modelWorldMatrix;
  23430. }
  23431. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  23432. if ( defined( horizontal ) ) {
  23433. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  23434. modelViewMatrix[ 0 ][ 1 ] = 0;
  23435. modelViewMatrix[ 0 ][ 2 ] = 0;
  23436. }
  23437. if ( defined( vertical ) ) {
  23438. modelViewMatrix[ 1 ][ 0 ] = 0;
  23439. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  23440. modelViewMatrix[ 1 ][ 2 ] = 0;
  23441. }
  23442. modelViewMatrix[ 2 ][ 0 ] = 0;
  23443. modelViewMatrix[ 2 ][ 1 ] = 0;
  23444. modelViewMatrix[ 2 ][ 2 ] = 1;
  23445. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23446. } );
  23447. /**
  23448. * A special version of a screen uv function that involves a depth comparison
  23449. * when computing the final uvs. The function mitigates visual errors when
  23450. * using viewport texture nodes for refraction purposes. Without this function
  23451. * objects in front of a refractive surface might appear on the refractive surface
  23452. * which is incorrect.
  23453. *
  23454. * @tsl
  23455. * @function
  23456. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  23457. * @return {Node<vec2>} The update uv coordinates.
  23458. */
  23459. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  23460. const depth = linearDepth();
  23461. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  23462. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  23463. return finalUV;
  23464. } );
  23465. /**
  23466. * Can be used to compute texture coordinates for animated sprite sheets.
  23467. *
  23468. * ```js
  23469. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  23470. *
  23471. * material.colorNode = texture( spriteSheet, uvNode );
  23472. * ```
  23473. *
  23474. * @augments Node
  23475. */
  23476. class SpriteSheetUVNode extends Node {
  23477. static get type() {
  23478. return 'SpriteSheetUVNode';
  23479. }
  23480. /**
  23481. * Constructs a new sprite sheet uv node.
  23482. *
  23483. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23484. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  23485. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23486. */
  23487. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  23488. super( 'vec2' );
  23489. /**
  23490. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23491. *
  23492. * @type {Node<vec2>}
  23493. */
  23494. this.countNode = countNode;
  23495. /**
  23496. * The uv node.
  23497. *
  23498. * @type {Node<vec2>}
  23499. */
  23500. this.uvNode = uvNode;
  23501. /**
  23502. * The node that defines the current frame/sprite.
  23503. *
  23504. * @type {Node<float>}
  23505. */
  23506. this.frameNode = frameNode;
  23507. }
  23508. setup() {
  23509. const { frameNode, uvNode, countNode } = this;
  23510. const { width, height } = countNode;
  23511. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  23512. const column = frameNum.mod( width );
  23513. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  23514. const scale = countNode.reciprocal();
  23515. const uvFrameOffset = vec2( column, row );
  23516. return uvNode.add( uvFrameOffset ).mul( scale );
  23517. }
  23518. }
  23519. /**
  23520. * TSL function for creating a sprite sheet uv node.
  23521. *
  23522. * @tsl
  23523. * @function
  23524. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23525. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  23526. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23527. * @returns {SpriteSheetUVNode}
  23528. */
  23529. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  23530. /**
  23531. * TSL function for creating a triplanar textures node.
  23532. *
  23533. * Can be used for triplanar texture mapping.
  23534. *
  23535. * ```js
  23536. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  23537. * ```
  23538. *
  23539. * @tsl
  23540. * @function
  23541. * @param {Node} textureXNode - First texture node.
  23542. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23543. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23544. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23545. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23546. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23547. * @returns {Node<vec4>}
  23548. */
  23549. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  23550. // Reference: https://github.com/keijiro/StandardTriplanar
  23551. // Blending factor of triplanar mapping
  23552. let bf = normalNode.abs().normalize();
  23553. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  23554. // Triplanar mapping
  23555. const tx = positionNode.yz.mul( scaleNode );
  23556. const ty = positionNode.zx.mul( scaleNode );
  23557. const tz = positionNode.xy.mul( scaleNode );
  23558. // Base color
  23559. const textureX = textureXNode.value;
  23560. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  23561. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  23562. const cx = texture( textureX, tx ).mul( bf.x );
  23563. const cy = texture( textureY, ty ).mul( bf.y );
  23564. const cz = texture( textureZ, tz ).mul( bf.z );
  23565. return add( cx, cy, cz );
  23566. } );
  23567. /**
  23568. * TSL function for creating a triplanar textures node.
  23569. *
  23570. * @tsl
  23571. * @function
  23572. * @param {Node} textureXNode - First texture node.
  23573. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23574. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23575. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23576. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23577. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23578. * @returns {Node<vec4>}
  23579. */
  23580. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  23581. const _reflectorPlane = new Plane();
  23582. const _normal = new Vector3();
  23583. const _reflectorWorldPosition = new Vector3();
  23584. const _cameraWorldPosition = new Vector3();
  23585. const _rotationMatrix = new Matrix4();
  23586. const _lookAtPosition = new Vector3( 0, 0, -1 );
  23587. const clipPlane = new Vector4();
  23588. const _view = new Vector3();
  23589. const _target = new Vector3();
  23590. const _q = new Vector4();
  23591. const _size$2 = new Vector2();
  23592. const _defaultRT = new RenderTarget();
  23593. const _defaultUV = screenUV.flipX();
  23594. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  23595. let _inReflector = false;
  23596. /**
  23597. * This node can be used to implement mirror-like flat reflective surfaces.
  23598. *
  23599. * ```js
  23600. * const groundReflector = reflector();
  23601. * material.colorNode = groundReflector;
  23602. *
  23603. * const plane = new Mesh( geometry, material );
  23604. * plane.add( groundReflector.target );
  23605. * ```
  23606. *
  23607. * @augments TextureNode
  23608. */
  23609. class ReflectorNode extends TextureNode {
  23610. static get type() {
  23611. return 'ReflectorNode';
  23612. }
  23613. /**
  23614. * Constructs a new reflector node.
  23615. *
  23616. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23617. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23618. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  23619. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23620. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23621. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23622. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23623. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23624. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23625. */
  23626. constructor( parameters = {} ) {
  23627. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  23628. /**
  23629. * A reference to the internal reflector base node which holds the actual implementation.
  23630. *
  23631. * @private
  23632. * @type {ReflectorBaseNode}
  23633. * @default ReflectorBaseNode
  23634. */
  23635. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  23636. /**
  23637. * A reference to the internal depth node.
  23638. *
  23639. * @private
  23640. * @type {?Node}
  23641. * @default null
  23642. */
  23643. this._depthNode = null;
  23644. this.setUpdateMatrix( false );
  23645. }
  23646. /**
  23647. * A reference to the internal reflector node.
  23648. *
  23649. * @type {ReflectorBaseNode}
  23650. */
  23651. get reflector() {
  23652. return this._reflectorBaseNode;
  23653. }
  23654. /**
  23655. * A reference to 3D object the reflector is linked to.
  23656. *
  23657. * @type {Object3D}
  23658. */
  23659. get target() {
  23660. return this._reflectorBaseNode.target;
  23661. }
  23662. /**
  23663. * Returns a node representing the mirror's depth. That can be used
  23664. * to implement more advanced reflection effects like distance attenuation.
  23665. *
  23666. * @return {Node} The depth node.
  23667. */
  23668. getDepthNode() {
  23669. if ( this._depthNode === null ) {
  23670. if ( this._reflectorBaseNode.depth !== true ) {
  23671. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  23672. }
  23673. this._depthNode = nodeObject( new ReflectorNode( {
  23674. defaultTexture: _defaultRT.depthTexture,
  23675. reflector: this._reflectorBaseNode
  23676. } ) );
  23677. }
  23678. return this._depthNode;
  23679. }
  23680. setup( builder ) {
  23681. // ignore if used in post-processing
  23682. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  23683. return super.setup( builder );
  23684. }
  23685. clone() {
  23686. const newNode = new this.constructor( this.reflectorNode );
  23687. newNode.uvNode = this.uvNode;
  23688. newNode.levelNode = this.levelNode;
  23689. newNode.biasNode = this.biasNode;
  23690. newNode.sampler = this.sampler;
  23691. newNode.depthNode = this.depthNode;
  23692. newNode.compareNode = this.compareNode;
  23693. newNode.gradNode = this.gradNode;
  23694. newNode.offsetNode = this.offsetNode;
  23695. newNode._reflectorBaseNode = this._reflectorBaseNode;
  23696. return newNode;
  23697. }
  23698. /**
  23699. * Frees internal resources. Should be called when the node is no longer in use.
  23700. */
  23701. dispose() {
  23702. super.dispose();
  23703. this._reflectorBaseNode.dispose();
  23704. }
  23705. }
  23706. /**
  23707. * Holds the actual implementation of the reflector.
  23708. *
  23709. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  23710. * in `ReflectorNode`, see #29619.
  23711. *
  23712. * @private
  23713. * @augments Node
  23714. */
  23715. class ReflectorBaseNode extends Node {
  23716. static get type() {
  23717. return 'ReflectorBaseNode';
  23718. }
  23719. /**
  23720. * Constructs a new reflector base node.
  23721. *
  23722. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  23723. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23724. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23725. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  23726. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23727. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23728. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23729. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23730. */
  23731. constructor( textureNode, parameters = {} ) {
  23732. super();
  23733. const {
  23734. target = new Object3D(),
  23735. resolutionScale = 1,
  23736. generateMipmaps = false,
  23737. bounces = true,
  23738. depth = false,
  23739. samples = 0
  23740. } = parameters;
  23741. /**
  23742. * Represents the rendered reflections as a texture node.
  23743. *
  23744. * @type {TextureNode}
  23745. */
  23746. this.textureNode = textureNode;
  23747. /**
  23748. * The 3D object the reflector is linked to.
  23749. *
  23750. * @type {Object3D}
  23751. * @default {new Object3D()}
  23752. */
  23753. this.target = target;
  23754. /**
  23755. * The resolution scale.
  23756. *
  23757. * @type {number}
  23758. * @default {1}
  23759. */
  23760. this.resolutionScale = resolutionScale;
  23761. if ( parameters.resolution !== undefined ) {
  23762. warnOnce( 'ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  23763. this.resolutionScale = parameters.resolution;
  23764. }
  23765. /**
  23766. * Whether mipmaps should be generated or not.
  23767. *
  23768. * @type {boolean}
  23769. * @default {false}
  23770. */
  23771. this.generateMipmaps = generateMipmaps;
  23772. /**
  23773. * Whether reflectors can render other reflector nodes or not.
  23774. *
  23775. * @type {boolean}
  23776. * @default {true}
  23777. */
  23778. this.bounces = bounces;
  23779. /**
  23780. * Whether depth data should be generated or not.
  23781. *
  23782. * @type {boolean}
  23783. * @default {false}
  23784. */
  23785. this.depth = depth;
  23786. /**
  23787. * The number of anti-aliasing samples for the render-target
  23788. *
  23789. * @type {number}
  23790. * @default {0}
  23791. */
  23792. this.samples = samples;
  23793. /**
  23794. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  23795. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  23796. *
  23797. * @type {string}
  23798. * @default 'render'
  23799. */
  23800. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  23801. /**
  23802. * Weak map for managing virtual cameras.
  23803. *
  23804. * @type {WeakMap<Camera, Camera>}
  23805. */
  23806. this.virtualCameras = new WeakMap();
  23807. /**
  23808. * Weak map for managing render targets.
  23809. *
  23810. * @type {Map<Camera, RenderTarget>}
  23811. */
  23812. this.renderTargets = new Map();
  23813. /**
  23814. * Force render even if reflector is facing away from camera.
  23815. *
  23816. * @type {boolean}
  23817. * @default {false}
  23818. */
  23819. this.forceUpdate = false;
  23820. /**
  23821. * Whether the reflector has been rendered or not.
  23822. *
  23823. * When the reflector is facing away from the camera,
  23824. * this flag is set to `false` and the texture will be empty(black).
  23825. *
  23826. * @type {boolean}
  23827. * @default {false}
  23828. */
  23829. this.hasOutput = false;
  23830. }
  23831. /**
  23832. * Updates the resolution of the internal render target.
  23833. *
  23834. * @private
  23835. * @param {RenderTarget} renderTarget - The render target to resize.
  23836. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  23837. */
  23838. _updateResolution( renderTarget, renderer ) {
  23839. const resolution = this.resolutionScale;
  23840. renderer.getDrawingBufferSize( _size$2 );
  23841. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  23842. }
  23843. setup( builder ) {
  23844. this._updateResolution( _defaultRT, builder.renderer );
  23845. return super.setup( builder );
  23846. }
  23847. /**
  23848. * Frees internal resources. Should be called when the node is no longer in use.
  23849. */
  23850. dispose() {
  23851. super.dispose();
  23852. for ( const renderTarget of this.renderTargets.values() ) {
  23853. renderTarget.dispose();
  23854. }
  23855. }
  23856. /**
  23857. * Returns a virtual camera for the given camera. The virtual camera is used to
  23858. * render the scene from the reflector's view so correct reflections can be produced.
  23859. *
  23860. * @param {Camera} camera - The scene's camera.
  23861. * @return {Camera} The corresponding virtual camera.
  23862. */
  23863. getVirtualCamera( camera ) {
  23864. let virtualCamera = this.virtualCameras.get( camera );
  23865. if ( virtualCamera === undefined ) {
  23866. virtualCamera = camera.clone();
  23867. this.virtualCameras.set( camera, virtualCamera );
  23868. }
  23869. return virtualCamera;
  23870. }
  23871. /**
  23872. * Returns a render target for the given camera. The reflections are rendered
  23873. * into this render target.
  23874. *
  23875. * @param {Camera} camera - The scene's camera.
  23876. * @return {RenderTarget} The render target.
  23877. */
  23878. getRenderTarget( camera ) {
  23879. let renderTarget = this.renderTargets.get( camera );
  23880. if ( renderTarget === undefined ) {
  23881. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  23882. if ( this.generateMipmaps === true ) {
  23883. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  23884. renderTarget.texture.generateMipmaps = true;
  23885. }
  23886. if ( this.depth === true ) {
  23887. renderTarget.depthTexture = new DepthTexture();
  23888. }
  23889. this.renderTargets.set( camera, renderTarget );
  23890. }
  23891. return renderTarget;
  23892. }
  23893. updateBefore( frame ) {
  23894. if ( this.bounces === false && _inReflector ) return false;
  23895. _inReflector = true;
  23896. const { scene, camera, renderer, material } = frame;
  23897. const { target } = this;
  23898. const virtualCamera = this.getVirtualCamera( camera );
  23899. const renderTarget = this.getRenderTarget( virtualCamera );
  23900. renderer.getDrawingBufferSize( _size$2 );
  23901. this._updateResolution( renderTarget, renderer );
  23902. //
  23903. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  23904. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  23905. _rotationMatrix.extractRotation( target.matrixWorld );
  23906. _normal.set( 0, 0, 1 );
  23907. _normal.applyMatrix4( _rotationMatrix );
  23908. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  23909. // Avoid rendering when reflector is facing away unless forcing an update
  23910. const isFacingAway = _view.dot( _normal ) > 0;
  23911. let needsClear = false;
  23912. if ( isFacingAway === true && this.forceUpdate === false ) {
  23913. if ( this.hasOutput === false ) {
  23914. _inReflector = false;
  23915. return;
  23916. }
  23917. needsClear = true;
  23918. }
  23919. _view.reflect( _normal ).negate();
  23920. _view.add( _reflectorWorldPosition );
  23921. _rotationMatrix.extractRotation( camera.matrixWorld );
  23922. _lookAtPosition.set( 0, 0, -1 );
  23923. _lookAtPosition.applyMatrix4( _rotationMatrix );
  23924. _lookAtPosition.add( _cameraWorldPosition );
  23925. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  23926. _target.reflect( _normal ).negate();
  23927. _target.add( _reflectorWorldPosition );
  23928. //
  23929. virtualCamera.coordinateSystem = camera.coordinateSystem;
  23930. virtualCamera.position.copy( _view );
  23931. virtualCamera.up.set( 0, 1, 0 );
  23932. virtualCamera.up.applyMatrix4( _rotationMatrix );
  23933. virtualCamera.up.reflect( _normal );
  23934. virtualCamera.lookAt( _target );
  23935. virtualCamera.near = camera.near;
  23936. virtualCamera.far = camera.far;
  23937. virtualCamera.updateMatrixWorld();
  23938. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  23939. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  23940. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  23941. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  23942. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  23943. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  23944. const projectionMatrix = virtualCamera.projectionMatrix;
  23945. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  23946. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  23947. _q.z = -1;
  23948. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  23949. // Calculate the scaled plane vector
  23950. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  23951. const clipBias = 0;
  23952. // Replacing the third row of the projection matrix
  23953. projectionMatrix.elements[ 2 ] = clipPlane.x;
  23954. projectionMatrix.elements[ 6 ] = clipPlane.y;
  23955. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  23956. projectionMatrix.elements[ 14 ] = clipPlane.w;
  23957. //
  23958. this.textureNode.value = renderTarget.texture;
  23959. if ( this.depth === true ) {
  23960. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  23961. }
  23962. material.visible = false;
  23963. const currentRenderTarget = renderer.getRenderTarget();
  23964. const currentMRT = renderer.getMRT();
  23965. const currentAutoClear = renderer.autoClear;
  23966. renderer.setMRT( null );
  23967. renderer.setRenderTarget( renderTarget );
  23968. renderer.autoClear = true;
  23969. if ( needsClear ) {
  23970. renderer.clear();
  23971. this.hasOutput = false;
  23972. } else {
  23973. renderer.render( scene, virtualCamera );
  23974. this.hasOutput = true;
  23975. }
  23976. renderer.setMRT( currentMRT );
  23977. renderer.setRenderTarget( currentRenderTarget );
  23978. renderer.autoClear = currentAutoClear;
  23979. material.visible = true;
  23980. _inReflector = false;
  23981. this.forceUpdate = false;
  23982. }
  23983. /**
  23984. * The resolution scale.
  23985. *
  23986. * @deprecated
  23987. * @type {number}
  23988. * @default {1}
  23989. */
  23990. get resolution() {
  23991. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  23992. return this.resolutionScale;
  23993. }
  23994. set resolution( value ) {
  23995. warnOnce( 'ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  23996. this.resolutionScale = value;
  23997. }
  23998. }
  23999. /**
  24000. * TSL function for creating a reflector node.
  24001. *
  24002. * @tsl
  24003. * @function
  24004. * @param {Object} [parameters={}] - An object holding configuration parameters.
  24005. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  24006. * @param {number} [parameters.resolution=1] - The resolution scale.
  24007. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  24008. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  24009. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  24010. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  24011. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  24012. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  24013. * @returns {ReflectorNode}
  24014. */
  24015. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  24016. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  24017. /**
  24018. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  24019. *
  24020. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  24021. *
  24022. * @private
  24023. * @augments BufferGeometry
  24024. */
  24025. class QuadGeometry extends BufferGeometry {
  24026. /**
  24027. * Constructs a new quad geometry.
  24028. *
  24029. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  24030. */
  24031. constructor( flipY = false ) {
  24032. super();
  24033. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  24034. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  24035. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  24036. }
  24037. }
  24038. const _geometry = /*@__PURE__*/ new QuadGeometry();
  24039. /**
  24040. * This module is a helper for passes which need to render a full
  24041. * screen effect which is quite common in context of post processing.
  24042. *
  24043. * The intended usage is to reuse a single quad mesh for rendering
  24044. * subsequent passes by just reassigning the `material` reference.
  24045. *
  24046. * Note: This module can only be used with `WebGPURenderer`.
  24047. *
  24048. * @augments Mesh
  24049. */
  24050. class QuadMesh extends Mesh {
  24051. /**
  24052. * Constructs a new quad mesh.
  24053. *
  24054. * @param {?Material} [material=null] - The material to render the quad mesh with.
  24055. */
  24056. constructor( material = null ) {
  24057. super( _geometry, material );
  24058. /**
  24059. * The camera to render the quad mesh with.
  24060. *
  24061. * @type {OrthographicCamera}
  24062. * @readonly
  24063. */
  24064. this.camera = _camera;
  24065. /**
  24066. * This flag can be used for type testing.
  24067. *
  24068. * @type {boolean}
  24069. * @readonly
  24070. * @default true
  24071. */
  24072. this.isQuadMesh = true;
  24073. }
  24074. /**
  24075. * Async version of `render()`.
  24076. *
  24077. * @async
  24078. * @param {Renderer} renderer - The renderer.
  24079. * @return {Promise} A Promise that resolves when the render has been finished.
  24080. */
  24081. async renderAsync( renderer ) {
  24082. return renderer.renderAsync( this, _camera );
  24083. }
  24084. /**
  24085. * Renders the quad mesh
  24086. *
  24087. * @param {Renderer} renderer - The renderer.
  24088. */
  24089. render( renderer ) {
  24090. renderer.render( this, _camera );
  24091. }
  24092. }
  24093. const _size$1 = /*@__PURE__*/ new Vector2();
  24094. /**
  24095. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  24096. * This module is especially relevant in context of post processing where certain nodes require
  24097. * texture input for their effects. With the helper function `convertToTexture()` which is based
  24098. * on this module, the node system can automatically ensure texture input if required.
  24099. *
  24100. * @augments TextureNode
  24101. */
  24102. class RTTNode extends TextureNode {
  24103. static get type() {
  24104. return 'RTTNode';
  24105. }
  24106. /**
  24107. * Constructs a new RTT node.
  24108. *
  24109. * @param {Node} node - The node to render a texture with.
  24110. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24111. * @param {?number} [height=null] - The height of the internal render target.
  24112. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24113. */
  24114. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  24115. const renderTarget = new RenderTarget( width, height, options );
  24116. super( renderTarget.texture, uv$1() );
  24117. /**
  24118. * This flag can be used for type testing.
  24119. *
  24120. * @type {boolean}
  24121. * @readonly
  24122. * @default true
  24123. */
  24124. this.isRTTNode = true;
  24125. /**
  24126. * The node to render a texture with.
  24127. *
  24128. * @type {Node}
  24129. */
  24130. this.node = node;
  24131. /**
  24132. * The width of the internal render target.
  24133. * If not width is applied, the render target is automatically resized.
  24134. *
  24135. * @type {?number}
  24136. * @default null
  24137. */
  24138. this.width = width;
  24139. /**
  24140. * The height of the internal render target.
  24141. *
  24142. * @type {?number}
  24143. * @default null
  24144. */
  24145. this.height = height;
  24146. /**
  24147. * The pixel ratio
  24148. *
  24149. * @type {number}
  24150. * @default 1
  24151. */
  24152. this.pixelRatio = 1;
  24153. /**
  24154. * The render target
  24155. *
  24156. * @type {RenderTarget}
  24157. */
  24158. this.renderTarget = renderTarget;
  24159. /**
  24160. * Whether the texture requires an update or not.
  24161. *
  24162. * @type {boolean}
  24163. * @default true
  24164. */
  24165. this.textureNeedsUpdate = true;
  24166. /**
  24167. * Whether the texture should automatically be updated or not.
  24168. *
  24169. * @type {boolean}
  24170. * @default true
  24171. */
  24172. this.autoUpdate = true;
  24173. /**
  24174. * The node which is used with the quad mesh for RTT.
  24175. *
  24176. * @private
  24177. * @type {Node}
  24178. * @default null
  24179. */
  24180. this._rttNode = null;
  24181. /**
  24182. * The internal quad mesh for RTT.
  24183. *
  24184. * @private
  24185. * @type {QuadMesh}
  24186. */
  24187. this._quadMesh = new QuadMesh( new NodeMaterial() );
  24188. /**
  24189. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  24190. * the texture once per render in its {@link RTTNode#updateBefore} method.
  24191. *
  24192. * @type {string}
  24193. * @default 'render'
  24194. */
  24195. this.updateBeforeType = NodeUpdateType.RENDER;
  24196. }
  24197. /**
  24198. * Whether the internal render target should automatically be resized or not.
  24199. *
  24200. * @type {boolean}
  24201. * @readonly
  24202. * @default true
  24203. */
  24204. get autoResize() {
  24205. return this.width === null;
  24206. }
  24207. setup( builder ) {
  24208. this._rttNode = this.node.context( builder.getSharedContext() );
  24209. this._quadMesh.material.name = 'RTT';
  24210. this._quadMesh.material.needsUpdate = true;
  24211. return super.setup( builder );
  24212. }
  24213. /**
  24214. * Sets the size of the internal render target
  24215. *
  24216. * @param {number} width - The width to set.
  24217. * @param {number} height - The width to set.
  24218. */
  24219. setSize( width, height ) {
  24220. this.width = width;
  24221. this.height = height;
  24222. const effectiveWidth = width * this.pixelRatio;
  24223. const effectiveHeight = height * this.pixelRatio;
  24224. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24225. this.textureNeedsUpdate = true;
  24226. }
  24227. /**
  24228. * Sets the pixel ratio. This will also resize the render target.
  24229. *
  24230. * @param {number} pixelRatio - The pixel ratio to set.
  24231. */
  24232. setPixelRatio( pixelRatio ) {
  24233. this.pixelRatio = pixelRatio;
  24234. this.setSize( this.width, this.height );
  24235. }
  24236. updateBefore( { renderer } ) {
  24237. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  24238. this.textureNeedsUpdate = false;
  24239. //
  24240. if ( this.autoResize === true ) {
  24241. const pixelRatio = renderer.getPixelRatio();
  24242. const size = renderer.getSize( _size$1 );
  24243. const effectiveWidth = size.width * pixelRatio;
  24244. const effectiveHeight = size.height * pixelRatio;
  24245. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  24246. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24247. this.textureNeedsUpdate = true;
  24248. }
  24249. }
  24250. //
  24251. this._quadMesh.material.fragmentNode = this._rttNode;
  24252. //
  24253. const currentRenderTarget = renderer.getRenderTarget();
  24254. renderer.setRenderTarget( this.renderTarget );
  24255. this._quadMesh.render( renderer );
  24256. renderer.setRenderTarget( currentRenderTarget );
  24257. }
  24258. clone() {
  24259. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  24260. newNode.sampler = this.sampler;
  24261. newNode.referenceNode = this;
  24262. return newNode;
  24263. }
  24264. }
  24265. /**
  24266. * TSL function for creating a RTT node.
  24267. *
  24268. * @tsl
  24269. * @function
  24270. * @param {Node} node - The node to render a texture with.
  24271. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24272. * @param {?number} [height=null] - The height of the internal render target.
  24273. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24274. * @returns {RTTNode}
  24275. */
  24276. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  24277. /**
  24278. * TSL function for converting nodes to textures nodes.
  24279. *
  24280. * @tsl
  24281. * @function
  24282. * @param {Node} node - The node to render a texture with.
  24283. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24284. * @param {?number} [height=null] - The height of the internal render target.
  24285. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24286. * @returns {RTTNode}
  24287. */
  24288. const convertToTexture = ( node, ...params ) => {
  24289. if ( node.isSampleNode || node.isTextureNode ) return node;
  24290. if ( node.isPassNode ) return node.getTextureNode();
  24291. return rtt( node, ...params );
  24292. };
  24293. /**
  24294. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  24295. * depth value and the camera's inverse projection matrix.
  24296. *
  24297. * @tsl
  24298. * @function
  24299. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  24300. * @param {Node<float>} depth - The fragment's depth value.
  24301. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24302. * @return {Node<vec3>} The fragments position in view space.
  24303. */
  24304. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  24305. let clipSpacePosition;
  24306. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  24307. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  24308. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  24309. } else {
  24310. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  24311. }
  24312. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  24313. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  24314. } );
  24315. /**
  24316. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  24317. * and the camera's projection matrix
  24318. *
  24319. * @tsl
  24320. * @function
  24321. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  24322. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  24323. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  24324. */
  24325. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  24326. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  24327. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  24328. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  24329. } );
  24330. /**
  24331. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  24332. * target is available or if flat surface normals are required.
  24333. *
  24334. * @tsl
  24335. * @function
  24336. * @param {Node<vec2>} uv - The texture coordinate.
  24337. * @param {DepthTexture} depthTexture - The depth texture.
  24338. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24339. * @return {Node<vec3>} The computed normal vector.
  24340. */
  24341. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  24342. const size = textureSize( textureLoad( depthTexture ) );
  24343. const p = ivec2( uv.mul( size ) ).toVar();
  24344. const c0 = textureLoad( depthTexture, p ).toVar();
  24345. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  24346. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  24347. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  24348. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  24349. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  24350. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  24351. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  24352. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  24353. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  24354. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  24355. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  24356. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  24357. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  24358. 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 ) ) );
  24359. 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 ) ) );
  24360. return normalize( cross( dpdx, dpdy ) );
  24361. } );
  24362. /**
  24363. * Class representing a node that samples a value using a provided callback function.
  24364. *
  24365. * @extends Node
  24366. */
  24367. class SampleNode extends Node {
  24368. /**
  24369. * Returns the type of the node.
  24370. *
  24371. * @type {string}
  24372. * @readonly
  24373. * @static
  24374. */
  24375. static get type() {
  24376. return 'SampleNode';
  24377. }
  24378. /**
  24379. * Creates an instance of SampleNode.
  24380. *
  24381. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24382. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  24383. */
  24384. constructor( callback, uvNode = null ) {
  24385. super();
  24386. this.callback = callback;
  24387. /**
  24388. * Represents the texture coordinates.
  24389. *
  24390. * @type {?Node<vec2|vec3>}
  24391. * @default null
  24392. */
  24393. this.uvNode = uvNode;
  24394. /**
  24395. * This flag can be used for type testing.
  24396. *
  24397. * @type {boolean}
  24398. * @readonly
  24399. * @default true
  24400. */
  24401. this.isSampleNode = true;
  24402. }
  24403. /**
  24404. * Sets up the node by sampling with the default UV accessor.
  24405. *
  24406. * @returns {Node} The result of the callback function when called with the UV node.
  24407. */
  24408. setup() {
  24409. return this.sample( uv$1() );
  24410. }
  24411. /**
  24412. * Calls the callback function with the provided UV node.
  24413. *
  24414. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  24415. * @returns {Node} The result of the callback function.
  24416. */
  24417. sample( uv ) {
  24418. return this.callback( uv );
  24419. }
  24420. }
  24421. /**
  24422. * Helper function to create a SampleNode wrapped as a node object.
  24423. *
  24424. * @function
  24425. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24426. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  24427. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  24428. */
  24429. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  24430. /**
  24431. * EventNode is a node that executes a callback during specific update phases.
  24432. *
  24433. * @augments Node
  24434. */
  24435. class EventNode extends Node {
  24436. static get type() {
  24437. return 'EventNode';
  24438. }
  24439. /**
  24440. * Creates an EventNode.
  24441. *
  24442. * @param {string} eventType - The type of event
  24443. * @param {Function} callback - The callback to execute on update.
  24444. */
  24445. constructor( eventType, callback ) {
  24446. super( 'void' );
  24447. this.eventType = eventType;
  24448. this.callback = callback;
  24449. if ( eventType === EventNode.OBJECT ) {
  24450. this.updateType = NodeUpdateType.OBJECT;
  24451. } else if ( eventType === EventNode.MATERIAL ) {
  24452. this.updateType = NodeUpdateType.RENDER;
  24453. }
  24454. }
  24455. update( frame ) {
  24456. this.callback( frame );
  24457. }
  24458. }
  24459. EventNode.OBJECT = 'object';
  24460. EventNode.MATERIAL = 'material';
  24461. /**
  24462. * Helper to create an EventNode and add it to the stack.
  24463. *
  24464. * @param {string} type - The event type.
  24465. * @param {Function} callback - The callback function.
  24466. * @returns {EventNode}
  24467. */
  24468. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  24469. /**
  24470. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  24471. *
  24472. * 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.
  24473. *
  24474. * @param {Function} callback - The callback function.
  24475. * @returns {EventNode}
  24476. */
  24477. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  24478. /**
  24479. * Creates an event that triggers a function when the first object that uses the material is rendered.
  24480. *
  24481. * 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.
  24482. *
  24483. * @param {Function} callback - The callback function.
  24484. * @returns {EventNode}
  24485. */
  24486. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  24487. /**
  24488. * This special type of instanced buffer attribute is intended for compute shaders.
  24489. * In earlier three.js versions it was only possible to update attribute data
  24490. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24491. * new material system and renderer it is now possible to use compute shaders
  24492. * to compute the data for an attribute more efficiently on the GPU.
  24493. *
  24494. * The idea is to create an instance of this class and provide it as an input
  24495. * to {@link StorageBufferNode}.
  24496. *
  24497. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24498. *
  24499. * @augments InstancedBufferAttribute
  24500. */
  24501. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24502. /**
  24503. * Constructs a new storage instanced buffer attribute.
  24504. *
  24505. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24506. * The subsequent parameters are then obsolete.
  24507. * @param {number} itemSize - The item size.
  24508. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24509. */
  24510. constructor( count, itemSize, typeClass = Float32Array ) {
  24511. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24512. super( array, itemSize );
  24513. /**
  24514. * This flag can be used for type testing.
  24515. *
  24516. * @type {boolean}
  24517. * @readonly
  24518. * @default true
  24519. */
  24520. this.isStorageInstancedBufferAttribute = true;
  24521. }
  24522. }
  24523. /**
  24524. * This special type of buffer attribute is intended for compute shaders.
  24525. * In earlier three.js versions it was only possible to update attribute data
  24526. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24527. * new material system and renderer it is now possible to use compute shaders
  24528. * to compute the data for an attribute more efficiently on the GPU.
  24529. *
  24530. * The idea is to create an instance of this class and provide it as an input
  24531. * to {@link StorageBufferNode}.
  24532. *
  24533. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24534. *
  24535. * @augments BufferAttribute
  24536. */
  24537. class StorageBufferAttribute extends BufferAttribute {
  24538. /**
  24539. * Constructs a new storage buffer attribute.
  24540. *
  24541. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24542. * The subsequent parameters are then obsolete.
  24543. * @param {number} itemSize - The item size.
  24544. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24545. */
  24546. constructor( count, itemSize, typeClass = Float32Array ) {
  24547. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24548. super( array, itemSize );
  24549. /**
  24550. * This flag can be used for type testing.
  24551. *
  24552. * @type {boolean}
  24553. * @readonly
  24554. * @default true
  24555. */
  24556. this.isStorageBufferAttribute = true;
  24557. }
  24558. }
  24559. /**
  24560. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  24561. *
  24562. * @tsl
  24563. * @function
  24564. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24565. * @param {string|Struct} [type='float'] - The data type.
  24566. * @returns {StorageBufferNode}
  24567. */
  24568. const attributeArray = ( count, type = 'float' ) => {
  24569. let itemSize, typedArray;
  24570. if ( type.isStruct === true ) {
  24571. itemSize = type.layout.getLength();
  24572. typedArray = getTypedArrayFromType( 'float' );
  24573. } else {
  24574. itemSize = getLengthFromType( type );
  24575. typedArray = getTypedArrayFromType( type );
  24576. }
  24577. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  24578. const node = storage( buffer, type, count );
  24579. return node;
  24580. };
  24581. /**
  24582. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  24583. *
  24584. * @tsl
  24585. * @function
  24586. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24587. * @param {string|Struct} [type='float'] - The data type.
  24588. * @returns {StorageBufferNode}
  24589. */
  24590. const instancedArray = ( count, type = 'float' ) => {
  24591. let itemSize, typedArray;
  24592. if ( type.isStruct === true ) {
  24593. itemSize = type.layout.getLength();
  24594. typedArray = getTypedArrayFromType( 'float' );
  24595. } else {
  24596. itemSize = getLengthFromType( type );
  24597. typedArray = getTypedArrayFromType( type );
  24598. }
  24599. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  24600. const node = storage( buffer, type, count );
  24601. return node;
  24602. };
  24603. /**
  24604. * A node for representing the uv coordinates of points.
  24605. *
  24606. * Can only be used with a WebGL backend. In WebGPU, point
  24607. * primitives always have the size of one pixel and can thus
  24608. * can't be used as sprite-like objects that display textures.
  24609. *
  24610. * @augments Node
  24611. */
  24612. class PointUVNode extends Node {
  24613. static get type() {
  24614. return 'PointUVNode';
  24615. }
  24616. /**
  24617. * Constructs a new point uv node.
  24618. */
  24619. constructor() {
  24620. super( 'vec2' );
  24621. /**
  24622. * This flag can be used for type testing.
  24623. *
  24624. * @type {boolean}
  24625. * @readonly
  24626. * @default true
  24627. */
  24628. this.isPointUVNode = true;
  24629. }
  24630. generate( /*builder*/ ) {
  24631. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  24632. }
  24633. }
  24634. /**
  24635. * TSL object that represents the uv coordinates of points.
  24636. *
  24637. * @tsl
  24638. * @type {PointUVNode}
  24639. */
  24640. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  24641. const _e1 = /*@__PURE__*/ new Euler();
  24642. const _m1 = /*@__PURE__*/ new Matrix4();
  24643. /**
  24644. * This module allows access to a collection of scene properties. The following predefined TSL objects
  24645. * are available for easier use:
  24646. *
  24647. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  24648. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  24649. * - `backgroundRotation`: A node that represents the scene's background rotation.
  24650. *
  24651. * @augments Node
  24652. */
  24653. class SceneNode extends Node {
  24654. static get type() {
  24655. return 'SceneNode';
  24656. }
  24657. /**
  24658. * Constructs a new scene node.
  24659. *
  24660. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  24661. * @param {?Scene} [scene=null] - A reference to the scene.
  24662. */
  24663. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  24664. super();
  24665. /**
  24666. * The scope defines the type of scene property that is accessed.
  24667. *
  24668. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  24669. */
  24670. this.scope = scope;
  24671. /**
  24672. * A reference to the scene that is going to be accessed.
  24673. *
  24674. * @type {?Scene}
  24675. * @default null
  24676. */
  24677. this.scene = scene;
  24678. }
  24679. /**
  24680. * Depending on the scope, the method returns a different type of node that represents
  24681. * the respective scene property.
  24682. *
  24683. * @param {NodeBuilder} builder - The current node builder.
  24684. * @return {Node} The output node.
  24685. */
  24686. setup( builder ) {
  24687. const scope = this.scope;
  24688. const scene = this.scene !== null ? this.scene : builder.scene;
  24689. let output;
  24690. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  24691. output = reference( 'backgroundBlurriness', 'float', scene );
  24692. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  24693. output = reference( 'backgroundIntensity', 'float', scene );
  24694. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  24695. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24696. const background = scene.background;
  24697. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  24698. _e1.copy( scene.backgroundRotation );
  24699. // accommodate left-handed frame
  24700. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  24701. _m1.makeRotationFromEuler( _e1 );
  24702. } else {
  24703. _m1.identity();
  24704. }
  24705. return _m1;
  24706. } );
  24707. } else {
  24708. error( 'SceneNode: Unknown scope:', scope );
  24709. }
  24710. return output;
  24711. }
  24712. }
  24713. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  24714. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  24715. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  24716. /**
  24717. * TSL object that represents the scene's background blurriness.
  24718. *
  24719. * @tsl
  24720. * @type {SceneNode}
  24721. */
  24722. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  24723. /**
  24724. * TSL object that represents the scene's background intensity.
  24725. *
  24726. * @tsl
  24727. * @type {SceneNode}
  24728. */
  24729. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  24730. /**
  24731. * TSL object that represents the scene's background rotation.
  24732. *
  24733. * @tsl
  24734. * @type {SceneNode}
  24735. */
  24736. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  24737. /**
  24738. * This special version of a texture node can be used to
  24739. * write data into a storage texture with a compute shader.
  24740. *
  24741. * ```js
  24742. * const storageTexture = new THREE.StorageTexture( width, height );
  24743. *
  24744. * const computeTexture = Fn( ( { storageTexture } ) => {
  24745. *
  24746. * const posX = instanceIndex.mod( width );
  24747. * const posY = instanceIndex.div( width );
  24748. * const indexUV = uvec2( posX, posY );
  24749. *
  24750. * // generate RGB values
  24751. *
  24752. * const r = 1;
  24753. * const g = 1;
  24754. * const b = 1;
  24755. *
  24756. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  24757. *
  24758. * } );
  24759. *
  24760. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  24761. * renderer.computeAsync( computeNode );
  24762. * ```
  24763. *
  24764. * This node can only be used with a WebGPU backend.
  24765. *
  24766. * @augments TextureNode
  24767. */
  24768. class StorageTextureNode extends TextureNode {
  24769. static get type() {
  24770. return 'StorageTextureNode';
  24771. }
  24772. /**
  24773. * Constructs a new storage texture node.
  24774. *
  24775. * @param {StorageTexture} value - The storage texture.
  24776. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24777. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24778. */
  24779. constructor( value, uvNode, storeNode = null ) {
  24780. super( value, uvNode );
  24781. /**
  24782. * The value node that should be stored in the texture.
  24783. *
  24784. * @type {?Node}
  24785. * @default null
  24786. */
  24787. this.storeNode = storeNode;
  24788. /**
  24789. * This flag can be used for type testing.
  24790. *
  24791. * @type {boolean}
  24792. * @readonly
  24793. * @default true
  24794. */
  24795. this.isStorageTextureNode = true;
  24796. /**
  24797. * The access type of the texture node.
  24798. *
  24799. * @type {string}
  24800. * @default 'writeOnly'
  24801. */
  24802. this.access = NodeAccess.WRITE_ONLY;
  24803. }
  24804. /**
  24805. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  24806. *
  24807. * @param {NodeBuilder} builder - The current node builder.
  24808. * @return {string} The input type.
  24809. */
  24810. getInputType( /*builder*/ ) {
  24811. return 'storageTexture';
  24812. }
  24813. setup( builder ) {
  24814. super.setup( builder );
  24815. const properties = builder.getNodeProperties( this );
  24816. properties.storeNode = this.storeNode;
  24817. return properties;
  24818. }
  24819. /**
  24820. * Defines the node access.
  24821. *
  24822. * @param {string} value - The node access.
  24823. * @return {StorageTextureNode} A reference to this node.
  24824. */
  24825. setAccess( value ) {
  24826. this.access = value;
  24827. return this;
  24828. }
  24829. /**
  24830. * Generates the code snippet of the storage node. If no `storeNode`
  24831. * is defined, the texture node is generated as normal texture.
  24832. *
  24833. * @param {NodeBuilder} builder - The current node builder.
  24834. * @param {string} output - The current output.
  24835. * @return {string} The generated code snippet.
  24836. */
  24837. generate( builder, output ) {
  24838. let snippet;
  24839. if ( this.storeNode !== null ) {
  24840. snippet = this.generateStore( builder );
  24841. } else {
  24842. snippet = super.generate( builder, output );
  24843. }
  24844. return snippet;
  24845. }
  24846. /**
  24847. * Convenience method for configuring a read/write node access.
  24848. *
  24849. * @return {StorageTextureNode} A reference to this node.
  24850. */
  24851. toReadWrite() {
  24852. return this.setAccess( NodeAccess.READ_WRITE );
  24853. }
  24854. /**
  24855. * Convenience method for configuring a read-only node access.
  24856. *
  24857. * @return {StorageTextureNode} A reference to this node.
  24858. */
  24859. toReadOnly() {
  24860. return this.setAccess( NodeAccess.READ_ONLY );
  24861. }
  24862. /**
  24863. * Convenience method for configuring a write-only node access.
  24864. *
  24865. * @return {StorageTextureNode} A reference to this node.
  24866. */
  24867. toWriteOnly() {
  24868. return this.setAccess( NodeAccess.WRITE_ONLY );
  24869. }
  24870. /**
  24871. * Generates the code snippet of the storage texture node.
  24872. *
  24873. * @param {NodeBuilder} builder - The current node builder.
  24874. */
  24875. generateStore( builder ) {
  24876. const properties = builder.getNodeProperties( this );
  24877. const { uvNode, storeNode, depthNode } = properties;
  24878. const textureProperty = super.generate( builder, 'property' );
  24879. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  24880. const storeSnippet = storeNode.build( builder, 'vec4' );
  24881. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24882. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  24883. builder.addLineFlowCode( snippet, this );
  24884. }
  24885. clone() {
  24886. const newNode = super.clone();
  24887. newNode.storeNode = this.storeNode;
  24888. return newNode;
  24889. }
  24890. }
  24891. /**
  24892. * TSL function for creating a storage texture node.
  24893. *
  24894. * @tsl
  24895. * @function
  24896. * @param {StorageTexture} value - The storage texture.
  24897. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  24898. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24899. * @returns {StorageTextureNode}
  24900. */
  24901. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  24902. /**
  24903. * TODO: Explain difference to `storageTexture()`.
  24904. *
  24905. * @tsl
  24906. * @function
  24907. * @param {StorageTexture} value - The storage texture.
  24908. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24909. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24910. * @returns {StorageTextureNode}
  24911. */
  24912. const textureStore = ( value, uvNode, storeNode ) => {
  24913. const node = storageTexture( value, uvNode, storeNode );
  24914. if ( storeNode !== null ) node.toStack();
  24915. return node;
  24916. };
  24917. const normal = Fn( ( { texture, uv } ) => {
  24918. const epsilon = 0.0001;
  24919. const ret = vec3().toVar();
  24920. If( uv.x.lessThan( epsilon ), () => {
  24921. ret.assign( vec3( 1, 0, 0 ) );
  24922. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  24923. ret.assign( vec3( 0, 1, 0 ) );
  24924. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  24925. ret.assign( vec3( 0, 0, 1 ) );
  24926. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  24927. ret.assign( vec3( -1, 0, 0 ) );
  24928. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  24929. ret.assign( vec3( 0, -1, 0 ) );
  24930. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  24931. ret.assign( vec3( 0, 0, -1 ) );
  24932. } ).Else( () => {
  24933. const step = 0.01;
  24934. 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 );
  24935. 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 );
  24936. 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 );
  24937. ret.assign( vec3( x, y, z ) );
  24938. } );
  24939. return ret.normalize();
  24940. } );
  24941. /**
  24942. * This type of uniform node represents a 3D texture.
  24943. *
  24944. * @augments TextureNode
  24945. */
  24946. class Texture3DNode extends TextureNode {
  24947. static get type() {
  24948. return 'Texture3DNode';
  24949. }
  24950. /**
  24951. * Constructs a new 3D texture node.
  24952. *
  24953. * @param {Data3DTexture} value - The 3D texture.
  24954. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24955. * @param {?Node<int>} [levelNode=null] - The level node.
  24956. */
  24957. constructor( value, uvNode = null, levelNode = null ) {
  24958. super( value, uvNode, levelNode );
  24959. /**
  24960. * This flag can be used for type testing.
  24961. *
  24962. * @type {boolean}
  24963. * @readonly
  24964. * @default true
  24965. */
  24966. this.isTexture3DNode = true;
  24967. }
  24968. /**
  24969. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  24970. *
  24971. * @param {NodeBuilder} builder - The current node builder.
  24972. * @return {string} The input type.
  24973. */
  24974. getInputType( /*builder*/ ) {
  24975. return 'texture3D';
  24976. }
  24977. /**
  24978. * Returns a default uv node which is in context of 3D textures a three-dimensional
  24979. * uv node.
  24980. *
  24981. * @return {Node<vec3>} The default uv node.
  24982. */
  24983. getDefaultUV() {
  24984. return vec3( 0.5, 0.5, 0.5 );
  24985. }
  24986. /**
  24987. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  24988. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  24989. *
  24990. * @param {boolean} value - The update toggle.
  24991. */
  24992. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  24993. /**
  24994. * Overwrites the default implementation to return the unmodified uv node.
  24995. *
  24996. * @param {NodeBuilder} builder - The current node builder.
  24997. * @param {Node} uvNode - The uv node to setup.
  24998. * @return {Node} The unmodified uv node.
  24999. */
  25000. setupUV( builder, uvNode ) {
  25001. const texture = this.value;
  25002. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  25003. if ( this.sampler ) {
  25004. uvNode = uvNode.flipY();
  25005. } else {
  25006. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  25007. }
  25008. }
  25009. return uvNode;
  25010. }
  25011. /**
  25012. * Generates the uv code snippet.
  25013. *
  25014. * @param {NodeBuilder} builder - The current node builder.
  25015. * @param {Node} uvNode - The uv node to generate code for.
  25016. * @return {string} The generated code snippet.
  25017. */
  25018. generateUV( builder, uvNode ) {
  25019. return uvNode.build( builder, this.sampler === true ? 'vec3' : 'ivec3' );
  25020. }
  25021. /**
  25022. * Generates the offset code snippet.
  25023. *
  25024. * @param {NodeBuilder} builder - The current node builder.
  25025. * @param {Node} offsetNode - The offset node to generate code for.
  25026. * @return {string} The generated code snippet.
  25027. */
  25028. generateOffset( builder, offsetNode ) {
  25029. return offsetNode.build( builder, 'ivec3' );
  25030. }
  25031. /**
  25032. * TODO.
  25033. *
  25034. * @param {Node<vec3>} uvNode - The uv node .
  25035. * @return {Node<vec3>} TODO.
  25036. */
  25037. normal( uvNode ) {
  25038. return normal( { texture: this, uv: uvNode } );
  25039. }
  25040. }
  25041. /**
  25042. * TSL function for creating a 3D texture node.
  25043. *
  25044. * @tsl
  25045. * @function
  25046. * @param {Data3DTexture} value - The 3D texture.
  25047. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  25048. * @param {?Node<int>} [levelNode=null] - The level node.
  25049. * @returns {Texture3DNode}
  25050. */
  25051. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  25052. /**
  25053. * A special type of reference node that allows to link values in
  25054. * `userData` fields to node objects.
  25055. * ```js
  25056. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  25057. *
  25058. * const material = new THREE.SpriteNodeMaterial();
  25059. * material.rotationNode = userData( 'rotation', 'float' );
  25060. * ```
  25061. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  25062. * will automatically be updated when the `rotation` user data field changes.
  25063. *
  25064. * @augments ReferenceNode
  25065. */
  25066. class UserDataNode extends ReferenceNode {
  25067. static get type() {
  25068. return 'UserDataNode';
  25069. }
  25070. /**
  25071. * Constructs a new user data node.
  25072. *
  25073. * @param {string} property - The property name that should be referenced by the node.
  25074. * @param {string} inputType - The node data type of the reference.
  25075. * @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.
  25076. */
  25077. constructor( property, inputType, userData = null ) {
  25078. super( property, inputType, userData );
  25079. /**
  25080. * A reference to the `userData` object. If not provided, the `userData`
  25081. * property of the 3D object that uses the node material is evaluated.
  25082. *
  25083. * @type {?Object}
  25084. * @default null
  25085. */
  25086. this.userData = userData;
  25087. }
  25088. /**
  25089. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  25090. * `userData` field.
  25091. *
  25092. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  25093. * @return {Object} A reference to the `userData` field.
  25094. */
  25095. updateReference( state ) {
  25096. this.reference = this.userData !== null ? this.userData : state.object.userData;
  25097. return this.reference;
  25098. }
  25099. }
  25100. /**
  25101. * TSL function for creating a user data node.
  25102. *
  25103. * @tsl
  25104. * @function
  25105. * @param {string} name - The property name that should be referenced by the node.
  25106. * @param {string} inputType - The node data type of the reference.
  25107. * @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.
  25108. * @returns {UserDataNode}
  25109. */
  25110. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  25111. const _objectData = new WeakMap();
  25112. /**
  25113. * A node for representing motion or velocity vectors. Foundation
  25114. * for advanced post processing effects like motion blur or TRAA.
  25115. *
  25116. * The node keeps track of the model, view and projection matrices
  25117. * of the previous frame and uses them to compute offsets in NDC space.
  25118. * These offsets represent the final velocity.
  25119. *
  25120. * @augments TempNode
  25121. */
  25122. class VelocityNode extends TempNode {
  25123. static get type() {
  25124. return 'VelocityNode';
  25125. }
  25126. /**
  25127. * Constructs a new vertex color node.
  25128. */
  25129. constructor() {
  25130. super( 'vec2' );
  25131. /**
  25132. * The current projection matrix.
  25133. *
  25134. * @type {?Matrix4}
  25135. * @default null
  25136. */
  25137. this.projectionMatrix = null;
  25138. /**
  25139. * Overwritten since velocity nodes are updated per object.
  25140. *
  25141. * @type {string}
  25142. * @default 'object'
  25143. */
  25144. this.updateType = NodeUpdateType.OBJECT;
  25145. /**
  25146. * Overwritten since velocity nodes save data after the update.
  25147. *
  25148. * @type {string}
  25149. * @default 'object'
  25150. */
  25151. this.updateAfterType = NodeUpdateType.OBJECT;
  25152. /**
  25153. * Uniform node representing the previous model matrix in world space.
  25154. *
  25155. * @type {UniformNode<mat4>}
  25156. * @default null
  25157. */
  25158. this.previousModelWorldMatrix = uniform( new Matrix4() );
  25159. /**
  25160. * Uniform node representing the previous projection matrix.
  25161. *
  25162. * @type {UniformNode<mat4>}
  25163. * @default null
  25164. */
  25165. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  25166. /**
  25167. * Uniform node representing the previous view matrix.
  25168. *
  25169. * @type {UniformNode<mat4>}
  25170. * @default null
  25171. */
  25172. this.previousCameraViewMatrix = uniform( new Matrix4() );
  25173. }
  25174. /**
  25175. * Sets the given projection matrix.
  25176. *
  25177. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  25178. */
  25179. setProjectionMatrix( projectionMatrix ) {
  25180. this.projectionMatrix = projectionMatrix;
  25181. }
  25182. /**
  25183. * Updates velocity specific uniforms.
  25184. *
  25185. * @param {NodeFrame} frame - A reference to the current node frame.
  25186. */
  25187. update( { frameId, camera, object } ) {
  25188. const previousModelMatrix = getPreviousMatrix( object );
  25189. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  25190. //
  25191. const cameraData = getData( camera );
  25192. if ( cameraData.frameId !== frameId ) {
  25193. cameraData.frameId = frameId;
  25194. if ( cameraData.previousProjectionMatrix === undefined ) {
  25195. cameraData.previousProjectionMatrix = new Matrix4();
  25196. cameraData.previousCameraViewMatrix = new Matrix4();
  25197. cameraData.currentProjectionMatrix = new Matrix4();
  25198. cameraData.currentCameraViewMatrix = new Matrix4();
  25199. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25200. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  25201. } else {
  25202. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  25203. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  25204. }
  25205. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25206. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  25207. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  25208. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  25209. }
  25210. }
  25211. /**
  25212. * Overwritten to updated velocity specific uniforms.
  25213. *
  25214. * @param {NodeFrame} frame - A reference to the current node frame.
  25215. */
  25216. updateAfter( { object } ) {
  25217. getPreviousMatrix( object ).copy( object.matrixWorld );
  25218. }
  25219. /**
  25220. * Implements the velocity computation based on the previous and current vertex data.
  25221. *
  25222. * @param {NodeBuilder} builder - A reference to the current node builder.
  25223. * @return {Node<vec2>} The motion vector.
  25224. */
  25225. setup( /*builder*/ ) {
  25226. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  25227. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  25228. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25229. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  25230. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  25231. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  25232. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  25233. return velocity;
  25234. }
  25235. }
  25236. function getData( object ) {
  25237. let objectData = _objectData.get( object );
  25238. if ( objectData === undefined ) {
  25239. objectData = {};
  25240. _objectData.set( object, objectData );
  25241. }
  25242. return objectData;
  25243. }
  25244. function getPreviousMatrix( object, index = 0 ) {
  25245. const objectData = getData( object );
  25246. let matrix = objectData[ index ];
  25247. if ( matrix === undefined ) {
  25248. objectData[ index ] = matrix = new Matrix4();
  25249. objectData[ index ].copy( object.matrixWorld );
  25250. }
  25251. return matrix;
  25252. }
  25253. /**
  25254. * TSL object that represents the velocity of a render pass.
  25255. *
  25256. * @tsl
  25257. * @type {VelocityNode}
  25258. */
  25259. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  25260. /**
  25261. * Computes a grayscale value for the given RGB color value.
  25262. *
  25263. * @tsl
  25264. * @function
  25265. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  25266. * @return {Node<vec3>} The grayscale color.
  25267. */
  25268. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25269. return luminance( color.rgb );
  25270. } );
  25271. /**
  25272. * Super-saturates or desaturates the given RGB color.
  25273. *
  25274. * @tsl
  25275. * @function
  25276. * @param {Node<vec3>} color - The input color.
  25277. * @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.
  25278. * @return {Node<vec3>} The saturated color.
  25279. */
  25280. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25281. return adjustment.mix( luminance( color.rgb ), color.rgb );
  25282. } );
  25283. /**
  25284. * Selectively enhance the intensity of less saturated RGB colors. Can result
  25285. * in a more natural and visually appealing image with enhanced color depth
  25286. * compared to {@link ColorAdjustment#saturation}.
  25287. *
  25288. * @tsl
  25289. * @function
  25290. * @param {Node<vec3>} color - The input color.
  25291. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  25292. * @return {Node<vec3>} The updated color.
  25293. */
  25294. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25295. const average = add( color.r, color.g, color.b ).div( 3.0 );
  25296. const mx = color.r.max( color.g.max( color.b ) );
  25297. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  25298. return mix( color.rgb, mx, amt );
  25299. } );
  25300. /**
  25301. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  25302. *
  25303. * @tsl
  25304. * @function
  25305. * @param {Node<vec3>} color - The input color.
  25306. * @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.
  25307. * @return {Node<vec3>} The updated color.
  25308. */
  25309. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25310. const k = vec3( 0.57735, 0.57735, 0.57735 );
  25311. const cosAngle = adjustment.cos();
  25312. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  25313. } );
  25314. /**
  25315. * Computes the luminance for the given RGB color value.
  25316. *
  25317. * @tsl
  25318. * @function
  25319. * @param {Node<vec3>} color - The color value to compute the luminance for.
  25320. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  25321. * @return {Node<float>} The luminance.
  25322. */
  25323. const luminance = (
  25324. color,
  25325. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  25326. ) => dot( color, luminanceCoefficients );
  25327. /**
  25328. * Color Decision List (CDL) v1.2
  25329. *
  25330. * Compact representation of color grading information, defined by slope, offset, power, and
  25331. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  25332. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  25333. *
  25334. * @tsl
  25335. * @function
  25336. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  25337. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  25338. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  25339. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  25340. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  25341. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  25342. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  25343. *
  25344. * References:
  25345. * - ASC CDL v1.2
  25346. * - {@link https://blender.stackexchange.com/a/55239/43930}
  25347. * - {@link https://docs.acescentral.com/specifications/acescc/}
  25348. */
  25349. const cdl = /*@__PURE__*/ Fn( ( [
  25350. color,
  25351. slope = vec3( 1 ),
  25352. offset = vec3( 0 ),
  25353. power = vec3( 1 ),
  25354. saturation = float( 1 ),
  25355. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  25356. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  25357. ] ) => {
  25358. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  25359. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  25360. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  25361. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  25362. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  25363. const pv = v.pow( power ).toVar();
  25364. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  25365. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  25366. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  25367. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  25368. return vec4( v.rgb, color.a );
  25369. } );
  25370. /**
  25371. * Represents a posterize effect which reduces the number of colors
  25372. * in an image, resulting in a more blocky and stylized appearance.
  25373. *
  25374. * @augments TempNode
  25375. */
  25376. class PosterizeNode extends TempNode {
  25377. static get type() {
  25378. return 'PosterizeNode';
  25379. }
  25380. /**
  25381. * Constructs a new posterize node.
  25382. *
  25383. * @param {Node} sourceNode - The input color.
  25384. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25385. */
  25386. constructor( sourceNode, stepsNode ) {
  25387. super();
  25388. /**
  25389. * The input color.
  25390. *
  25391. * @type {Node}
  25392. */
  25393. this.sourceNode = sourceNode;
  25394. /**
  25395. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25396. *
  25397. * @type {Node}
  25398. */
  25399. this.stepsNode = stepsNode;
  25400. }
  25401. setup() {
  25402. const { sourceNode, stepsNode } = this;
  25403. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  25404. }
  25405. }
  25406. /**
  25407. * TSL function for creating a posterize node.
  25408. *
  25409. * @tsl
  25410. * @function
  25411. * @param {Node} sourceNode - The input color.
  25412. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25413. * @returns {PosterizeNode}
  25414. */
  25415. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  25416. const _size = /*@__PURE__*/ new Vector2();
  25417. /**
  25418. * Represents the texture of a pass node.
  25419. *
  25420. * @augments TextureNode
  25421. */
  25422. class PassTextureNode extends TextureNode {
  25423. static get type() {
  25424. return 'PassTextureNode';
  25425. }
  25426. /**
  25427. * Constructs a new pass texture node.
  25428. *
  25429. * @param {PassNode} passNode - The pass node.
  25430. * @param {Texture} texture - The output texture.
  25431. */
  25432. constructor( passNode, texture ) {
  25433. super( texture );
  25434. /**
  25435. * A reference to the pass node.
  25436. *
  25437. * @type {PassNode}
  25438. */
  25439. this.passNode = passNode;
  25440. this.setUpdateMatrix( false );
  25441. }
  25442. setup( builder ) {
  25443. this.passNode.build( builder );
  25444. return super.setup( builder );
  25445. }
  25446. clone() {
  25447. return new this.constructor( this.passNode, this.value );
  25448. }
  25449. }
  25450. /**
  25451. * An extension of `PassTextureNode` which allows to manage more than one
  25452. * internal texture. Relevant for the `getPreviousTexture()` related API.
  25453. *
  25454. * @augments PassTextureNode
  25455. */
  25456. class PassMultipleTextureNode extends PassTextureNode {
  25457. static get type() {
  25458. return 'PassMultipleTextureNode';
  25459. }
  25460. /**
  25461. * Constructs a new pass texture node.
  25462. *
  25463. * @param {PassNode} passNode - The pass node.
  25464. * @param {string} textureName - The output texture name.
  25465. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  25466. */
  25467. constructor( passNode, textureName, previousTexture = false ) {
  25468. // null is passed to the super call since this class does not
  25469. // use an external texture for rendering pass data into. Instead
  25470. // the texture is managed by the pass node itself
  25471. super( passNode, null );
  25472. /**
  25473. * The output texture name.
  25474. *
  25475. * @type {string}
  25476. */
  25477. this.textureName = textureName;
  25478. /**
  25479. * Whether previous frame data should be used or not.
  25480. *
  25481. * @type {boolean}
  25482. */
  25483. this.previousTexture = previousTexture;
  25484. }
  25485. /**
  25486. * Updates the texture reference of this node.
  25487. */
  25488. updateTexture() {
  25489. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  25490. }
  25491. setup( builder ) {
  25492. this.updateTexture();
  25493. return super.setup( builder );
  25494. }
  25495. clone() {
  25496. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  25497. newNode.uvNode = this.uvNode;
  25498. newNode.levelNode = this.levelNode;
  25499. newNode.biasNode = this.biasNode;
  25500. newNode.sampler = this.sampler;
  25501. newNode.depthNode = this.depthNode;
  25502. newNode.compareNode = this.compareNode;
  25503. newNode.gradNode = this.gradNode;
  25504. newNode.offsetNode = this.offsetNode;
  25505. return newNode;
  25506. }
  25507. }
  25508. /**
  25509. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  25510. * This pass produces a render for the given scene and camera and can provide multiple outputs
  25511. * via MRT for further processing.
  25512. *
  25513. * ```js
  25514. * const postProcessing = new PostProcessing( renderer );
  25515. *
  25516. * const scenePass = pass( scene, camera );
  25517. *
  25518. * postProcessing.outputNode = scenePass;
  25519. * ```
  25520. *
  25521. * @augments TempNode
  25522. */
  25523. class PassNode extends TempNode {
  25524. static get type() {
  25525. return 'PassNode';
  25526. }
  25527. /**
  25528. * Constructs a new pass node.
  25529. *
  25530. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  25531. * @param {Scene} scene - A reference to the scene.
  25532. * @param {Camera} camera - A reference to the camera.
  25533. * @param {Object} options - Options for the internal render target.
  25534. */
  25535. constructor( scope, scene, camera, options = {} ) {
  25536. super( 'vec4' );
  25537. /**
  25538. * The scope of the pass. The scope determines whether the node outputs color or depth.
  25539. *
  25540. * @type {('color'|'depth')}
  25541. */
  25542. this.scope = scope;
  25543. /**
  25544. * A reference to the scene.
  25545. *
  25546. * @type {Scene}
  25547. */
  25548. this.scene = scene;
  25549. /**
  25550. * A reference to the camera.
  25551. *
  25552. * @type {Camera}
  25553. */
  25554. this.camera = camera;
  25555. /**
  25556. * Options for the internal render target.
  25557. *
  25558. * @type {Object}
  25559. */
  25560. this.options = options;
  25561. /**
  25562. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  25563. *
  25564. * @private
  25565. * @type {number}
  25566. * @default 1
  25567. */
  25568. this._pixelRatio = 1;
  25569. /**
  25570. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  25571. * @private
  25572. * @type {number}
  25573. * @default 1
  25574. */
  25575. this._width = 1;
  25576. /**
  25577. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  25578. * @private
  25579. * @type {number}
  25580. * @default 1
  25581. */
  25582. this._height = 1;
  25583. const depthTexture = new DepthTexture();
  25584. depthTexture.isRenderTargetTexture = true;
  25585. //depthTexture.type = FloatType;
  25586. depthTexture.name = 'depth';
  25587. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  25588. renderTarget.texture.name = 'output';
  25589. renderTarget.depthTexture = depthTexture;
  25590. /**
  25591. * The pass's render target.
  25592. *
  25593. * @type {RenderTarget}
  25594. */
  25595. this.renderTarget = renderTarget;
  25596. /**
  25597. * A dictionary holding the internal result textures.
  25598. *
  25599. * @private
  25600. * @type {Object<string, Texture>}
  25601. */
  25602. this._textures = {
  25603. output: renderTarget.texture,
  25604. depth: depthTexture
  25605. };
  25606. /**
  25607. * A dictionary holding the internal texture nodes.
  25608. *
  25609. * @private
  25610. * @type {Object<string, TextureNode>}
  25611. */
  25612. this._textureNodes = {};
  25613. /**
  25614. * A dictionary holding the internal depth nodes.
  25615. *
  25616. * @private
  25617. * @type {Object}
  25618. */
  25619. this._linearDepthNodes = {};
  25620. /**
  25621. * A dictionary holding the internal viewZ nodes.
  25622. *
  25623. * @private
  25624. * @type {Object}
  25625. */
  25626. this._viewZNodes = {};
  25627. /**
  25628. * A dictionary holding the texture data of the previous frame.
  25629. * Used for computing velocity/motion vectors.
  25630. *
  25631. * @private
  25632. * @type {Object<string, Texture>}
  25633. */
  25634. this._previousTextures = {};
  25635. /**
  25636. * A dictionary holding the texture nodes of the previous frame.
  25637. * Used for computing velocity/motion vectors.
  25638. *
  25639. * @private
  25640. * @type {Object<string, TextureNode>}
  25641. */
  25642. this._previousTextureNodes = {};
  25643. /**
  25644. * The `near` property of the camera as a uniform.
  25645. *
  25646. * @private
  25647. * @type {UniformNode}
  25648. */
  25649. this._cameraNear = uniform( 0 );
  25650. /**
  25651. * The `far` property of the camera as a uniform.
  25652. *
  25653. * @private
  25654. * @type {UniformNode}
  25655. */
  25656. this._cameraFar = uniform( 0 );
  25657. /**
  25658. * A MRT node configuring the MRT settings.
  25659. *
  25660. * @private
  25661. * @type {?MRTNode}
  25662. * @default null
  25663. */
  25664. this._mrt = null;
  25665. /**
  25666. * Layer object for configuring the camera that is used
  25667. * to produce the pass.
  25668. *
  25669. * @private
  25670. * @type {?Layers}
  25671. * @default null
  25672. */
  25673. this._layers = null;
  25674. /**
  25675. * Scales the resolution of the internal render target.
  25676. *
  25677. * @private
  25678. * @type {number}
  25679. * @default 1
  25680. */
  25681. this._resolution = 1;
  25682. /**
  25683. * Custom viewport definition.
  25684. *
  25685. * @private
  25686. * @type {?Vector4}
  25687. * @default null
  25688. */
  25689. this._viewport = null;
  25690. /**
  25691. * Custom scissor definition.
  25692. *
  25693. * @private
  25694. * @type {?Vector4}
  25695. * @default null
  25696. */
  25697. this._scissor = null;
  25698. /**
  25699. * This flag can be used for type testing.
  25700. *
  25701. * @type {boolean}
  25702. * @readonly
  25703. * @default true
  25704. */
  25705. this.isPassNode = true;
  25706. /**
  25707. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  25708. * scene once per frame in its {@link PassNode#updateBefore} method.
  25709. *
  25710. * @type {string}
  25711. * @default 'frame'
  25712. */
  25713. this.updateBeforeType = NodeUpdateType.FRAME;
  25714. /**
  25715. * This flag is used for global cache.
  25716. *
  25717. * @type {boolean}
  25718. * @default true
  25719. */
  25720. this.global = true;
  25721. }
  25722. /**
  25723. * Sets the resolution for the pass.
  25724. * The resolution is a factor that is multiplied with the renderer's width and height.
  25725. *
  25726. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  25727. * @return {PassNode} A reference to this pass.
  25728. */
  25729. setResolution( resolution ) {
  25730. this._resolution = resolution;
  25731. return this;
  25732. }
  25733. /**
  25734. * Gets the current resolution of the pass.
  25735. *
  25736. * @return {number} The current resolution. A value of `1` means full resolution.
  25737. */
  25738. getResolution() {
  25739. return this._resolution;
  25740. }
  25741. /**
  25742. * Sets the layer configuration that should be used when rendering the pass.
  25743. *
  25744. * @param {Layers} layers - The layers object to set.
  25745. * @return {PassNode} A reference to this pass.
  25746. */
  25747. setLayers( layers ) {
  25748. this._layers = layers;
  25749. return this;
  25750. }
  25751. /**
  25752. * Gets the current layer configuration of the pass.
  25753. *
  25754. * @return {?Layers} .
  25755. */
  25756. getLayers() {
  25757. return this._layers;
  25758. }
  25759. /**
  25760. * Sets the given MRT node to setup MRT for this pass.
  25761. *
  25762. * @param {MRTNode} mrt - The MRT object.
  25763. * @return {PassNode} A reference to this pass.
  25764. */
  25765. setMRT( mrt ) {
  25766. this._mrt = mrt;
  25767. return this;
  25768. }
  25769. /**
  25770. * Returns the current MRT node.
  25771. *
  25772. * @return {MRTNode} The current MRT node.
  25773. */
  25774. getMRT() {
  25775. return this._mrt;
  25776. }
  25777. /**
  25778. * Returns the texture for the given output name.
  25779. *
  25780. * @param {string} name - The output name to get the texture for.
  25781. * @return {Texture} The texture.
  25782. */
  25783. getTexture( name ) {
  25784. let texture = this._textures[ name ];
  25785. if ( texture === undefined ) {
  25786. const refTexture = this.renderTarget.texture;
  25787. texture = refTexture.clone();
  25788. texture.name = name;
  25789. this._textures[ name ] = texture;
  25790. this.renderTarget.textures.push( texture );
  25791. }
  25792. return texture;
  25793. }
  25794. /**
  25795. * Returns the texture holding the data of the previous frame for the given output name.
  25796. *
  25797. * @param {string} name - The output name to get the texture for.
  25798. * @return {Texture} The texture holding the data of the previous frame.
  25799. */
  25800. getPreviousTexture( name ) {
  25801. let texture = this._previousTextures[ name ];
  25802. if ( texture === undefined ) {
  25803. texture = this.getTexture( name ).clone();
  25804. this._previousTextures[ name ] = texture;
  25805. }
  25806. return texture;
  25807. }
  25808. /**
  25809. * Switches current and previous textures for the given output name.
  25810. *
  25811. * @param {string} name - The output name.
  25812. */
  25813. toggleTexture( name ) {
  25814. const prevTexture = this._previousTextures[ name ];
  25815. if ( prevTexture !== undefined ) {
  25816. const texture = this._textures[ name ];
  25817. const index = this.renderTarget.textures.indexOf( texture );
  25818. this.renderTarget.textures[ index ] = prevTexture;
  25819. this._textures[ name ] = prevTexture;
  25820. this._previousTextures[ name ] = texture;
  25821. this._textureNodes[ name ].updateTexture();
  25822. this._previousTextureNodes[ name ].updateTexture();
  25823. }
  25824. }
  25825. /**
  25826. * Returns the texture node for the given output name.
  25827. *
  25828. * @param {string} [name='output'] - The output name to get the texture node for.
  25829. * @return {TextureNode} The texture node.
  25830. */
  25831. getTextureNode( name = 'output' ) {
  25832. let textureNode = this._textureNodes[ name ];
  25833. if ( textureNode === undefined ) {
  25834. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  25835. textureNode.updateTexture();
  25836. this._textureNodes[ name ] = textureNode;
  25837. }
  25838. return textureNode;
  25839. }
  25840. /**
  25841. * Returns the previous texture node for the given output name.
  25842. *
  25843. * @param {string} [name='output'] - The output name to get the previous texture node for.
  25844. * @return {TextureNode} The previous texture node.
  25845. */
  25846. getPreviousTextureNode( name = 'output' ) {
  25847. let textureNode = this._previousTextureNodes[ name ];
  25848. if ( textureNode === undefined ) {
  25849. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  25850. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  25851. textureNode.updateTexture();
  25852. this._previousTextureNodes[ name ] = textureNode;
  25853. }
  25854. return textureNode;
  25855. }
  25856. /**
  25857. * Returns a viewZ node of this pass.
  25858. *
  25859. * @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.
  25860. * @return {Node} The viewZ node.
  25861. */
  25862. getViewZNode( name = 'depth' ) {
  25863. let viewZNode = this._viewZNodes[ name ];
  25864. if ( viewZNode === undefined ) {
  25865. const cameraNear = this._cameraNear;
  25866. const cameraFar = this._cameraFar;
  25867. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  25868. }
  25869. return viewZNode;
  25870. }
  25871. /**
  25872. * Returns a linear depth node of this pass.
  25873. *
  25874. * @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.
  25875. * @return {Node} The linear depth node.
  25876. */
  25877. getLinearDepthNode( name = 'depth' ) {
  25878. let linearDepthNode = this._linearDepthNodes[ name ];
  25879. if ( linearDepthNode === undefined ) {
  25880. const cameraNear = this._cameraNear;
  25881. const cameraFar = this._cameraFar;
  25882. const viewZNode = this.getViewZNode( name );
  25883. // TODO: just if ( builder.camera.isPerspectiveCamera )
  25884. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  25885. }
  25886. return linearDepthNode;
  25887. }
  25888. /**
  25889. * Precompiles the pass.
  25890. *
  25891. * Note that this method must be called after the pass configuration is complete.
  25892. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  25893. *
  25894. * @async
  25895. * @param {Renderer} renderer - The renderer.
  25896. * @return {Promise} A Promise that resolves when the compile has been finished.
  25897. * @see {@link Renderer#compileAsync}
  25898. */
  25899. async compileAsync( renderer ) {
  25900. const currentRenderTarget = renderer.getRenderTarget();
  25901. const currentMRT = renderer.getMRT();
  25902. renderer.setRenderTarget( this.renderTarget );
  25903. renderer.setMRT( this._mrt );
  25904. await renderer.compileAsync( this.scene, this.camera );
  25905. renderer.setRenderTarget( currentRenderTarget );
  25906. renderer.setMRT( currentMRT );
  25907. }
  25908. setup( { renderer } ) {
  25909. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  25910. this.renderTarget.texture.type = renderer.getColorBufferType();
  25911. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  25912. }
  25913. updateBefore( frame ) {
  25914. const { renderer } = frame;
  25915. const { scene } = this;
  25916. let camera;
  25917. let pixelRatio;
  25918. const outputRenderTarget = renderer.getOutputRenderTarget();
  25919. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  25920. pixelRatio = 1;
  25921. camera = renderer.xr.getCamera();
  25922. renderer.xr.updateCamera( camera );
  25923. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  25924. } else {
  25925. camera = this.camera;
  25926. pixelRatio = renderer.getPixelRatio();
  25927. renderer.getSize( _size );
  25928. }
  25929. this._pixelRatio = pixelRatio;
  25930. this.setSize( _size.width, _size.height );
  25931. const currentRenderTarget = renderer.getRenderTarget();
  25932. const currentMRT = renderer.getMRT();
  25933. const currentMask = camera.layers.mask;
  25934. this._cameraNear.value = camera.near;
  25935. this._cameraFar.value = camera.far;
  25936. if ( this._layers !== null ) {
  25937. camera.layers.mask = this._layers.mask;
  25938. }
  25939. for ( const name in this._previousTextures ) {
  25940. this.toggleTexture( name );
  25941. }
  25942. renderer.setRenderTarget( this.renderTarget );
  25943. renderer.setMRT( this._mrt );
  25944. renderer.render( scene, camera );
  25945. renderer.setRenderTarget( currentRenderTarget );
  25946. renderer.setMRT( currentMRT );
  25947. camera.layers.mask = currentMask;
  25948. }
  25949. /**
  25950. * Sets the size of the pass's render target. Honors the pixel ratio.
  25951. *
  25952. * @param {number} width - The width to set.
  25953. * @param {number} height - The height to set.
  25954. */
  25955. setSize( width, height ) {
  25956. this._width = width;
  25957. this._height = height;
  25958. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  25959. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  25960. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25961. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  25962. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  25963. }
  25964. /**
  25965. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  25966. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25967. * with `null` as the single argument.
  25968. *
  25969. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  25970. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  25971. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  25972. * @param {number} width - The width of the scissor box in logical pixel unit.
  25973. * @param {number} height - The height of the scissor box in logical pixel unit.
  25974. */
  25975. setScissor( x, y, width, height ) {
  25976. if ( x === null ) {
  25977. this._scissor = null;
  25978. } else {
  25979. if ( this._scissor === null ) this._scissor = new Vector4();
  25980. if ( x.isVector4 ) {
  25981. this._scissor.copy( x );
  25982. } else {
  25983. this._scissor.set( x, y, width, height );
  25984. }
  25985. this._scissor.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25986. }
  25987. }
  25988. /**
  25989. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  25990. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25991. * with `null` as the single argument.
  25992. *
  25993. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25994. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25995. * @param {number} width - The width of the viewport in logical pixel unit.
  25996. * @param {number} height - The height of the viewport in logical pixel unit.
  25997. */
  25998. setViewport( x, y, width, height ) {
  25999. if ( x === null ) {
  26000. this._viewport = null;
  26001. } else {
  26002. if ( this._viewport === null ) this._viewport = new Vector4();
  26003. if ( x.isVector4 ) {
  26004. this._viewport.copy( x );
  26005. } else {
  26006. this._viewport.set( x, y, width, height );
  26007. }
  26008. this._viewport.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  26009. }
  26010. }
  26011. /**
  26012. * Sets the pixel ratio the pass's render target and updates the size.
  26013. *
  26014. * @param {number} pixelRatio - The pixel ratio to set.
  26015. */
  26016. setPixelRatio( pixelRatio ) {
  26017. this._pixelRatio = pixelRatio;
  26018. this.setSize( this._width, this._height );
  26019. }
  26020. /**
  26021. * Frees internal resources. Should be called when the node is no longer in use.
  26022. */
  26023. dispose() {
  26024. this.renderTarget.dispose();
  26025. }
  26026. }
  26027. /**
  26028. * @static
  26029. * @type {'color'}
  26030. * @default 'color'
  26031. */
  26032. PassNode.COLOR = 'color';
  26033. /**
  26034. * @static
  26035. * @type {'depth'}
  26036. * @default 'depth'
  26037. */
  26038. PassNode.DEPTH = 'depth';
  26039. /**
  26040. * TSL function for creating a pass node.
  26041. *
  26042. * @tsl
  26043. * @function
  26044. * @param {Scene} scene - A reference to the scene.
  26045. * @param {Camera} camera - A reference to the camera.
  26046. * @param {Object} options - Options for the internal render target.
  26047. * @returns {PassNode}
  26048. */
  26049. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  26050. /**
  26051. * TSL function for creating a pass texture node.
  26052. *
  26053. * @tsl
  26054. * @function
  26055. * @param {PassNode} pass - The pass node.
  26056. * @param {Texture} texture - The output texture.
  26057. * @returns {PassTextureNode}
  26058. */
  26059. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  26060. /**
  26061. * TSL function for creating a depth pass node.
  26062. *
  26063. * @tsl
  26064. * @function
  26065. * @param {Scene} scene - A reference to the scene.
  26066. * @param {Camera} camera - A reference to the camera.
  26067. * @param {Object} options - Options for the internal render target.
  26068. * @returns {PassNode}
  26069. */
  26070. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  26071. /**
  26072. * Represents a render pass for producing a toon outline effect on compatible objects.
  26073. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  26074. * will receive the outline.
  26075. *
  26076. * ```js
  26077. * const postProcessing = new PostProcessing( renderer );
  26078. *
  26079. * const scenePass = toonOutlinePass( scene, camera );
  26080. *
  26081. * postProcessing.outputNode = scenePass;
  26082. * ```
  26083. * @augments PassNode
  26084. */
  26085. class ToonOutlinePassNode extends PassNode {
  26086. static get type() {
  26087. return 'ToonOutlinePassNode';
  26088. }
  26089. /**
  26090. * Constructs a new outline pass node.
  26091. *
  26092. * @param {Scene} scene - A reference to the scene.
  26093. * @param {Camera} camera - A reference to the camera.
  26094. * @param {Node} colorNode - Defines the outline's color.
  26095. * @param {Node} thicknessNode - Defines the outline's thickness.
  26096. * @param {Node} alphaNode - Defines the outline's alpha.
  26097. */
  26098. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  26099. super( PassNode.COLOR, scene, camera );
  26100. /**
  26101. * Defines the outline's color.
  26102. *
  26103. * @type {Node}
  26104. */
  26105. this.colorNode = colorNode;
  26106. /**
  26107. * Defines the outline's thickness.
  26108. *
  26109. * @type {Node}
  26110. */
  26111. this.thicknessNode = thicknessNode;
  26112. /**
  26113. * Defines the outline's alpha.
  26114. *
  26115. * @type {Node}
  26116. */
  26117. this.alphaNode = alphaNode;
  26118. /**
  26119. * An internal material cache.
  26120. *
  26121. * @private
  26122. * @type {WeakMap<Material, NodeMaterial>}
  26123. */
  26124. this._materialCache = new WeakMap();
  26125. }
  26126. updateBefore( frame ) {
  26127. const { renderer } = frame;
  26128. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26129. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  26130. // only render outline for supported materials
  26131. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  26132. if ( material.wireframe === false ) {
  26133. const outlineMaterial = this._getOutlineMaterial( material );
  26134. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  26135. }
  26136. }
  26137. // default
  26138. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  26139. } );
  26140. super.updateBefore( frame );
  26141. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26142. }
  26143. /**
  26144. * Creates the material used for outline rendering.
  26145. *
  26146. * @private
  26147. * @return {NodeMaterial} The outline material.
  26148. */
  26149. _createMaterial() {
  26150. const material = new NodeMaterial();
  26151. material.isMeshToonOutlineMaterial = true;
  26152. material.name = 'Toon_Outline';
  26153. material.side = BackSide;
  26154. // vertex node
  26155. const outlineNormal = normalLocal.negate();
  26156. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  26157. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  26158. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  26159. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  26160. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  26161. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  26162. // color node
  26163. material.colorNode = vec4( this.colorNode, this.alphaNode );
  26164. return material;
  26165. }
  26166. /**
  26167. * For the given toon material, this method returns a corresponding
  26168. * outline material.
  26169. *
  26170. * @private
  26171. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  26172. * @return {NodeMaterial} The outline material.
  26173. */
  26174. _getOutlineMaterial( originalMaterial ) {
  26175. let outlineMaterial = this._materialCache.get( originalMaterial );
  26176. if ( outlineMaterial === undefined ) {
  26177. outlineMaterial = this._createMaterial();
  26178. this._materialCache.set( originalMaterial, outlineMaterial );
  26179. }
  26180. return outlineMaterial;
  26181. }
  26182. }
  26183. /**
  26184. * TSL function for creating a toon outline pass node.
  26185. *
  26186. * @tsl
  26187. * @function
  26188. * @param {Scene} scene - A reference to the scene.
  26189. * @param {Camera} camera - A reference to the camera.
  26190. * @param {Color} color - Defines the outline's color.
  26191. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  26192. * @param {number} [alpha=1] - Defines the outline's alpha.
  26193. * @returns {ToonOutlinePassNode}
  26194. */
  26195. 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 ) ) );
  26196. /**
  26197. * Linear tone mapping, exposure only.
  26198. *
  26199. * @tsl
  26200. * @function
  26201. * @param {Node<vec3>} color - The color that should be tone mapped.
  26202. * @param {Node<float>} exposure - The exposure.
  26203. * @return {Node<vec3>} The tone mapped color.
  26204. */
  26205. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26206. return color.mul( exposure ).clamp();
  26207. } ).setLayout( {
  26208. name: 'linearToneMapping',
  26209. type: 'vec3',
  26210. inputs: [
  26211. { name: 'color', type: 'vec3' },
  26212. { name: 'exposure', type: 'float' }
  26213. ]
  26214. } );
  26215. /**
  26216. * Reinhard tone mapping.
  26217. *
  26218. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  26219. *
  26220. * @tsl
  26221. * @function
  26222. * @param {Node<vec3>} color - The color that should be tone mapped.
  26223. * @param {Node<float>} exposure - The exposure.
  26224. * @return {Node<vec3>} The tone mapped color.
  26225. */
  26226. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26227. color = color.mul( exposure );
  26228. return color.div( color.add( 1.0 ) ).clamp();
  26229. } ).setLayout( {
  26230. name: 'reinhardToneMapping',
  26231. type: 'vec3',
  26232. inputs: [
  26233. { name: 'color', type: 'vec3' },
  26234. { name: 'exposure', type: 'float' }
  26235. ]
  26236. } );
  26237. /**
  26238. * Cineon tone mapping.
  26239. *
  26240. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  26241. *
  26242. * @tsl
  26243. * @function
  26244. * @param {Node<vec3>} color - The color that should be tone mapped.
  26245. * @param {Node<float>} exposure - The exposure.
  26246. * @return {Node<vec3>} The tone mapped color.
  26247. */
  26248. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26249. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  26250. color = color.mul( exposure );
  26251. color = color.sub( 0.004 ).max( 0.0 );
  26252. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  26253. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  26254. return a.div( b ).pow( 2.2 );
  26255. } ).setLayout( {
  26256. name: 'cineonToneMapping',
  26257. type: 'vec3',
  26258. inputs: [
  26259. { name: 'color', type: 'vec3' },
  26260. { name: 'exposure', type: 'float' }
  26261. ]
  26262. } );
  26263. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  26264. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26265. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  26266. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  26267. return a.div( b );
  26268. } );
  26269. /**
  26270. * ACESFilmic tone mapping.
  26271. *
  26272. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  26273. *
  26274. * @tsl
  26275. * @function
  26276. * @param {Node<vec3>} color - The color that should be tone mapped.
  26277. * @param {Node<float>} exposure - The exposure.
  26278. * @return {Node<vec3>} The tone mapped color.
  26279. */
  26280. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26281. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  26282. const ACESInputMat = mat3(
  26283. 0.59719, 0.35458, 0.04823,
  26284. 0.07600, 0.90834, 0.01566,
  26285. 0.02840, 0.13383, 0.83777
  26286. );
  26287. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  26288. const ACESOutputMat = mat3(
  26289. 1.60475, -0.53108, -0.07367,
  26290. -0.10208, 1.10813, -605e-5,
  26291. -327e-5, -0.07276, 1.07602
  26292. );
  26293. color = color.mul( exposure ).div( 0.6 );
  26294. color = ACESInputMat.mul( color );
  26295. // Apply RRT and ODT
  26296. color = RRTAndODTFit( color );
  26297. color = ACESOutputMat.mul( color );
  26298. // Clamp to [0, 1]
  26299. return color.clamp();
  26300. } ).setLayout( {
  26301. name: 'acesFilmicToneMapping',
  26302. type: 'vec3',
  26303. inputs: [
  26304. { name: 'color', type: 'vec3' },
  26305. { name: 'exposure', type: 'float' }
  26306. ]
  26307. } );
  26308. 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 ) );
  26309. 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 ) );
  26310. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26311. const x = vec3( x_immutable ).toVar();
  26312. const x2 = vec3( x.mul( x ) ).toVar();
  26313. const x4 = vec3( x2.mul( x2 ) ).toVar();
  26314. 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 ) ) ) );
  26315. } );
  26316. /**
  26317. * AgX tone mapping.
  26318. *
  26319. * @tsl
  26320. * @function
  26321. * @param {Node<vec3>} color - The color that should be tone mapped.
  26322. * @param {Node<float>} exposure - The exposure.
  26323. * @return {Node<vec3>} The tone mapped color.
  26324. */
  26325. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26326. const colortone = vec3( color ).toVar();
  26327. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  26328. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  26329. const AgxMinEv = float( -12.47393 );
  26330. const AgxMaxEv = float( 4.026069 );
  26331. colortone.mulAssign( exposure );
  26332. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  26333. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  26334. colortone.assign( max$1( colortone, 1e-10 ) );
  26335. colortone.assign( log2( colortone ) );
  26336. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  26337. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26338. colortone.assign( agxDefaultContrastApprox( colortone ) );
  26339. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  26340. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  26341. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  26342. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26343. return colortone;
  26344. } ).setLayout( {
  26345. name: 'agxToneMapping',
  26346. type: 'vec3',
  26347. inputs: [
  26348. { name: 'color', type: 'vec3' },
  26349. { name: 'exposure', type: 'float' }
  26350. ]
  26351. } );
  26352. /**
  26353. * Neutral tone mapping.
  26354. *
  26355. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  26356. *
  26357. * @tsl
  26358. * @function
  26359. * @param {Node<vec3>} color - The color that should be tone mapped.
  26360. * @param {Node<float>} exposure - The exposure.
  26361. * @return {Node<vec3>} The tone mapped color.
  26362. */
  26363. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26364. const StartCompression = float( 0.8 - 0.04 );
  26365. const Desaturation = float( 0.15 );
  26366. color = color.mul( exposure );
  26367. const x = min$1( color.r, min$1( color.g, color.b ) );
  26368. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  26369. color.subAssign( offset );
  26370. const peak = max$1( color.r, max$1( color.g, color.b ) );
  26371. If( peak.lessThan( StartCompression ), () => {
  26372. return color;
  26373. } );
  26374. const d = sub( 1, StartCompression );
  26375. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  26376. color.mulAssign( newPeak.div( peak ) );
  26377. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  26378. return mix( color, vec3( newPeak ), g );
  26379. } ).setLayout( {
  26380. name: 'neutralToneMapping',
  26381. type: 'vec3',
  26382. inputs: [
  26383. { name: 'color', type: 'vec3' },
  26384. { name: 'exposure', type: 'float' }
  26385. ]
  26386. } );
  26387. /**
  26388. * This class represents native code sections. It is the base
  26389. * class for modules like {@link FunctionNode} which allows to implement
  26390. * functions with native shader languages.
  26391. *
  26392. * @augments Node
  26393. */
  26394. class CodeNode extends Node {
  26395. static get type() {
  26396. return 'CodeNode';
  26397. }
  26398. /**
  26399. * Constructs a new code node.
  26400. *
  26401. * @param {string} [code=''] - The native code.
  26402. * @param {Array<Node>} [includes=[]] - An array of includes.
  26403. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26404. */
  26405. constructor( code = '', includes = [], language = '' ) {
  26406. super( 'code' );
  26407. /**
  26408. * This flag can be used for type testing.
  26409. *
  26410. * @type {boolean}
  26411. * @readonly
  26412. * @default true
  26413. */
  26414. this.isCodeNode = true;
  26415. /**
  26416. * This flag is used for global cache.
  26417. *
  26418. * @type {boolean}
  26419. * @default true
  26420. */
  26421. this.global = true;
  26422. /**
  26423. * The native code.
  26424. *
  26425. * @type {string}
  26426. * @default ''
  26427. */
  26428. this.code = code;
  26429. /**
  26430. * An array of includes
  26431. *
  26432. * @type {Array<Node>}
  26433. * @default []
  26434. */
  26435. this.includes = includes;
  26436. /**
  26437. * The used language.
  26438. *
  26439. * @type {('js'|'wgsl'|'glsl')}
  26440. * @default ''
  26441. */
  26442. this.language = language;
  26443. }
  26444. /**
  26445. * Sets the includes of this code node.
  26446. *
  26447. * @param {Array<Node>} includes - The includes to set.
  26448. * @return {CodeNode} A reference to this node.
  26449. */
  26450. setIncludes( includes ) {
  26451. this.includes = includes;
  26452. return this;
  26453. }
  26454. /**
  26455. * Returns the includes of this code node.
  26456. *
  26457. * @param {NodeBuilder} builder - The current node builder.
  26458. * @return {Array<Node>} The includes.
  26459. */
  26460. getIncludes( /*builder*/ ) {
  26461. return this.includes;
  26462. }
  26463. generate( builder ) {
  26464. const includes = this.getIncludes( builder );
  26465. for ( const include of includes ) {
  26466. include.build( builder );
  26467. }
  26468. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  26469. nodeCode.code = this.code;
  26470. return nodeCode.code;
  26471. }
  26472. serialize( data ) {
  26473. super.serialize( data );
  26474. data.code = this.code;
  26475. data.language = this.language;
  26476. }
  26477. deserialize( data ) {
  26478. super.deserialize( data );
  26479. this.code = data.code;
  26480. this.language = data.language;
  26481. }
  26482. }
  26483. /**
  26484. * TSL function for creating a code node.
  26485. *
  26486. * @tsl
  26487. * @function
  26488. * @param {string} [code] - The native code.
  26489. * @param {?Array<Node>} [includes=[]] - An array of includes.
  26490. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26491. * @returns {CodeNode}
  26492. */
  26493. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  26494. /**
  26495. * TSL function for creating a JS code node.
  26496. *
  26497. * @tsl
  26498. * @function
  26499. * @param {string} src - The native code.
  26500. * @param {Array<Node>} includes - An array of includes.
  26501. * @returns {CodeNode}
  26502. */
  26503. const js = ( src, includes ) => code( src, includes, 'js' );
  26504. /**
  26505. * TSL function for creating a WGSL code node.
  26506. *
  26507. * @tsl
  26508. * @function
  26509. * @param {string} src - The native code.
  26510. * @param {Array<Node>} includes - An array of includes.
  26511. * @returns {CodeNode}
  26512. */
  26513. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  26514. /**
  26515. * TSL function for creating a GLSL code node.
  26516. *
  26517. * @tsl
  26518. * @function
  26519. * @param {string} src - The native code.
  26520. * @param {Array<Node>} includes - An array of includes.
  26521. * @returns {CodeNode}
  26522. */
  26523. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  26524. /**
  26525. * This class represents a native shader function. It can be used to implement
  26526. * certain aspects of a node material with native shader code. There are two predefined
  26527. * TSL functions for easier usage.
  26528. *
  26529. * - `wgslFn`: Creates a WGSL function node.
  26530. * - `glslFn`: Creates a GLSL function node.
  26531. *
  26532. * A basic example with one include looks like so:
  26533. *
  26534. * ```js
  26535. * const desaturateWGSLFn = wgslFn( `
  26536. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  26537. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  26538. * return vec3<f32>( dot( lum, color ) );
  26539. * }`
  26540. *);
  26541. * const someWGSLFn = wgslFn( `
  26542. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  26543. * return desaturate( color );
  26544. * }
  26545. * `, [ desaturateWGSLFn ] );
  26546. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  26547. *```
  26548. * @augments CodeNode
  26549. */
  26550. class FunctionNode extends CodeNode {
  26551. static get type() {
  26552. return 'FunctionNode';
  26553. }
  26554. /**
  26555. * Constructs a new function node.
  26556. *
  26557. * @param {string} [code=''] - The native code.
  26558. * @param {Array<Node>} [includes=[]] - An array of includes.
  26559. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26560. */
  26561. constructor( code = '', includes = [], language = '' ) {
  26562. super( code, includes, language );
  26563. }
  26564. /**
  26565. * Returns the type of this function node.
  26566. *
  26567. * @param {NodeBuilder} builder - The current node builder.
  26568. * @return {string} The type.
  26569. */
  26570. getNodeType( builder ) {
  26571. return this.getNodeFunction( builder ).type;
  26572. }
  26573. /**
  26574. * Returns the type of a member of this function node.
  26575. *
  26576. * @param {NodeBuilder} builder - The current node builder.
  26577. * @param {string} name - The name of the member.
  26578. * @return {string} The type of the member.
  26579. */
  26580. getMemberType( builder, name ) {
  26581. const type = this.getNodeType( builder );
  26582. const structType = builder.getStructTypeNode( type );
  26583. return structType.getMemberType( builder, name );
  26584. }
  26585. /**
  26586. * Returns the inputs of this function node.
  26587. *
  26588. * @param {NodeBuilder} builder - The current node builder.
  26589. * @return {Array<NodeFunctionInput>} The inputs.
  26590. */
  26591. getInputs( builder ) {
  26592. return this.getNodeFunction( builder ).inputs;
  26593. }
  26594. /**
  26595. * Returns the node function for this function node.
  26596. *
  26597. * @param {NodeBuilder} builder - The current node builder.
  26598. * @return {NodeFunction} The node function.
  26599. */
  26600. getNodeFunction( builder ) {
  26601. const nodeData = builder.getDataFromNode( this );
  26602. let nodeFunction = nodeData.nodeFunction;
  26603. if ( nodeFunction === undefined ) {
  26604. nodeFunction = builder.parser.parseFunction( this.code );
  26605. nodeData.nodeFunction = nodeFunction;
  26606. }
  26607. return nodeFunction;
  26608. }
  26609. generate( builder, output ) {
  26610. super.generate( builder );
  26611. const nodeFunction = this.getNodeFunction( builder );
  26612. const name = nodeFunction.name;
  26613. const type = nodeFunction.type;
  26614. const nodeCode = builder.getCodeFromNode( this, type );
  26615. if ( name !== '' ) {
  26616. // use a custom property name
  26617. nodeCode.name = name;
  26618. }
  26619. const propertyName = builder.getPropertyName( nodeCode );
  26620. const code = this.getNodeFunction( builder ).getCode( propertyName );
  26621. nodeCode.code = code + '\n';
  26622. if ( output === 'property' ) {
  26623. return propertyName;
  26624. } else {
  26625. return builder.format( `${ propertyName }()`, type, output );
  26626. }
  26627. }
  26628. }
  26629. const nativeFn = ( code, includes = [], language = '' ) => {
  26630. for ( let i = 0; i < includes.length; i ++ ) {
  26631. const include = includes[ i ];
  26632. // TSL Function: glslFn, wgslFn
  26633. if ( typeof include === 'function' ) {
  26634. includes[ i ] = include.functionNode;
  26635. }
  26636. }
  26637. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  26638. const fn = ( ...params ) => functionNode.call( ...params );
  26639. fn.functionNode = functionNode;
  26640. return fn;
  26641. };
  26642. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  26643. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  26644. /**
  26645. * `ScriptableNode` uses this class to manage script inputs and outputs.
  26646. *
  26647. * @augments Node
  26648. */
  26649. class ScriptableValueNode extends Node {
  26650. static get type() {
  26651. return 'ScriptableValueNode';
  26652. }
  26653. /**
  26654. * Constructs a new scriptable node.
  26655. *
  26656. * @param {any} [value=null] - The value.
  26657. */
  26658. constructor( value = null ) {
  26659. super();
  26660. /**
  26661. * A reference to the value.
  26662. *
  26663. * @private
  26664. * @default null
  26665. */
  26666. this._value = value;
  26667. /**
  26668. * Depending on the type of `_value`, this property might cache parsed data.
  26669. *
  26670. * @private
  26671. * @default null
  26672. */
  26673. this._cache = null;
  26674. /**
  26675. * If this node represents an input, this property represents the input type.
  26676. *
  26677. * @type {?string}
  26678. * @default null
  26679. */
  26680. this.inputType = null;
  26681. /**
  26682. * If this node represents an output, this property represents the output type.
  26683. *
  26684. * @type {?string}
  26685. * @default null
  26686. */
  26687. this.outputType = null;
  26688. /**
  26689. * An event dispatcher for managing events.
  26690. *
  26691. * @type {EventDispatcher}
  26692. */
  26693. this.events = new EventDispatcher();
  26694. /**
  26695. * This flag can be used for type testing.
  26696. *
  26697. * @type {boolean}
  26698. * @readonly
  26699. * @default true
  26700. */
  26701. this.isScriptableValueNode = true;
  26702. }
  26703. /**
  26704. * Whether this node represents an output or not.
  26705. *
  26706. * @type {boolean}
  26707. * @readonly
  26708. * @default true
  26709. */
  26710. get isScriptableOutputNode() {
  26711. return this.outputType !== null;
  26712. }
  26713. set value( val ) {
  26714. if ( this._value === val ) return;
  26715. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  26716. URL.revokeObjectURL( this._cache );
  26717. this._cache = null;
  26718. }
  26719. this._value = val;
  26720. this.events.dispatchEvent( { type: 'change' } );
  26721. this.refresh();
  26722. }
  26723. /**
  26724. * The node's value.
  26725. *
  26726. * @type {any}
  26727. */
  26728. get value() {
  26729. return this._value;
  26730. }
  26731. /**
  26732. * Dispatches the `refresh` event.
  26733. */
  26734. refresh() {
  26735. this.events.dispatchEvent( { type: 'refresh' } );
  26736. }
  26737. /**
  26738. * The `value` property usually represents a node or even binary data in form of array buffers.
  26739. * In this case, this method tries to return the actual value behind the complex type.
  26740. *
  26741. * @return {any} The value.
  26742. */
  26743. getValue() {
  26744. const value = this.value;
  26745. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  26746. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  26747. } else if ( value && value.value !== null && value.value !== undefined && (
  26748. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  26749. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  26750. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  26751. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  26752. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  26753. ( this.inputType === 'Color' && value.value.isColor ) ||
  26754. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  26755. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  26756. ) ) {
  26757. return value.value;
  26758. }
  26759. return this._cache || value;
  26760. }
  26761. /**
  26762. * Overwritten since the node type is inferred from the value.
  26763. *
  26764. * @param {NodeBuilder} builder - The current node builder.
  26765. * @return {string} The node type.
  26766. */
  26767. getNodeType( builder ) {
  26768. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  26769. }
  26770. setup() {
  26771. return this.value && this.value.isNode ? this.value : float();
  26772. }
  26773. serialize( data ) {
  26774. super.serialize( data );
  26775. if ( this.value !== null ) {
  26776. if ( this.inputType === 'ArrayBuffer' ) {
  26777. data.value = arrayBufferToBase64( this.value );
  26778. } else {
  26779. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  26780. }
  26781. } else {
  26782. data.value = null;
  26783. }
  26784. data.inputType = this.inputType;
  26785. data.outputType = this.outputType;
  26786. }
  26787. deserialize( data ) {
  26788. super.deserialize( data );
  26789. let value = null;
  26790. if ( data.value !== null ) {
  26791. if ( data.inputType === 'ArrayBuffer' ) {
  26792. value = base64ToArrayBuffer( data.value );
  26793. } else if ( data.inputType === 'Texture' ) {
  26794. value = data.meta.textures[ data.value ];
  26795. } else {
  26796. value = data.meta.nodes[ data.value ] || null;
  26797. }
  26798. }
  26799. this.value = value;
  26800. this.inputType = data.inputType;
  26801. this.outputType = data.outputType;
  26802. }
  26803. }
  26804. /**
  26805. * TSL function for creating a scriptable value node.
  26806. *
  26807. * @tsl
  26808. * @function
  26809. * @param {any} [value] - The value.
  26810. * @returns {ScriptableValueNode}
  26811. */
  26812. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  26813. /**
  26814. * A Map-like data structure for managing resources of scriptable nodes.
  26815. *
  26816. * @augments Map
  26817. */
  26818. class Resources extends Map {
  26819. get( key, callback = null, ...params ) {
  26820. if ( this.has( key ) ) return super.get( key );
  26821. if ( callback !== null ) {
  26822. const value = callback( ...params );
  26823. this.set( key, value );
  26824. return value;
  26825. }
  26826. }
  26827. }
  26828. class Parameters {
  26829. constructor( scriptableNode ) {
  26830. this.scriptableNode = scriptableNode;
  26831. }
  26832. get parameters() {
  26833. return this.scriptableNode.parameters;
  26834. }
  26835. get layout() {
  26836. return this.scriptableNode.getLayout();
  26837. }
  26838. getInputLayout( id ) {
  26839. return this.scriptableNode.getInputLayout( id );
  26840. }
  26841. get( name ) {
  26842. const param = this.parameters[ name ];
  26843. const value = param ? param.getValue() : null;
  26844. return value;
  26845. }
  26846. }
  26847. /**
  26848. * Defines the resources (e.g. namespaces) of scriptable nodes.
  26849. *
  26850. * @type {Resources}
  26851. */
  26852. const ScriptableNodeResources = new Resources();
  26853. /**
  26854. * This type of node allows to implement nodes with custom scripts. The script
  26855. * section is represented as an instance of `CodeNode` written with JavaScript.
  26856. * The script itself must adhere to a specific structure.
  26857. *
  26858. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  26859. * - layout: The layout object defines the script's interface (inputs and outputs).
  26860. *
  26861. * ```js
  26862. * ScriptableNodeResources.set( 'TSL', TSL );
  26863. *
  26864. * const scriptableNode = scriptable( js( `
  26865. * layout = {
  26866. * outputType: 'node',
  26867. * elements: [
  26868. * { name: 'source', inputType: 'node' },
  26869. * ]
  26870. * };
  26871. *
  26872. * const { mul, oscSine } = TSL;
  26873. *
  26874. * function main() {
  26875. * const source = parameters.get( 'source' ) || float();
  26876. * return mul( source, oscSine() ) );
  26877. * }
  26878. *
  26879. * ` ) );
  26880. *
  26881. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  26882. *
  26883. * const material = new THREE.MeshBasicNodeMaterial();
  26884. * material.colorNode = scriptableNode;
  26885. * ```
  26886. *
  26887. * @augments Node
  26888. */
  26889. class ScriptableNode extends Node {
  26890. static get type() {
  26891. return 'ScriptableNode';
  26892. }
  26893. /**
  26894. * Constructs a new scriptable node.
  26895. *
  26896. * @param {?CodeNode} [codeNode=null] - The code node.
  26897. * @param {Object} [parameters={}] - The parameters definition.
  26898. */
  26899. constructor( codeNode = null, parameters = {} ) {
  26900. super();
  26901. /**
  26902. * The code node.
  26903. *
  26904. * @type {?CodeNode}
  26905. * @default null
  26906. */
  26907. this.codeNode = codeNode;
  26908. /**
  26909. * The parameters definition.
  26910. *
  26911. * @type {Object}
  26912. * @default {}
  26913. */
  26914. this.parameters = parameters;
  26915. this._local = new Resources();
  26916. this._output = scriptableValue( null );
  26917. this._outputs = {};
  26918. this._source = this.source;
  26919. this._method = null;
  26920. this._object = null;
  26921. this._value = null;
  26922. this._needsOutputUpdate = true;
  26923. this.onRefresh = this.onRefresh.bind( this );
  26924. /**
  26925. * This flag can be used for type testing.
  26926. *
  26927. * @type {boolean}
  26928. * @readonly
  26929. * @default true
  26930. */
  26931. this.isScriptableNode = true;
  26932. }
  26933. /**
  26934. * The source code of the scriptable node.
  26935. *
  26936. * @type {string}
  26937. */
  26938. get source() {
  26939. return this.codeNode ? this.codeNode.code : '';
  26940. }
  26941. /**
  26942. * Sets the reference of a local script variable.
  26943. *
  26944. * @param {string} name - The variable name.
  26945. * @param {Object} value - The reference to set.
  26946. * @return {Resources} The resource map
  26947. */
  26948. setLocal( name, value ) {
  26949. return this._local.set( name, value );
  26950. }
  26951. /**
  26952. * Gets the value of a local script variable.
  26953. *
  26954. * @param {string} name - The variable name.
  26955. * @return {Object} The value.
  26956. */
  26957. getLocal( name ) {
  26958. return this._local.get( name );
  26959. }
  26960. /**
  26961. * Event listener for the `refresh` event.
  26962. */
  26963. onRefresh() {
  26964. this._refresh();
  26965. }
  26966. /**
  26967. * Returns an input from the layout with the given id/name.
  26968. *
  26969. * @param {string} id - The id/name of the input.
  26970. * @return {Object} The element entry.
  26971. */
  26972. getInputLayout( id ) {
  26973. for ( const element of this.getLayout() ) {
  26974. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  26975. return element;
  26976. }
  26977. }
  26978. }
  26979. /**
  26980. * Returns an output from the layout with the given id/name.
  26981. *
  26982. * @param {string} id - The id/name of the output.
  26983. * @return {Object} The element entry.
  26984. */
  26985. getOutputLayout( id ) {
  26986. for ( const element of this.getLayout() ) {
  26987. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  26988. return element;
  26989. }
  26990. }
  26991. }
  26992. /**
  26993. * Defines a script output for the given name and value.
  26994. *
  26995. * @param {string} name - The name of the output.
  26996. * @param {Node} value - The node value.
  26997. * @return {ScriptableNode} A reference to this node.
  26998. */
  26999. setOutput( name, value ) {
  27000. const outputs = this._outputs;
  27001. if ( outputs[ name ] === undefined ) {
  27002. outputs[ name ] = scriptableValue( value );
  27003. } else {
  27004. outputs[ name ].value = value;
  27005. }
  27006. return this;
  27007. }
  27008. /**
  27009. * Returns a script output for the given name.
  27010. *
  27011. * @param {string} name - The name of the output.
  27012. * @return {ScriptableValueNode} The node value.
  27013. */
  27014. getOutput( name ) {
  27015. return this._outputs[ name ];
  27016. }
  27017. /**
  27018. * Returns a parameter for the given name
  27019. *
  27020. * @param {string} name - The name of the parameter.
  27021. * @return {ScriptableValueNode} The node value.
  27022. */
  27023. getParameter( name ) {
  27024. return this.parameters[ name ];
  27025. }
  27026. /**
  27027. * Sets a value for the given parameter name.
  27028. *
  27029. * @param {string} name - The parameter name.
  27030. * @param {any} value - The parameter value.
  27031. * @return {ScriptableNode} A reference to this node.
  27032. */
  27033. setParameter( name, value ) {
  27034. const parameters = this.parameters;
  27035. if ( value && value.isScriptableNode ) {
  27036. this.deleteParameter( name );
  27037. parameters[ name ] = value;
  27038. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  27039. } else if ( value && value.isScriptableValueNode ) {
  27040. this.deleteParameter( name );
  27041. parameters[ name ] = value;
  27042. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27043. } else if ( parameters[ name ] === undefined ) {
  27044. parameters[ name ] = scriptableValue( value );
  27045. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  27046. } else {
  27047. parameters[ name ].value = value;
  27048. }
  27049. return this;
  27050. }
  27051. /**
  27052. * Returns the value of this node which is the value of
  27053. * the default output.
  27054. *
  27055. * @return {Node} The value.
  27056. */
  27057. getValue() {
  27058. return this.getDefaultOutput().getValue();
  27059. }
  27060. /**
  27061. * Deletes a parameter from the script.
  27062. *
  27063. * @param {string} name - The parameter to remove.
  27064. * @return {ScriptableNode} A reference to this node.
  27065. */
  27066. deleteParameter( name ) {
  27067. let valueNode = this.parameters[ name ];
  27068. if ( valueNode ) {
  27069. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27070. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  27071. }
  27072. return this;
  27073. }
  27074. /**
  27075. * Deletes all parameters from the script.
  27076. *
  27077. * @return {ScriptableNode} A reference to this node.
  27078. */
  27079. clearParameters() {
  27080. for ( const name of Object.keys( this.parameters ) ) {
  27081. this.deleteParameter( name );
  27082. }
  27083. this.needsUpdate = true;
  27084. return this;
  27085. }
  27086. /**
  27087. * Calls a function from the script.
  27088. *
  27089. * @param {string} name - The function name.
  27090. * @param {...any} params - A list of parameters.
  27091. * @return {any} The result of the function call.
  27092. */
  27093. call( name, ...params ) {
  27094. const object = this.getObject();
  27095. const method = object[ name ];
  27096. if ( typeof method === 'function' ) {
  27097. return method( ...params );
  27098. }
  27099. }
  27100. /**
  27101. * Asynchronously calls a function from the script.
  27102. *
  27103. * @param {string} name - The function name.
  27104. * @param {...any} params - A list of parameters.
  27105. * @return {Promise<any>} The result of the function call.
  27106. */
  27107. async callAsync( name, ...params ) {
  27108. const object = this.getObject();
  27109. const method = object[ name ];
  27110. if ( typeof method === 'function' ) {
  27111. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  27112. }
  27113. }
  27114. /**
  27115. * Overwritten since the node types is inferred from the script's output.
  27116. *
  27117. * @param {NodeBuilder} builder - The current node builder
  27118. * @return {string} The node type.
  27119. */
  27120. getNodeType( builder ) {
  27121. return this.getDefaultOutputNode().getNodeType( builder );
  27122. }
  27123. /**
  27124. * Refreshes the script node.
  27125. *
  27126. * @param {?string} [output=null] - An optional output.
  27127. */
  27128. refresh( output = null ) {
  27129. if ( output !== null ) {
  27130. this.getOutput( output ).refresh();
  27131. } else {
  27132. this._refresh();
  27133. }
  27134. }
  27135. /**
  27136. * Returns an object representation of the script.
  27137. *
  27138. * @return {Object} The result object.
  27139. */
  27140. getObject() {
  27141. if ( this.needsUpdate ) this.dispose();
  27142. if ( this._object !== null ) return this._object;
  27143. //
  27144. const refresh = () => this.refresh();
  27145. const setOutput = ( id, value ) => this.setOutput( id, value );
  27146. const parameters = new Parameters( this );
  27147. const THREE = ScriptableNodeResources.get( 'THREE' );
  27148. const TSL = ScriptableNodeResources.get( 'TSL' );
  27149. const method = this.getMethod();
  27150. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  27151. this._object = method( ...params );
  27152. const layout = this._object.layout;
  27153. if ( layout ) {
  27154. if ( layout.cache === false ) {
  27155. this._local.clear();
  27156. }
  27157. // default output
  27158. this._output.outputType = layout.outputType || null;
  27159. if ( Array.isArray( layout.elements ) ) {
  27160. for ( const element of layout.elements ) {
  27161. const id = element.id || element.name;
  27162. if ( element.inputType ) {
  27163. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  27164. this.getParameter( id ).inputType = element.inputType;
  27165. }
  27166. if ( element.outputType ) {
  27167. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  27168. this.getOutput( id ).outputType = element.outputType;
  27169. }
  27170. }
  27171. }
  27172. }
  27173. return this._object;
  27174. }
  27175. deserialize( data ) {
  27176. super.deserialize( data );
  27177. for ( const name in this.parameters ) {
  27178. let valueNode = this.parameters[ name ];
  27179. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27180. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  27181. }
  27182. }
  27183. /**
  27184. * Returns the layout of the script.
  27185. *
  27186. * @return {Object} The script's layout.
  27187. */
  27188. getLayout() {
  27189. return this.getObject().layout;
  27190. }
  27191. /**
  27192. * Returns default node output of the script.
  27193. *
  27194. * @return {Node} The default node output.
  27195. */
  27196. getDefaultOutputNode() {
  27197. const output = this.getDefaultOutput().value;
  27198. if ( output && output.isNode ) {
  27199. return output;
  27200. }
  27201. return float();
  27202. }
  27203. /**
  27204. * Returns default output of the script.
  27205. *
  27206. * @return {ScriptableValueNode} The default output.
  27207. */
  27208. getDefaultOutput() {
  27209. return this._exec()._output;
  27210. }
  27211. /**
  27212. * Returns a function created from the node's script.
  27213. *
  27214. * @return {Function} The function representing the node's code.
  27215. */
  27216. getMethod() {
  27217. if ( this.needsUpdate ) this.dispose();
  27218. if ( this._method !== null ) return this._method;
  27219. //
  27220. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  27221. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  27222. const properties = interfaceProps.join( ', ' );
  27223. const declarations = 'var ' + properties + '; var output = {};\n';
  27224. const returns = '\nreturn { ...output, ' + properties + ' };';
  27225. const code = declarations + this.codeNode.code + returns;
  27226. //
  27227. this._method = new Function( ...parametersProps, code );
  27228. return this._method;
  27229. }
  27230. /**
  27231. * Frees all internal resources.
  27232. */
  27233. dispose() {
  27234. if ( this._method === null ) return;
  27235. if ( this._object && typeof this._object.dispose === 'function' ) {
  27236. this._object.dispose();
  27237. }
  27238. this._method = null;
  27239. this._object = null;
  27240. this._source = null;
  27241. this._value = null;
  27242. this._needsOutputUpdate = true;
  27243. this._output.value = null;
  27244. this._outputs = {};
  27245. }
  27246. setup() {
  27247. return this.getDefaultOutputNode();
  27248. }
  27249. getCacheKey( force ) {
  27250. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  27251. for ( const param in this.parameters ) {
  27252. values.push( this.parameters[ param ].getCacheKey( force ) );
  27253. }
  27254. return hashArray( values );
  27255. }
  27256. set needsUpdate( value ) {
  27257. if ( value === true ) this.dispose();
  27258. }
  27259. get needsUpdate() {
  27260. return this.source !== this._source;
  27261. }
  27262. /**
  27263. * Executes the `main` function of the script.
  27264. *
  27265. * @private
  27266. * @return {ScriptableNode} A reference to this node.
  27267. */
  27268. _exec() {
  27269. if ( this.codeNode === null ) return this;
  27270. if ( this._needsOutputUpdate === true ) {
  27271. this._value = this.call( 'main' );
  27272. this._needsOutputUpdate = false;
  27273. }
  27274. this._output.value = this._value;
  27275. return this;
  27276. }
  27277. /**
  27278. * Executes the refresh.
  27279. *
  27280. * @private
  27281. */
  27282. _refresh() {
  27283. this.needsUpdate = true;
  27284. this._exec();
  27285. this._output.refresh();
  27286. }
  27287. }
  27288. /**
  27289. * TSL function for creating a scriptable node.
  27290. *
  27291. * @tsl
  27292. * @function
  27293. * @param {CodeNode} [codeNode] - The code node.
  27294. * @param {?Object} [parameters={}] - The parameters definition.
  27295. * @returns {ScriptableNode}
  27296. */
  27297. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  27298. /**
  27299. * Returns a node that represents the `z` coordinate in view space
  27300. * for the current fragment. It's a different representation of the
  27301. * default depth value.
  27302. *
  27303. * This value can be part of a computation that defines how the fog
  27304. * density increases when moving away from the camera.
  27305. *
  27306. * @param {NodeBuilder} builder - The current node builder.
  27307. * @return {Node} The viewZ node.
  27308. */
  27309. function getViewZNode( builder ) {
  27310. let viewZ;
  27311. const getViewZ = builder.context.getViewZ;
  27312. if ( getViewZ !== undefined ) {
  27313. viewZ = getViewZ( this );
  27314. }
  27315. return ( viewZ || positionView.z ).negate();
  27316. }
  27317. /**
  27318. * Constructs a new range factor node.
  27319. *
  27320. * @tsl
  27321. * @function
  27322. * @param {Node} near - Defines the near value.
  27323. * @param {Node} far - Defines the far value.
  27324. */
  27325. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  27326. const viewZ = getViewZNode( builder );
  27327. return smoothstep( near, far, viewZ );
  27328. } );
  27329. /**
  27330. * Represents an exponential squared fog. This type of fog gives
  27331. * a clear view near the camera and a faster than exponentially
  27332. * densening fog farther from the camera.
  27333. *
  27334. * @tsl
  27335. * @function
  27336. * @param {Node} density - Defines the fog density.
  27337. */
  27338. const densityFogFactor = Fn( ( [ density ], builder ) => {
  27339. const viewZ = getViewZNode( builder );
  27340. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  27341. } );
  27342. /**
  27343. * This class can be used to configure a fog for the scene.
  27344. * Nodes of this type are assigned to `Scene.fogNode`.
  27345. *
  27346. * @tsl
  27347. * @function
  27348. * @param {Node} color - Defines the color of the fog.
  27349. * @param {Node} factor - Defines how the fog is factored in the scene.
  27350. */
  27351. const fog = Fn( ( [ color, factor ] ) => {
  27352. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  27353. } );
  27354. // Deprecated
  27355. /**
  27356. * @tsl
  27357. * @function
  27358. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  27359. *
  27360. * @param {Node} color
  27361. * @param {Node} near
  27362. * @param {Node} far
  27363. * @returns {Function}
  27364. */
  27365. function rangeFog( color, near, far ) { // @deprecated, r171
  27366. warn( 'TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  27367. return fog( color, rangeFogFactor( near, far ) );
  27368. }
  27369. /**
  27370. * @tsl
  27371. * @function
  27372. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  27373. *
  27374. * @param {Node} color
  27375. * @param {Node} density
  27376. * @returns {Function}
  27377. */
  27378. function densityFog( color, density ) { // @deprecated, r171
  27379. warn( 'TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  27380. return fog( color, densityFogFactor( density ) );
  27381. }
  27382. let min = null;
  27383. let max = null;
  27384. /**
  27385. * `RangeNode` generates random instanced attribute data in a defined range.
  27386. * An exemplary use case for this utility node is to generate random per-instance
  27387. * colors:
  27388. * ```js
  27389. * const material = new MeshBasicNodeMaterial();
  27390. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  27391. * const mesh = new InstancedMesh( geometry, material, count );
  27392. * ```
  27393. * @augments Node
  27394. */
  27395. class RangeNode extends Node {
  27396. static get type() {
  27397. return 'RangeNode';
  27398. }
  27399. /**
  27400. * Constructs a new range node.
  27401. *
  27402. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27403. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27404. */
  27405. constructor( minNode = float(), maxNode = float() ) {
  27406. super();
  27407. /**
  27408. * A node defining the lower bound of the range.
  27409. *
  27410. * @type {Node<any>}
  27411. * @default float()
  27412. */
  27413. this.minNode = minNode;
  27414. /**
  27415. * A node defining the upper bound of the range.
  27416. *
  27417. * @type {Node<any>}
  27418. * @default float()
  27419. */
  27420. this.maxNode = maxNode;
  27421. }
  27422. /**
  27423. * Returns the vector length which is computed based on the range definition.
  27424. *
  27425. * @param {NodeBuilder} builder - The current node builder.
  27426. * @return {number} The vector length.
  27427. */
  27428. getVectorLength( builder ) {
  27429. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  27430. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  27431. return minLength > maxLength ? minLength : maxLength;
  27432. }
  27433. /**
  27434. * This method is overwritten since the node type is inferred from range definition.
  27435. *
  27436. * @param {NodeBuilder} builder - The current node builder.
  27437. * @return {string} The node type.
  27438. */
  27439. getNodeType( builder ) {
  27440. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  27441. }
  27442. setup( builder ) {
  27443. const object = builder.object;
  27444. let output = null;
  27445. if ( object.count > 1 ) {
  27446. const minValue = this.minNode.value;
  27447. const maxValue = this.maxNode.value;
  27448. const minLength = builder.getTypeLength( getValueType( minValue ) );
  27449. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  27450. min = min || new Vector4();
  27451. max = max || new Vector4();
  27452. min.setScalar( 0 );
  27453. max.setScalar( 0 );
  27454. if ( minLength === 1 ) min.setScalar( minValue );
  27455. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  27456. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  27457. if ( maxLength === 1 ) max.setScalar( maxValue );
  27458. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  27459. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  27460. const stride = 4;
  27461. const length = stride * object.count;
  27462. const array = new Float32Array( length );
  27463. for ( let i = 0; i < length; i ++ ) {
  27464. const index = i % stride;
  27465. const minElementValue = min.getComponent( index );
  27466. const maxElementValue = max.getComponent( index );
  27467. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  27468. }
  27469. const nodeType = this.getNodeType( builder );
  27470. if ( object.count <= 4096 ) {
  27471. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  27472. } else {
  27473. // TODO: Improve anonymous buffer attribute creation removing this part
  27474. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  27475. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  27476. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  27477. }
  27478. } else {
  27479. output = float( 0 );
  27480. }
  27481. return output;
  27482. }
  27483. }
  27484. /**
  27485. * TSL function for creating a range node.
  27486. *
  27487. * @tsl
  27488. * @function
  27489. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27490. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27491. * @returns {RangeNode}
  27492. */
  27493. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  27494. /**
  27495. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  27496. * about the currently running dispatch and/or the device it is running on.
  27497. *
  27498. * This node can only be used with a WebGPU backend.
  27499. *
  27500. * @augments Node
  27501. */
  27502. class ComputeBuiltinNode extends Node {
  27503. static get type() {
  27504. return 'ComputeBuiltinNode';
  27505. }
  27506. /**
  27507. * Constructs a new compute builtin node.
  27508. *
  27509. * @param {string} builtinName - The built-in name.
  27510. * @param {string} nodeType - The node type.
  27511. */
  27512. constructor( builtinName, nodeType ) {
  27513. super( nodeType );
  27514. /**
  27515. * The built-in name.
  27516. *
  27517. * @private
  27518. * @type {string}
  27519. */
  27520. this._builtinName = builtinName;
  27521. }
  27522. /**
  27523. * This method is overwritten since hash is derived from the built-in name.
  27524. *
  27525. * @param {NodeBuilder} builder - The current node builder.
  27526. * @return {string} The hash.
  27527. */
  27528. getHash( builder ) {
  27529. return this.getBuiltinName( builder );
  27530. }
  27531. /**
  27532. * This method is overwritten since the node type is simply derived from `nodeType`..
  27533. *
  27534. * @param {NodeBuilder} builder - The current node builder.
  27535. * @return {string} The node type.
  27536. */
  27537. getNodeType( /*builder*/ ) {
  27538. return this.nodeType;
  27539. }
  27540. /**
  27541. * Sets the builtin name.
  27542. *
  27543. * @param {string} builtinName - The built-in name.
  27544. * @return {ComputeBuiltinNode} A reference to this node.
  27545. */
  27546. setBuiltinName( builtinName ) {
  27547. this._builtinName = builtinName;
  27548. return this;
  27549. }
  27550. /**
  27551. * Returns the builtin name.
  27552. *
  27553. * @param {NodeBuilder} builder - The current node builder.
  27554. * @return {string} The builtin name.
  27555. */
  27556. getBuiltinName( /*builder*/ ) {
  27557. return this._builtinName;
  27558. }
  27559. /**
  27560. * Whether the current node builder has the builtin or not.
  27561. *
  27562. * @param {NodeBuilder} builder - The current node builder.
  27563. * @return {boolean} Whether the builder has the builtin or not.
  27564. */
  27565. hasBuiltin( builder ) {
  27566. return builder.hasBuiltin( this._builtinName );
  27567. }
  27568. generate( builder, output ) {
  27569. const builtinName = this.getBuiltinName( builder );
  27570. const nodeType = this.getNodeType( builder );
  27571. if ( builder.shaderStage === 'compute' ) {
  27572. return builder.format( builtinName, nodeType, output );
  27573. } else {
  27574. warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  27575. return builder.generateConst( nodeType );
  27576. }
  27577. }
  27578. serialize( data ) {
  27579. super.serialize( data );
  27580. data.global = this.global;
  27581. data._builtinName = this._builtinName;
  27582. }
  27583. deserialize( data ) {
  27584. super.deserialize( data );
  27585. this.global = data.global;
  27586. this._builtinName = data._builtinName;
  27587. }
  27588. }
  27589. /**
  27590. * TSL function for creating a compute builtin node.
  27591. *
  27592. * @tsl
  27593. * @function
  27594. * @param {string} name - The built-in name.
  27595. * @param {string} nodeType - The node type.
  27596. * @returns {ComputeBuiltinNode}
  27597. */
  27598. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  27599. /**
  27600. * Represents the number of workgroups dispatched by the compute shader.
  27601. * ```js
  27602. * // Run 512 invocations/threads with a workgroup size of 128.
  27603. * const computeFn = Fn(() => {
  27604. *
  27605. * // numWorkgroups.x = 4
  27606. * storageBuffer.element(0).assign(numWorkgroups.x)
  27607. *
  27608. * })().compute(512, [128]);
  27609. *
  27610. * // Run 512 invocations/threads with the default workgroup size of 64.
  27611. * const computeFn = Fn(() => {
  27612. *
  27613. * // numWorkgroups.x = 8
  27614. * storageBuffer.element(0).assign(numWorkgroups.x)
  27615. *
  27616. * })().compute(512);
  27617. * ```
  27618. *
  27619. * @tsl
  27620. * @type {ComputeBuiltinNode<uvec3>}
  27621. */
  27622. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  27623. /**
  27624. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  27625. * ```js
  27626. * // Execute 12 compute threads with a workgroup size of 3.
  27627. * const computeFn = Fn( () => {
  27628. *
  27629. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  27630. *
  27631. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  27632. *
  27633. * } ).Else( () => {
  27634. *
  27635. * storageBuffer.element( instanceIndex ).assign( 0 );
  27636. *
  27637. * } );
  27638. *
  27639. * } )().compute( 12, [ 3 ] );
  27640. *
  27641. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  27642. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  27643. * ```
  27644. *
  27645. * @tsl
  27646. * @type {ComputeBuiltinNode<uvec3>}
  27647. */
  27648. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  27649. /**
  27650. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  27651. *
  27652. * @tsl
  27653. * @type {ComputeBuiltinNode<uvec3>}
  27654. */
  27655. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  27656. /**
  27657. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  27658. *
  27659. * @tsl
  27660. * @type {ComputeBuiltinNode<uvec3>}
  27661. */
  27662. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  27663. /**
  27664. * A device dependent variable that exposes the size of the current invocation's subgroup.
  27665. *
  27666. * @tsl
  27667. * @type {ComputeBuiltinNode<uint>}
  27668. */
  27669. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  27670. /**
  27671. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  27672. *
  27673. * This node can only be used with a WebGPU backend.
  27674. *
  27675. * @augments Node
  27676. */
  27677. class BarrierNode extends Node {
  27678. /**
  27679. * Constructs a new barrier node.
  27680. *
  27681. * @param {string} scope - The scope defines the behavior of the node.
  27682. */
  27683. constructor( scope ) {
  27684. super();
  27685. this.scope = scope;
  27686. }
  27687. generate( builder ) {
  27688. const { scope } = this;
  27689. const { renderer } = builder;
  27690. if ( renderer.backend.isWebGLBackend === true ) {
  27691. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  27692. } else {
  27693. builder.addLineFlowCode( `${scope}Barrier()`, this );
  27694. }
  27695. }
  27696. }
  27697. /**
  27698. * TSL function for creating a barrier node.
  27699. *
  27700. * @tsl
  27701. * @function
  27702. * @param {string} scope - The scope defines the behavior of the node..
  27703. * @returns {BarrierNode}
  27704. */
  27705. const barrier = nodeProxy( BarrierNode );
  27706. /**
  27707. * TSL function for creating a workgroup barrier. All compute shader
  27708. * invocations must wait for each invocation within a workgroup to
  27709. * complete before the barrier can be surpassed.
  27710. *
  27711. * @tsl
  27712. * @function
  27713. * @returns {BarrierNode}
  27714. */
  27715. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  27716. /**
  27717. * TSL function for creating a storage barrier. All invocations must
  27718. * wait for each access to variables within the 'storage' address space
  27719. * to complete before the barrier can be passed.
  27720. *
  27721. * @tsl
  27722. * @function
  27723. * @returns {BarrierNode}
  27724. */
  27725. const storageBarrier = () => barrier( 'storage' ).toStack();
  27726. /**
  27727. * TSL function for creating a texture barrier. All invocations must
  27728. * wait for each access to variables within the 'texture' address space
  27729. * to complete before the barrier can be passed.
  27730. *
  27731. * @tsl
  27732. * @function
  27733. * @returns {BarrierNode}
  27734. */
  27735. const textureBarrier = () => barrier( 'texture' ).toStack();
  27736. /**
  27737. * Represents an element of a 'workgroup' scoped buffer.
  27738. *
  27739. * @augments ArrayElementNode
  27740. */
  27741. class WorkgroupInfoElementNode extends ArrayElementNode {
  27742. /**
  27743. * Constructs a new workgroup info element node.
  27744. *
  27745. * @param {Node} workgroupInfoNode - The workgroup info node.
  27746. * @param {Node} indexNode - The index node that defines the element access.
  27747. */
  27748. constructor( workgroupInfoNode, indexNode ) {
  27749. super( workgroupInfoNode, indexNode );
  27750. /**
  27751. * This flag can be used for type testing.
  27752. *
  27753. * @type {boolean}
  27754. * @readonly
  27755. * @default true
  27756. */
  27757. this.isWorkgroupInfoElementNode = true;
  27758. }
  27759. generate( builder, output ) {
  27760. let snippet;
  27761. const isAssignContext = builder.context.assign;
  27762. snippet = super.generate( builder );
  27763. if ( isAssignContext !== true ) {
  27764. const type = this.getNodeType( builder );
  27765. snippet = builder.format( snippet, type, output );
  27766. }
  27767. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  27768. return snippet;
  27769. }
  27770. }
  27771. /**
  27772. * A node allowing the user to create a 'workgroup' scoped buffer within the
  27773. * context of a compute shader. Typically, workgroup scoped buffers are
  27774. * created to hold data that is transferred from a global storage scope into
  27775. * a local workgroup scope. For invocations within a workgroup, data
  27776. * access speeds on 'workgroup' scoped buffers can be significantly faster
  27777. * than similar access operations on globally accessible storage buffers.
  27778. *
  27779. * This node can only be used with a WebGPU backend.
  27780. *
  27781. * @augments Node
  27782. */
  27783. class WorkgroupInfoNode extends Node {
  27784. /**
  27785. * Constructs a new buffer scoped to type scope.
  27786. *
  27787. * @param {string} scope - TODO.
  27788. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  27789. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  27790. */
  27791. constructor( scope, bufferType, bufferCount = 0 ) {
  27792. super( bufferType );
  27793. /**
  27794. * The buffer type.
  27795. *
  27796. * @type {string}
  27797. */
  27798. this.bufferType = bufferType;
  27799. /**
  27800. * The buffer count.
  27801. *
  27802. * @type {number}
  27803. * @default 0
  27804. */
  27805. this.bufferCount = bufferCount;
  27806. /**
  27807. * This flag can be used for type testing.
  27808. *
  27809. * @type {boolean}
  27810. * @readonly
  27811. * @default true
  27812. */
  27813. this.isWorkgroupInfoNode = true;
  27814. /**
  27815. * The data type of the array buffer.
  27816. *
  27817. * @type {string}
  27818. */
  27819. this.elementType = bufferType;
  27820. /**
  27821. * TODO.
  27822. *
  27823. * @type {string}
  27824. */
  27825. this.scope = scope;
  27826. /**
  27827. * The name of the workgroup scoped buffer.
  27828. *
  27829. * @type {string}
  27830. * @default ''
  27831. */
  27832. this.name = '';
  27833. }
  27834. /**
  27835. * Sets the name of this node.
  27836. *
  27837. * @param {string} name - The name to set.
  27838. * @return {WorkgroupInfoNode} A reference to this node.
  27839. */
  27840. setName( name ) {
  27841. this.name = name;
  27842. return this;
  27843. }
  27844. /**
  27845. * Sets the name/label of this node.
  27846. *
  27847. * @deprecated
  27848. * @param {string} name - The name to set.
  27849. * @return {WorkgroupInfoNode} A reference to this node.
  27850. */
  27851. label( name ) {
  27852. warn( 'TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  27853. return this.setName( name );
  27854. }
  27855. /**
  27856. * Sets the scope of this node.
  27857. *
  27858. * @param {string} scope - The scope to set.
  27859. * @return {WorkgroupInfoNode} A reference to this node.
  27860. */
  27861. setScope( scope ) {
  27862. this.scope = scope;
  27863. return this;
  27864. }
  27865. /**
  27866. * The data type of the array buffer.
  27867. *
  27868. * @return {string} The element type.
  27869. */
  27870. getElementType() {
  27871. return this.elementType;
  27872. }
  27873. /**
  27874. * Overwrites the default implementation since the input type
  27875. * is inferred from the scope.
  27876. *
  27877. * @param {NodeBuilder} builder - The current node builder.
  27878. * @return {string} The input type.
  27879. */
  27880. getInputType( /*builder*/ ) {
  27881. return `${this.scope}Array`;
  27882. }
  27883. /**
  27884. * This method can be used to access elements via an index node.
  27885. *
  27886. * @param {IndexNode} indexNode - indexNode.
  27887. * @return {WorkgroupInfoElementNode} A reference to an element.
  27888. */
  27889. element( indexNode ) {
  27890. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  27891. }
  27892. generate( builder ) {
  27893. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  27894. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  27895. }
  27896. }
  27897. /**
  27898. * TSL function for creating a workgroup info node.
  27899. * Creates a new 'workgroup' scoped array buffer.
  27900. *
  27901. * @tsl
  27902. * @function
  27903. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  27904. * @param {number} [count=0] - The number of elements in the buffer.
  27905. * @returns {WorkgroupInfoNode}
  27906. */
  27907. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  27908. /**
  27909. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  27910. * within a shader. In an atomic function, any modification to an atomic variable will
  27911. * occur as an indivisible step with a defined order relative to other modifications.
  27912. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  27913. * atomic operations will not interfere with each other.
  27914. *
  27915. * This node can only be used with a WebGPU backend.
  27916. *
  27917. * @augments Node
  27918. */
  27919. class AtomicFunctionNode extends Node {
  27920. static get type() {
  27921. return 'AtomicFunctionNode';
  27922. }
  27923. /**
  27924. * Constructs a new atomic function node.
  27925. *
  27926. * @param {string} method - The signature of the atomic function to construct.
  27927. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27928. * @param {Node} valueNode - The value that mutates the atomic variable.
  27929. */
  27930. constructor( method, pointerNode, valueNode ) {
  27931. super( 'uint' );
  27932. /**
  27933. * The signature of the atomic function to construct.
  27934. *
  27935. * @type {string}
  27936. */
  27937. this.method = method;
  27938. /**
  27939. * An atomic variable or element of an atomic buffer.
  27940. *
  27941. * @type {Node}
  27942. */
  27943. this.pointerNode = pointerNode;
  27944. /**
  27945. * A value that modifies the atomic variable.
  27946. *
  27947. * @type {Node}
  27948. */
  27949. this.valueNode = valueNode;
  27950. /**
  27951. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  27952. *
  27953. * @type {boolean}
  27954. * @default true
  27955. */
  27956. this.parents = true;
  27957. }
  27958. /**
  27959. * Overwrites the default implementation to return the type of
  27960. * the pointer node.
  27961. *
  27962. * @param {NodeBuilder} builder - The current node builder.
  27963. * @return {string} The input type.
  27964. */
  27965. getInputType( builder ) {
  27966. return this.pointerNode.getNodeType( builder );
  27967. }
  27968. /**
  27969. * Overwritten since the node type is inferred from the input type.
  27970. *
  27971. * @param {NodeBuilder} builder - The current node builder.
  27972. * @return {string} The node type.
  27973. */
  27974. getNodeType( builder ) {
  27975. return this.getInputType( builder );
  27976. }
  27977. generate( builder ) {
  27978. const properties = builder.getNodeProperties( this );
  27979. const parents = properties.parents;
  27980. const method = this.method;
  27981. const type = this.getNodeType( builder );
  27982. const inputType = this.getInputType( builder );
  27983. const a = this.pointerNode;
  27984. const b = this.valueNode;
  27985. const params = [];
  27986. params.push( `&${ a.build( builder, inputType ) }` );
  27987. if ( b !== null ) {
  27988. params.push( b.build( builder, inputType ) );
  27989. }
  27990. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  27991. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  27992. if ( isVoid ) {
  27993. builder.addLineFlowCode( methodSnippet, this );
  27994. } else {
  27995. if ( properties.constNode === undefined ) {
  27996. properties.constNode = expression( methodSnippet, type ).toConst();
  27997. }
  27998. return properties.constNode.build( builder );
  27999. }
  28000. }
  28001. }
  28002. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  28003. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  28004. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  28005. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  28006. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  28007. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  28008. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  28009. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  28010. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  28011. /**
  28012. * TSL function for creating an atomic function node.
  28013. *
  28014. * @tsl
  28015. * @function
  28016. * @param {string} method - The signature of the atomic function to construct.
  28017. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28018. * @param {Node} valueNode - The value that mutates the atomic variable.
  28019. * @returns {AtomicFunctionNode}
  28020. */
  28021. const atomicNode = nodeProxy( AtomicFunctionNode );
  28022. /**
  28023. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  28024. *
  28025. * @tsl
  28026. * @function
  28027. * @param {string} method - The signature of the atomic function to construct.
  28028. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28029. * @param {Node} valueNode - The value that mutates the atomic variable.
  28030. * @returns {AtomicFunctionNode}
  28031. */
  28032. const atomicFunc = ( method, pointerNode, valueNode ) => {
  28033. return atomicNode( method, pointerNode, valueNode ).toStack();
  28034. };
  28035. /**
  28036. * Loads the value stored in the atomic variable.
  28037. *
  28038. * @tsl
  28039. * @function
  28040. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28041. * @returns {AtomicFunctionNode}
  28042. */
  28043. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  28044. /**
  28045. * Stores a value in the atomic variable.
  28046. *
  28047. * @tsl
  28048. * @function
  28049. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28050. * @param {Node} valueNode - The value that mutates the atomic variable.
  28051. * @returns {AtomicFunctionNode}
  28052. */
  28053. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  28054. /**
  28055. * Increments the value stored in the atomic variable.
  28056. *
  28057. * @tsl
  28058. * @function
  28059. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28060. * @param {Node} valueNode - The value that mutates the atomic variable.
  28061. * @returns {AtomicFunctionNode}
  28062. */
  28063. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  28064. /**
  28065. * Decrements the value stored in the atomic variable.
  28066. *
  28067. * @tsl
  28068. * @function
  28069. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28070. * @param {Node} valueNode - The value that mutates the atomic variable.
  28071. * @returns {AtomicFunctionNode}
  28072. */
  28073. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  28074. /**
  28075. * Stores in an atomic variable the maximum between its current value and a parameter.
  28076. *
  28077. * @tsl
  28078. * @function
  28079. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28080. * @param {Node} valueNode - The value that mutates the atomic variable.
  28081. * @returns {AtomicFunctionNode}
  28082. */
  28083. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  28084. /**
  28085. * Stores in an atomic variable the minimum between its current value and a parameter.
  28086. *
  28087. * @tsl
  28088. * @function
  28089. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28090. * @param {Node} valueNode - The value that mutates the atomic variable.
  28091. * @returns {AtomicFunctionNode}
  28092. */
  28093. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  28094. /**
  28095. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  28096. *
  28097. * @tsl
  28098. * @function
  28099. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28100. * @param {Node} valueNode - The value that mutates the atomic variable.
  28101. * @returns {AtomicFunctionNode}
  28102. */
  28103. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  28104. /**
  28105. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  28106. *
  28107. * @tsl
  28108. * @function
  28109. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28110. * @param {Node} valueNode - The value that mutates the atomic variable.
  28111. * @returns {AtomicFunctionNode}
  28112. */
  28113. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  28114. /**
  28115. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  28116. *
  28117. * @tsl
  28118. * @function
  28119. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28120. * @param {Node} valueNode - The value that mutates the atomic variable.
  28121. * @returns {AtomicFunctionNode}
  28122. */
  28123. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  28124. /**
  28125. * This class represents a set of built in WGSL shader functions that sync
  28126. * synchronously execute an operation across a subgroup, or 'warp', of compute
  28127. * or fragment shader invocations within a workgroup. Typically, these functions
  28128. * will synchronously execute an operation using data from all active invocations
  28129. * within the subgroup, then broadcast that result to all active invocations. In
  28130. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  28131. * (DirectX/HLSL) or warp intrinsics (CUDA).
  28132. *
  28133. * @augments TempNode
  28134. */
  28135. class SubgroupFunctionNode extends TempNode {
  28136. static get type() {
  28137. return 'SubgroupFunctionNode';
  28138. }
  28139. /**
  28140. * Constructs a new function node.
  28141. *
  28142. * @param {string} method - The subgroup/wave intrinsic method to construct.
  28143. * @param {Node} [aNode=null] - The method's first argument.
  28144. * @param {Node} [bNode=null] - The method's second argument.
  28145. */
  28146. constructor( method, aNode = null, bNode = null ) {
  28147. super();
  28148. /**
  28149. * The subgroup/wave intrinsic method to construct.
  28150. *
  28151. * @type {String}
  28152. */
  28153. this.method = method;
  28154. /**
  28155. * The method's first argument.
  28156. *
  28157. * @type {Node}
  28158. */
  28159. this.aNode = aNode;
  28160. /**
  28161. * The method's second argument.
  28162. *
  28163. * @type {Node}
  28164. */
  28165. this.bNode = bNode;
  28166. }
  28167. getInputType( builder ) {
  28168. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  28169. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  28170. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  28171. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  28172. if ( aLen > bLen ) {
  28173. return aType;
  28174. } else {
  28175. return bType;
  28176. }
  28177. }
  28178. getNodeType( builder ) {
  28179. const method = this.method;
  28180. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  28181. return 'bool';
  28182. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  28183. return 'uvec4';
  28184. } else {
  28185. return this.getInputType( builder );
  28186. }
  28187. }
  28188. generate( builder, output ) {
  28189. const method = this.method;
  28190. const type = this.getNodeType( builder );
  28191. const inputType = this.getInputType( builder );
  28192. const a = this.aNode;
  28193. const b = this.bNode;
  28194. const params = [];
  28195. if (
  28196. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  28197. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  28198. method === SubgroupFunctionNode.QUAD_BROADCAST
  28199. ) {
  28200. const bType = b.getNodeType( builder );
  28201. params.push(
  28202. a.build( builder, type ),
  28203. b.build( builder, bType === 'float' ? 'int' : type )
  28204. );
  28205. } else if (
  28206. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  28207. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  28208. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  28209. ) {
  28210. params.push(
  28211. a.build( builder, type ),
  28212. b.build( builder, 'uint' )
  28213. );
  28214. } else {
  28215. if ( a !== null ) params.push( a.build( builder, inputType ) );
  28216. if ( b !== null ) params.push( b.build( builder, inputType ) );
  28217. }
  28218. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  28219. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  28220. }
  28221. serialize( data ) {
  28222. super.serialize( data );
  28223. data.method = this.method;
  28224. }
  28225. deserialize( data ) {
  28226. super.deserialize( data );
  28227. this.method = data.method;
  28228. }
  28229. }
  28230. // 0 inputs
  28231. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  28232. // 1 input
  28233. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  28234. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  28235. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  28236. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  28237. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  28238. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  28239. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  28240. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  28241. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  28242. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  28243. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  28244. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  28245. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  28246. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  28247. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  28248. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  28249. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  28250. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  28251. // 2 inputs
  28252. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  28253. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  28254. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  28255. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  28256. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  28257. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  28258. /**
  28259. * Returns true if this invocation has the lowest subgroup_invocation_id
  28260. * among active invocations in the subgroup.
  28261. *
  28262. * @method
  28263. * @return {bool} The result of the computation.
  28264. */
  28265. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  28266. /**
  28267. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  28268. * is 1 if pred is true for that active invocation and 0 otherwise.
  28269. *
  28270. * @method
  28271. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  28272. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  28273. */
  28274. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  28275. /**
  28276. * A reduction that adds e among all active invocations and returns that result.
  28277. *
  28278. * @method
  28279. * @param {number} e - The value provided to the reduction by the current invocation.
  28280. * @return {number} The accumulated result of the reduction operation.
  28281. */
  28282. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  28283. /**
  28284. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28285. *
  28286. * @method
  28287. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28288. * @return {number} The accumulated result of the inclusive scan operation.
  28289. */
  28290. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  28291. /**
  28292. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  28293. *
  28294. * @method
  28295. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28296. * @return {number} The accumulated result of the exclusive scan operation.
  28297. */
  28298. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  28299. /**
  28300. * A reduction that multiplies e among all active invocations and returns that result.
  28301. *
  28302. * @method
  28303. * @param {number} e - The value provided to the reduction by the current invocation.
  28304. * @return {number} The accumulated result of the reduction operation.
  28305. */
  28306. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  28307. /**
  28308. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28309. *
  28310. * @method
  28311. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28312. * @return {number} The accumulated result of the inclusive scan operation.
  28313. */
  28314. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  28315. /**
  28316. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  28317. *
  28318. * @method
  28319. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28320. * @return {number} The accumulated result of the exclusive scan operation.
  28321. */
  28322. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  28323. /**
  28324. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  28325. *
  28326. * @method
  28327. * @param {number} e - The value provided to the reduction by the current invocation.
  28328. * @return {number} The result of the reduction operation.
  28329. */
  28330. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  28331. /**
  28332. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  28333. *
  28334. * @method
  28335. * @param {number} e - The value provided to the reduction by the current invocation.
  28336. * @return {number} The result of the reduction operation.
  28337. */
  28338. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  28339. /**
  28340. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  28341. *
  28342. * @method
  28343. * @param {number} e - The value provided to the reduction by the current invocation.
  28344. * @return {number} The result of the reduction operation.
  28345. */
  28346. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  28347. /**
  28348. * A reduction that performs a min of e among all active invocations and returns that result.
  28349. *
  28350. * @method
  28351. * @param {number} e - The value provided to the reduction by the current invocation.
  28352. * @return {number} The result of the reduction operation.
  28353. */
  28354. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  28355. /**
  28356. * A reduction that performs a max of e among all active invocations and returns that result.
  28357. *
  28358. * @method
  28359. * @param {number} e - The value provided to the reduction by the current invocation.
  28360. * @return {number} The result of the reduction operation.
  28361. */
  28362. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  28363. /**
  28364. * Returns true if e is true for all active invocations in the subgroup.
  28365. *
  28366. * @method
  28367. * @return {bool} The result of the computation.
  28368. */
  28369. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  28370. /**
  28371. * Returns true if e is true for any active invocation in the subgroup
  28372. *
  28373. * @method
  28374. * @return {bool} The result of the computation.
  28375. */
  28376. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  28377. /**
  28378. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  28379. *
  28380. * @method
  28381. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  28382. * @param {number} id - The subgroup invocation to broadcast from.
  28383. * @return {number} The broadcast value.
  28384. */
  28385. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  28386. /**
  28387. * Swaps e between invocations in the quad in the X direction.
  28388. *
  28389. * @method
  28390. * @param {number} e - The value to swap from the current invocation.
  28391. * @return {number} The value received from the swap operation.
  28392. */
  28393. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  28394. /**
  28395. * Swaps e between invocations in the quad in the Y direction.
  28396. *
  28397. * @method
  28398. * @param {number} e - The value to swap from the current invocation.
  28399. * @return {number} The value received from the swap operation.
  28400. */
  28401. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  28402. /**
  28403. * Swaps e between invocations in the quad diagonally.
  28404. *
  28405. * @method
  28406. * @param {number} e - The value to swap from the current invocation.
  28407. * @return {number} The value received from the swap operation.
  28408. */
  28409. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  28410. /**
  28411. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  28412. *
  28413. * @method
  28414. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  28415. * @param {number} id - The subgroup invocation to broadcast from.
  28416. * @return {number} The broadcast value.
  28417. */
  28418. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  28419. /**
  28420. * Returns v from the active invocation whose subgroup_invocation_id matches id
  28421. *
  28422. * @method
  28423. * @param {number} v - The value to return from subgroup invocation id^mask.
  28424. * @param {number} id - The subgroup invocation which returns the value v.
  28425. * @return {number} The broadcast value.
  28426. */
  28427. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  28428. /**
  28429. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  28430. *
  28431. * @method
  28432. * @param {number} v - The value to return from subgroup invocation id^mask.
  28433. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  28434. * @return {number} The broadcast value.
  28435. */
  28436. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  28437. /**
  28438. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  28439. *
  28440. * @method
  28441. * @param {number} v - The value to return from subgroup invocation id^mask.
  28442. * @param {number} delta - A value that offsets the current in.
  28443. * @return {number} The broadcast value.
  28444. */
  28445. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  28446. /**
  28447. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  28448. *
  28449. * @method
  28450. * @param {number} v - The value to return from subgroup invocation id^mask.
  28451. * @param {number} delta - A value that offsets the current subgroup invocation.
  28452. * @return {number} The broadcast value.
  28453. */
  28454. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  28455. /**
  28456. * Broadcasts e from the quad invocation with id equal to id.
  28457. *
  28458. * @method
  28459. * @param {number} e - The value to broadcast.
  28460. * @return {number} The broadcast value.
  28461. */
  28462. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  28463. let uniformsLib;
  28464. function getLightData( light ) {
  28465. uniformsLib = uniformsLib || new WeakMap();
  28466. let uniforms = uniformsLib.get( light );
  28467. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  28468. return uniforms;
  28469. }
  28470. /**
  28471. * TSL function for getting a shadow matrix uniform node for the given light.
  28472. *
  28473. * @tsl
  28474. * @function
  28475. * @param {Light} light -The light source.
  28476. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  28477. */
  28478. function lightShadowMatrix( light ) {
  28479. const data = getLightData( light );
  28480. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  28481. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  28482. light.shadow.updateMatrices( light );
  28483. }
  28484. return light.shadow.matrix;
  28485. } ) );
  28486. }
  28487. /**
  28488. * TSL function for getting projected uv coordinates for the given light.
  28489. * Relevant when using maps with spot lights.
  28490. *
  28491. * @tsl
  28492. * @function
  28493. * @param {Light} light -The light source.
  28494. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  28495. * @returns {Node<vec3>} The projected uvs.
  28496. */
  28497. function lightProjectionUV( light, position = positionWorld ) {
  28498. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  28499. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  28500. return projectionUV;
  28501. }
  28502. /**
  28503. * TSL function for getting the position in world space for the given light.
  28504. *
  28505. * @tsl
  28506. * @function
  28507. * @param {Light} light -The light source.
  28508. * @returns {UniformNode<vec3>} The light's position in world space.
  28509. */
  28510. function lightPosition( light ) {
  28511. const data = getLightData( light );
  28512. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  28513. }
  28514. /**
  28515. * TSL function for getting the light target position in world space for the given light.
  28516. *
  28517. * @tsl
  28518. * @function
  28519. * @param {Light} light -The light source.
  28520. * @returns {UniformNode<vec3>} The light target position in world space.
  28521. */
  28522. function lightTargetPosition( light ) {
  28523. const data = getLightData( light );
  28524. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  28525. }
  28526. /**
  28527. * TSL function for getting the position in view space for the given light.
  28528. *
  28529. * @tsl
  28530. * @function
  28531. * @param {Light} light - The light source.
  28532. * @returns {UniformNode<vec3>} The light's position in view space.
  28533. */
  28534. function lightViewPosition( light ) {
  28535. const data = getLightData( light );
  28536. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  28537. self.value = self.value || new Vector3();
  28538. self.value.setFromMatrixPosition( light.matrixWorld );
  28539. self.value.applyMatrix4( camera.matrixWorldInverse );
  28540. } ) );
  28541. }
  28542. /**
  28543. * TSL function for getting the light target direction for the given light.
  28544. *
  28545. * @tsl
  28546. * @function
  28547. * @param {Light} light -The light source.
  28548. * @returns {Node<vec3>} The light's target direction.
  28549. */
  28550. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  28551. const sortLights = ( lights ) => {
  28552. return lights.sort( ( a, b ) => a.id - b.id );
  28553. };
  28554. const getLightNodeById = ( id, lightNodes ) => {
  28555. for ( const lightNode of lightNodes ) {
  28556. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  28557. return lightNode;
  28558. }
  28559. }
  28560. return null;
  28561. };
  28562. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  28563. const _hashData = [];
  28564. /**
  28565. * This node represents the scene's lighting and manages the lighting model's life cycle
  28566. * for the current build 3D object. It is responsible for computing the total outgoing
  28567. * light in a given lighting context.
  28568. *
  28569. * @augments Node
  28570. */
  28571. class LightsNode extends Node {
  28572. static get type() {
  28573. return 'LightsNode';
  28574. }
  28575. /**
  28576. * Constructs a new lights node.
  28577. */
  28578. constructor() {
  28579. super( 'vec3' );
  28580. /**
  28581. * A node representing the total diffuse light.
  28582. *
  28583. * @type {Node<vec3>}
  28584. */
  28585. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  28586. /**
  28587. * A node representing the total specular light.
  28588. *
  28589. * @type {Node<vec3>}
  28590. */
  28591. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  28592. /**
  28593. * A node representing the outgoing light.
  28594. *
  28595. * @type {Node<vec3>}
  28596. */
  28597. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  28598. /**
  28599. * An array representing the lights in the scene.
  28600. *
  28601. * @private
  28602. * @type {Array<Light>}
  28603. */
  28604. this._lights = [];
  28605. /**
  28606. * For each light in the scene, this node will create a
  28607. * corresponding light node.
  28608. *
  28609. * @private
  28610. * @type {?Array<LightingNode>}
  28611. * @default null
  28612. */
  28613. this._lightNodes = null;
  28614. /**
  28615. * A hash for identifying the current light nodes setup.
  28616. *
  28617. * @private
  28618. * @type {?string}
  28619. * @default null
  28620. */
  28621. this._lightNodesHash = null;
  28622. /**
  28623. * `LightsNode` sets this property to `true` by default.
  28624. *
  28625. * @type {boolean}
  28626. * @default true
  28627. */
  28628. this.global = true;
  28629. }
  28630. /**
  28631. * Overwrites the default {@link Node#customCacheKey} implementation by including
  28632. * light data into the cache key.
  28633. *
  28634. * @return {number} The custom cache key.
  28635. */
  28636. customCacheKey() {
  28637. const lights = this._lights;
  28638. for ( let i = 0; i < lights.length; i ++ ) {
  28639. const light = lights[ i ];
  28640. _hashData.push( light.id );
  28641. _hashData.push( light.castShadow ? 1 : 0 );
  28642. if ( light.isSpotLight === true ) {
  28643. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  28644. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  28645. _hashData.push( hashMap, hashColorNode );
  28646. }
  28647. }
  28648. const cacheKey = hashArray( _hashData );
  28649. _hashData.length = 0;
  28650. return cacheKey;
  28651. }
  28652. /**
  28653. * Computes a hash value for identifying the current light nodes setup.
  28654. *
  28655. * @param {NodeBuilder} builder - A reference to the current node builder.
  28656. * @return {string} The computed hash.
  28657. */
  28658. getHash( builder ) {
  28659. if ( this._lightNodesHash === null ) {
  28660. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28661. const hash = [];
  28662. for ( const lightNode of this._lightNodes ) {
  28663. hash.push( lightNode.getHash() );
  28664. }
  28665. this._lightNodesHash = 'lights-' + hash.join( ',' );
  28666. }
  28667. return this._lightNodesHash;
  28668. }
  28669. analyze( builder ) {
  28670. const properties = builder.getNodeProperties( this );
  28671. for ( const node of properties.nodes ) {
  28672. node.build( builder );
  28673. }
  28674. properties.outputNode.build( builder );
  28675. }
  28676. /**
  28677. * Creates lighting nodes for each scene light. This makes it possible to further
  28678. * process lights in the node system.
  28679. *
  28680. * @param {NodeBuilder} builder - A reference to the current node builder.
  28681. */
  28682. setupLightsNode( builder ) {
  28683. const lightNodes = [];
  28684. const previousLightNodes = this._lightNodes;
  28685. const lights = sortLights( this._lights );
  28686. const nodeLibrary = builder.renderer.library;
  28687. for ( const light of lights ) {
  28688. if ( light.isNode ) {
  28689. lightNodes.push( nodeObject( light ) );
  28690. } else {
  28691. let lightNode = null;
  28692. if ( previousLightNodes !== null ) {
  28693. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  28694. }
  28695. if ( lightNode === null ) {
  28696. // find the corresponding node type for a given light
  28697. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  28698. if ( lightNodeClass === null ) {
  28699. warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  28700. continue;
  28701. }
  28702. let lightNode = null;
  28703. if ( ! _lightsNodeRef.has( light ) ) {
  28704. lightNode = nodeObject( new lightNodeClass( light ) );
  28705. _lightsNodeRef.set( light, lightNode );
  28706. } else {
  28707. lightNode = _lightsNodeRef.get( light );
  28708. }
  28709. lightNodes.push( lightNode );
  28710. }
  28711. }
  28712. }
  28713. this._lightNodes = lightNodes;
  28714. }
  28715. /**
  28716. * Sets up a direct light in the lighting model.
  28717. *
  28718. * @param {Object} builder - The builder object containing the context and stack.
  28719. * @param {Object} lightNode - The light node.
  28720. * @param {Object} lightData - The light object containing color and direction properties.
  28721. */
  28722. setupDirectLight( builder, lightNode, lightData ) {
  28723. const { lightingModel, reflectedLight } = builder.context;
  28724. lightingModel.direct( {
  28725. ...lightData,
  28726. lightNode,
  28727. reflectedLight
  28728. }, builder );
  28729. }
  28730. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  28731. const { lightingModel, reflectedLight } = builder.context;
  28732. lightingModel.directRectArea( {
  28733. ...lightData,
  28734. lightNode,
  28735. reflectedLight
  28736. }, builder );
  28737. }
  28738. /**
  28739. * Setups the internal lights by building all respective
  28740. * light nodes.
  28741. *
  28742. * @param {NodeBuilder} builder - A reference to the current node builder.
  28743. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  28744. */
  28745. setupLights( builder, lightNodes ) {
  28746. for ( const lightNode of lightNodes ) {
  28747. lightNode.build( builder );
  28748. }
  28749. }
  28750. getLightNodes( builder ) {
  28751. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28752. return this._lightNodes;
  28753. }
  28754. /**
  28755. * The implementation makes sure that for each light in the scene
  28756. * there is a corresponding light node. By building the light nodes
  28757. * and evaluating the lighting model the outgoing light is computed.
  28758. *
  28759. * @param {NodeBuilder} builder - A reference to the current node builder.
  28760. * @return {Node<vec3>} A node representing the outgoing light.
  28761. */
  28762. setup( builder ) {
  28763. const currentLightsNode = builder.lightsNode;
  28764. builder.lightsNode = this;
  28765. //
  28766. let outgoingLightNode = this.outgoingLightNode;
  28767. const context = builder.context;
  28768. const lightingModel = context.lightingModel;
  28769. const properties = builder.getNodeProperties( this );
  28770. if ( lightingModel ) {
  28771. const { totalDiffuseNode, totalSpecularNode } = this;
  28772. context.outgoingLight = outgoingLightNode;
  28773. const stack = builder.addStack();
  28774. //
  28775. properties.nodes = stack.nodes;
  28776. //
  28777. lightingModel.start( builder );
  28778. //
  28779. const { backdrop, backdropAlpha } = context;
  28780. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  28781. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  28782. if ( backdrop !== null ) {
  28783. if ( backdropAlpha !== null ) {
  28784. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  28785. } else {
  28786. totalDiffuse = vec3( backdrop );
  28787. }
  28788. context.material.transparent = true;
  28789. }
  28790. totalDiffuseNode.assign( totalDiffuse );
  28791. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  28792. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  28793. //
  28794. lightingModel.finish( builder );
  28795. //
  28796. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  28797. } else {
  28798. properties.nodes = [];
  28799. }
  28800. //
  28801. builder.lightsNode = currentLightsNode;
  28802. return outgoingLightNode;
  28803. }
  28804. /**
  28805. * Configures this node with an array of lights.
  28806. *
  28807. * @param {Array<Light>} lights - An array of lights.
  28808. * @return {LightsNode} A reference to this node.
  28809. */
  28810. setLights( lights ) {
  28811. this._lights = lights;
  28812. this._lightNodes = null;
  28813. this._lightNodesHash = null;
  28814. return this;
  28815. }
  28816. /**
  28817. * Returns an array of the scene's lights.
  28818. *
  28819. * @return {Array<Light>} The scene's lights.
  28820. */
  28821. getLights() {
  28822. return this._lights;
  28823. }
  28824. /**
  28825. * Whether the scene has lights or not.
  28826. *
  28827. * @type {boolean}
  28828. */
  28829. get hasLights() {
  28830. return this._lights.length > 0;
  28831. }
  28832. }
  28833. /**
  28834. * TSL function for creating an instance of `LightsNode` and configuring
  28835. * it with the given array of lights.
  28836. *
  28837. * @tsl
  28838. * @function
  28839. * @param {Array<Light>} lights - An array of lights.
  28840. * @return {LightsNode} The created lights node.
  28841. */
  28842. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  28843. /**
  28844. * Base class for all shadow nodes.
  28845. *
  28846. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  28847. * Lighting nodes might share the same shadow node type or use specific ones depending on
  28848. * their requirements.
  28849. *
  28850. * @augments Node
  28851. */
  28852. class ShadowBaseNode extends Node {
  28853. static get type() {
  28854. return 'ShadowBaseNode';
  28855. }
  28856. /**
  28857. * Constructs a new shadow base node.
  28858. *
  28859. * @param {Light} light - The shadow casting light.
  28860. */
  28861. constructor( light ) {
  28862. super();
  28863. /**
  28864. * The shadow casting light.
  28865. *
  28866. * @type {Light}
  28867. */
  28868. this.light = light;
  28869. /**
  28870. * Overwritten since shadows are updated by default per render.
  28871. *
  28872. * @type {string}
  28873. * @default 'render'
  28874. */
  28875. this.updateBeforeType = NodeUpdateType.RENDER;
  28876. /**
  28877. * This flag can be used for type testing.
  28878. *
  28879. * @type {boolean}
  28880. * @readonly
  28881. * @default true
  28882. */
  28883. this.isShadowBaseNode = true;
  28884. }
  28885. /**
  28886. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  28887. *
  28888. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  28889. */
  28890. setupShadowPosition( { context, material } ) {
  28891. // Use assign inside an Fn()
  28892. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  28893. }
  28894. }
  28895. /**
  28896. * TSL object that represents the vertex position in world space during the shadow pass.
  28897. *
  28898. * @tsl
  28899. * @type {Node<vec3>}
  28900. */
  28901. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  28902. /**
  28903. * Saves the state of the given renderer and stores it into the given state object.
  28904. *
  28905. * If not state object is provided, the function creates one.
  28906. *
  28907. * @function
  28908. * @param {Renderer} renderer - The renderer.
  28909. * @param {Object} [state={}] - The state.
  28910. * @return {Object} The state.
  28911. */
  28912. function saveRendererState( renderer, state = {} ) {
  28913. state.toneMapping = renderer.toneMapping;
  28914. state.toneMappingExposure = renderer.toneMappingExposure;
  28915. state.outputColorSpace = renderer.outputColorSpace;
  28916. state.renderTarget = renderer.getRenderTarget();
  28917. state.activeCubeFace = renderer.getActiveCubeFace();
  28918. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  28919. state.renderObjectFunction = renderer.getRenderObjectFunction();
  28920. state.pixelRatio = renderer.getPixelRatio();
  28921. state.mrt = renderer.getMRT();
  28922. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  28923. state.clearAlpha = renderer.getClearAlpha();
  28924. state.autoClear = renderer.autoClear;
  28925. state.scissorTest = renderer.getScissorTest();
  28926. return state;
  28927. }
  28928. /**
  28929. * Saves the state of the given renderer and stores it into the given state object.
  28930. * Besides, the function also resets the state of the renderer to its default values.
  28931. *
  28932. * If not state object is provided, the function creates one.
  28933. *
  28934. * @function
  28935. * @param {Renderer} renderer - The renderer.
  28936. * @param {Object} [state={}] - The state.
  28937. * @return {Object} The state.
  28938. */
  28939. function resetRendererState( renderer, state ) {
  28940. state = saveRendererState( renderer, state );
  28941. renderer.setMRT( null );
  28942. renderer.setRenderObjectFunction( null );
  28943. renderer.setClearColor( 0x000000, 1 );
  28944. renderer.autoClear = true;
  28945. return state;
  28946. }
  28947. /**
  28948. * Restores the state of the given renderer from the given state object.
  28949. *
  28950. * @function
  28951. * @param {Renderer} renderer - The renderer.
  28952. * @param {Object} state - The state to restore.
  28953. */
  28954. function restoreRendererState( renderer, state ) {
  28955. renderer.toneMapping = state.toneMapping;
  28956. renderer.toneMappingExposure = state.toneMappingExposure;
  28957. renderer.outputColorSpace = state.outputColorSpace;
  28958. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  28959. renderer.setRenderObjectFunction( state.renderObjectFunction );
  28960. renderer.setPixelRatio( state.pixelRatio );
  28961. renderer.setMRT( state.mrt );
  28962. renderer.setClearColor( state.clearColor, state.clearAlpha );
  28963. renderer.autoClear = state.autoClear;
  28964. renderer.setScissorTest( state.scissorTest );
  28965. }
  28966. /**
  28967. * Saves the state of the given scene and stores it into the given state object.
  28968. *
  28969. * If not state object is provided, the function creates one.
  28970. *
  28971. * @function
  28972. * @param {Scene} scene - The scene.
  28973. * @param {Object} [state={}] - The state.
  28974. * @return {Object} The state.
  28975. */
  28976. function saveSceneState( scene, state = {} ) {
  28977. state.background = scene.background;
  28978. state.backgroundNode = scene.backgroundNode;
  28979. state.overrideMaterial = scene.overrideMaterial;
  28980. return state;
  28981. }
  28982. /**
  28983. * Saves the state of the given scene and stores it into the given state object.
  28984. * Besides, the function also resets the state of the scene to its default values.
  28985. *
  28986. * If not state object is provided, the function creates one.
  28987. *
  28988. * @function
  28989. * @param {Scene} scene - The scene.
  28990. * @param {Object} [state={}] - The state.
  28991. * @return {Object} The state.
  28992. */
  28993. function resetSceneState( scene, state ) {
  28994. state = saveSceneState( scene, state );
  28995. scene.background = null;
  28996. scene.backgroundNode = null;
  28997. scene.overrideMaterial = null;
  28998. return state;
  28999. }
  29000. /**
  29001. * Restores the state of the given scene from the given state object.
  29002. *
  29003. * @function
  29004. * @param {Scene} scene - The scene.
  29005. * @param {Object} state - The state to restore.
  29006. */
  29007. function restoreSceneState( scene, state ) {
  29008. scene.background = state.background;
  29009. scene.backgroundNode = state.backgroundNode;
  29010. scene.overrideMaterial = state.overrideMaterial;
  29011. }
  29012. /**
  29013. * Saves the state of the given renderer and scene and stores it into the given state object.
  29014. *
  29015. * If not state object is provided, the function creates one.
  29016. *
  29017. * @function
  29018. * @param {Renderer} renderer - The renderer.
  29019. * @param {Scene} scene - The scene.
  29020. * @param {Object} [state={}] - The state.
  29021. * @return {Object} The state.
  29022. */
  29023. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  29024. state = saveRendererState( renderer, state );
  29025. state = saveSceneState( scene, state );
  29026. return state;
  29027. }
  29028. /**
  29029. * Saves the state of the given renderer and scene and stores it into the given state object.
  29030. * Besides, the function also resets the state of the renderer and scene to its default values.
  29031. *
  29032. * If not state object is provided, the function creates one.
  29033. *
  29034. * @function
  29035. * @param {Renderer} renderer - The renderer.
  29036. * @param {Scene} scene - The scene.
  29037. * @param {Object} [state={}] - The state.
  29038. * @return {Object} The state.
  29039. */
  29040. function resetRendererAndSceneState( renderer, scene, state ) {
  29041. state = resetRendererState( renderer, state );
  29042. state = resetSceneState( scene, state );
  29043. return state;
  29044. }
  29045. /**
  29046. * Restores the state of the given renderer and scene from the given state object.
  29047. *
  29048. * @function
  29049. * @param {Renderer} renderer - The renderer.
  29050. * @param {Scene} scene - The scene.
  29051. * @param {Object} state - The state to restore.
  29052. */
  29053. function restoreRendererAndSceneState( renderer, scene, state ) {
  29054. restoreRendererState( renderer, state );
  29055. restoreSceneState( scene, state );
  29056. }
  29057. var RendererUtils = /*#__PURE__*/Object.freeze({
  29058. __proto__: null,
  29059. resetRendererAndSceneState: resetRendererAndSceneState,
  29060. resetRendererState: resetRendererState,
  29061. resetSceneState: resetSceneState,
  29062. restoreRendererAndSceneState: restoreRendererAndSceneState,
  29063. restoreRendererState: restoreRendererState,
  29064. restoreSceneState: restoreSceneState,
  29065. saveRendererAndSceneState: saveRendererAndSceneState,
  29066. saveRendererState: saveRendererState,
  29067. saveSceneState: saveSceneState
  29068. });
  29069. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  29070. /**
  29071. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  29072. * with a binary `[0,1]` result.
  29073. *
  29074. * @method
  29075. * @param {Object} inputs - The input parameter object.
  29076. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29077. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29078. * @return {Node<float>} The filtering result.
  29079. */
  29080. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29081. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  29082. if ( depthTexture.isArrayTexture ) {
  29083. basic = basic.depth( depthLayer );
  29084. }
  29085. return basic.compare( shadowCoord.z );
  29086. } );
  29087. /**
  29088. * A shadow filtering function performing PCF filtering.
  29089. *
  29090. * @method
  29091. * @param {Object} inputs - The input parameter object.
  29092. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29093. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29094. * @param {LightShadow} inputs.shadow - The light shadow.
  29095. * @return {Node<float>} The filtering result.
  29096. */
  29097. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29098. const depthCompare = ( uv, compare ) => {
  29099. let depth = texture( depthTexture, uv );
  29100. if ( depthTexture.isArrayTexture ) {
  29101. depth = depth.depth( depthLayer );
  29102. }
  29103. return depth.compare( compare );
  29104. };
  29105. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29106. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29107. const texelSize = vec2( 1 ).div( mapSize );
  29108. const dx0 = texelSize.x.negate().mul( radius );
  29109. const dy0 = texelSize.y.negate().mul( radius );
  29110. const dx1 = texelSize.x.mul( radius );
  29111. const dy1 = texelSize.y.mul( radius );
  29112. const dx2 = dx0.div( 2 );
  29113. const dy2 = dy0.div( 2 );
  29114. const dx3 = dx1.div( 2 );
  29115. const dy3 = dy1.div( 2 );
  29116. return add(
  29117. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  29118. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  29119. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  29120. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  29121. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  29122. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  29123. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  29124. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  29125. depthCompare( shadowCoord.xy, shadowCoord.z ),
  29126. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  29127. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  29128. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  29129. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  29130. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  29131. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  29132. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  29133. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  29134. ).mul( 1 / 17 );
  29135. } );
  29136. /**
  29137. * A shadow filtering function performing PCF soft filtering.
  29138. *
  29139. * @method
  29140. * @param {Object} inputs - The input parameter object.
  29141. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29142. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29143. * @param {LightShadow} inputs.shadow - The light shadow.
  29144. * @return {Node<float>} The filtering result.
  29145. */
  29146. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29147. const depthCompare = ( uv, compare ) => {
  29148. let depth = texture( depthTexture, uv );
  29149. if ( depthTexture.isArrayTexture ) {
  29150. depth = depth.depth( depthLayer );
  29151. }
  29152. return depth.compare( compare );
  29153. };
  29154. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29155. const texelSize = vec2( 1 ).div( mapSize );
  29156. const dx = texelSize.x;
  29157. const dy = texelSize.y;
  29158. const uv = shadowCoord.xy;
  29159. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  29160. uv.subAssign( f.mul( texelSize ) );
  29161. return add(
  29162. depthCompare( uv, shadowCoord.z ),
  29163. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  29164. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  29165. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  29166. mix(
  29167. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  29168. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  29169. f.x
  29170. ),
  29171. mix(
  29172. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  29173. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  29174. f.x
  29175. ),
  29176. mix(
  29177. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  29178. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  29179. f.y
  29180. ),
  29181. mix(
  29182. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  29183. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  29184. f.y
  29185. ),
  29186. mix(
  29187. mix(
  29188. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  29189. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  29190. f.x
  29191. ),
  29192. mix(
  29193. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  29194. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  29195. f.x
  29196. ),
  29197. f.y
  29198. )
  29199. ).mul( 1 / 9 );
  29200. } );
  29201. /**
  29202. * A shadow filtering function performing VSM filtering.
  29203. *
  29204. * @method
  29205. * @param {Object} inputs - The input parameter object.
  29206. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29207. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29208. * @return {Node<float>} The filtering result.
  29209. */
  29210. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29211. const occlusion = float( 1 ).toVar();
  29212. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  29213. if ( depthTexture.isArrayTexture ) {
  29214. distribution = distribution.depth( depthLayer );
  29215. }
  29216. distribution = distribution.rg;
  29217. const hardShadow = step( shadowCoord.z, distribution.x );
  29218. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  29219. const distance = shadowCoord.z.sub( distribution.x );
  29220. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  29221. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  29222. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  29223. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  29224. } );
  29225. return occlusion;
  29226. } );
  29227. //
  29228. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  29229. let dist = positionWorld.sub( position ).length();
  29230. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  29231. dist = dist.saturate(); // clamp to [ 0, 1 ]
  29232. return dist;
  29233. } );
  29234. const linearShadowDistance = ( light ) => {
  29235. const camera = light.shadow.camera;
  29236. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  29237. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  29238. const referencePosition = objectPosition( light );
  29239. return linearDistance( referencePosition, nearDistance, farDistance );
  29240. };
  29241. /**
  29242. * Retrieves or creates a shadow material for the given light source.
  29243. *
  29244. * This function checks if a shadow material already exists for the provided light.
  29245. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  29246. * in the `shadowMaterialLib` for future use.
  29247. *
  29248. * @param {Light} light - The light source for which the shadow material is needed.
  29249. * If the light is a point light, a depth node is calculated
  29250. * using the linear shadow distance.
  29251. * @returns {NodeMaterial} The shadow material associated with the given light.
  29252. */
  29253. const getShadowMaterial = ( light ) => {
  29254. let material = shadowMaterialLib.get( light );
  29255. if ( material === undefined ) {
  29256. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  29257. material = new NodeMaterial();
  29258. material.colorNode = vec4( 0, 0, 0, 1 );
  29259. material.depthNode = depthNode;
  29260. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  29261. material.name = 'ShadowMaterial';
  29262. material.fog = false;
  29263. shadowMaterialLib.set( light, material );
  29264. }
  29265. return material;
  29266. };
  29267. //
  29268. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  29269. const _shadowRenderObjectKeys = [];
  29270. /**
  29271. * Creates a function to render shadow objects in a scene.
  29272. *
  29273. * @param {Renderer} renderer - The renderer.
  29274. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  29275. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  29276. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  29277. * @return {Function} A function that renders shadow objects.
  29278. *
  29279. * The returned function has the following parameters:
  29280. * @param {Object3D} object - The 3D object to render.
  29281. * @param {Scene} scene - The scene containing the object.
  29282. * @param {Camera} _camera - The camera used for rendering.
  29283. * @param {BufferGeometry} geometry - The geometry of the object.
  29284. * @param {Material} material - The material of the object.
  29285. * @param {Group} group - The group the object belongs to.
  29286. * @param {...any} params - Additional parameters for rendering.
  29287. */
  29288. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  29289. _shadowRenderObjectKeys[ 0 ] = renderer;
  29290. _shadowRenderObjectKeys[ 1 ] = shadow;
  29291. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  29292. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  29293. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  29294. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  29295. if ( useVelocity ) {
  29296. getDataFromObject( object ).useVelocity = true;
  29297. }
  29298. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29299. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  29300. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29301. }
  29302. };
  29303. renderObjectFunction.shadowType = shadowType;
  29304. renderObjectFunction.useVelocity = useVelocity;
  29305. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  29306. }
  29307. _shadowRenderObjectKeys[ 0 ] = null;
  29308. _shadowRenderObjectKeys[ 1 ] = null;
  29309. return renderObjectFunction;
  29310. };
  29311. /**
  29312. * Represents the shader code for the first VSM render pass.
  29313. *
  29314. * @method
  29315. * @param {Object} inputs - The input parameter object.
  29316. * @param {Node<float>} inputs.samples - The number of samples
  29317. * @param {Node<float>} inputs.radius - The radius.
  29318. * @param {Node<float>} inputs.size - The size.
  29319. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  29320. * @return {Node<vec2>} The VSM output.
  29321. */
  29322. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29323. const mean = float( 0 ).toVar( 'meanVertical' );
  29324. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  29325. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29326. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29327. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29328. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29329. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  29330. if ( shadowPass.value.isArrayTexture ) {
  29331. depth = depth.depth( depthLayer );
  29332. }
  29333. depth = depth.x;
  29334. mean.addAssign( depth );
  29335. squaredMean.addAssign( depth.mul( depth ) );
  29336. } );
  29337. mean.divAssign( samples );
  29338. squaredMean.divAssign( samples );
  29339. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29340. return vec2( mean, std_dev );
  29341. } );
  29342. /**
  29343. * Represents the shader code for the second VSM render pass.
  29344. *
  29345. * @method
  29346. * @param {Object} inputs - The input parameter object.
  29347. * @param {Node<float>} inputs.samples - The number of samples
  29348. * @param {Node<float>} inputs.radius - The radius.
  29349. * @param {Node<float>} inputs.size - The size.
  29350. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  29351. * @return {Node<vec2>} The VSM output.
  29352. */
  29353. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29354. const mean = float( 0 ).toVar( 'meanHorizontal' );
  29355. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  29356. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29357. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29358. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29359. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29360. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  29361. if ( shadowPass.value.isArrayTexture ) {
  29362. distribution = distribution.depth( depthLayer );
  29363. }
  29364. mean.addAssign( distribution.x );
  29365. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  29366. } );
  29367. mean.divAssign( samples );
  29368. squaredMean.divAssign( samples );
  29369. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29370. return vec2( mean, std_dev );
  29371. } );
  29372. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  29373. //
  29374. let _rendererState;
  29375. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  29376. /**
  29377. * Represents the default shadow implementation for lighting nodes.
  29378. *
  29379. * @augments ShadowBaseNode
  29380. */
  29381. class ShadowNode extends ShadowBaseNode {
  29382. static get type() {
  29383. return 'ShadowNode';
  29384. }
  29385. /**
  29386. * Constructs a new shadow node.
  29387. *
  29388. * @param {Light} light - The shadow casting light.
  29389. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  29390. */
  29391. constructor( light, shadow = null ) {
  29392. super( light );
  29393. /**
  29394. * The light shadow which defines the properties light's
  29395. * shadow.
  29396. *
  29397. * @type {?LightShadow}
  29398. * @default null
  29399. */
  29400. this.shadow = shadow || light.shadow;
  29401. /**
  29402. * A reference to the shadow map which is a render target.
  29403. *
  29404. * @type {?RenderTarget}
  29405. * @default null
  29406. */
  29407. this.shadowMap = null;
  29408. /**
  29409. * Only relevant for VSM shadows. Render target for the
  29410. * first VSM render pass.
  29411. *
  29412. * @type {?RenderTarget}
  29413. * @default null
  29414. */
  29415. this.vsmShadowMapVertical = null;
  29416. /**
  29417. * Only relevant for VSM shadows. Render target for the
  29418. * second VSM render pass.
  29419. *
  29420. * @type {?RenderTarget}
  29421. * @default null
  29422. */
  29423. this.vsmShadowMapHorizontal = null;
  29424. /**
  29425. * Only relevant for VSM shadows. Node material which
  29426. * is used to render the first VSM pass.
  29427. *
  29428. * @type {?NodeMaterial}
  29429. * @default null
  29430. */
  29431. this.vsmMaterialVertical = null;
  29432. /**
  29433. * Only relevant for VSM shadows. Node material which
  29434. * is used to render the second VSM pass.
  29435. *
  29436. * @type {?NodeMaterial}
  29437. * @default null
  29438. */
  29439. this.vsmMaterialHorizontal = null;
  29440. /**
  29441. * A reference to the output node which defines the
  29442. * final result of this shadow node.
  29443. *
  29444. * @type {?Node}
  29445. * @private
  29446. * @default null
  29447. */
  29448. this._node = null;
  29449. this._cameraFrameId = new WeakMap();
  29450. /**
  29451. * This flag can be used for type testing.
  29452. *
  29453. * @type {boolean}
  29454. * @readonly
  29455. * @default true
  29456. */
  29457. this.isShadowNode = true;
  29458. /**
  29459. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  29460. *
  29461. * @type {number}
  29462. * @readonly
  29463. * @default true
  29464. */
  29465. this.depthLayer = 0;
  29466. }
  29467. /**
  29468. * Setups the shadow filtering.
  29469. *
  29470. * @param {NodeBuilder} builder - A reference to the current node builder.
  29471. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29472. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29473. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29474. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29475. * @param {LightShadow} inputs.shadow - The light shadow.
  29476. * @return {Node<float>} The result node of the shadow filtering.
  29477. */
  29478. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  29479. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  29480. .and( shadowCoord.x.lessThanEqual( 1 ) )
  29481. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  29482. .and( shadowCoord.y.lessThanEqual( 1 ) )
  29483. .and( shadowCoord.z.lessThanEqual( 1 ) );
  29484. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  29485. return frustumTest.select( shadowNode, float( 1 ) );
  29486. }
  29487. /**
  29488. * Setups the shadow coordinates.
  29489. *
  29490. * @param {NodeBuilder} builder - A reference to the current node builder.
  29491. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29492. * @return {Node<vec3>} The shadow coordinates.
  29493. */
  29494. setupShadowCoord( builder, shadowPosition ) {
  29495. const { shadow } = this;
  29496. const { renderer } = builder;
  29497. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29498. let shadowCoord = shadowPosition;
  29499. let coordZ;
  29500. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  29501. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  29502. coordZ = shadowCoord.z;
  29503. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  29504. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  29505. }
  29506. } else {
  29507. const w = shadowCoord.w;
  29508. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  29509. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  29510. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  29511. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  29512. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  29513. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  29514. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  29515. }
  29516. shadowCoord = vec3(
  29517. shadowCoord.x,
  29518. shadowCoord.y.oneMinus(), // follow webgpu standards
  29519. coordZ.add( bias )
  29520. );
  29521. return shadowCoord;
  29522. }
  29523. /**
  29524. * Returns the shadow filtering function for the given shadow type.
  29525. *
  29526. * @param {number} type - The shadow type.
  29527. * @return {Function} The filtering function.
  29528. */
  29529. getShadowFilterFn( type ) {
  29530. return _shadowFilterLib[ type ];
  29531. }
  29532. setupRenderTarget( shadow, builder ) {
  29533. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  29534. depthTexture.name = 'ShadowDepthTexture';
  29535. depthTexture.compareFunction = LessCompare;
  29536. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  29537. shadowMap.texture.name = 'ShadowMap';
  29538. shadowMap.texture.type = shadow.mapType;
  29539. shadowMap.depthTexture = depthTexture;
  29540. return { shadowMap, depthTexture };
  29541. }
  29542. /**
  29543. * Setups the shadow output node.
  29544. *
  29545. * @param {NodeBuilder} builder - A reference to the current node builder.
  29546. * @return {Node<vec3>} The shadow output node.
  29547. */
  29548. setupShadow( builder ) {
  29549. const { renderer } = builder;
  29550. const { light, shadow } = this;
  29551. const shadowMapType = renderer.shadowMap.type;
  29552. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  29553. shadow.camera.updateProjectionMatrix();
  29554. // VSM
  29555. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29556. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  29557. if ( shadowMap.depth > 1 ) {
  29558. if ( ! shadowMap._vsmShadowMapVertical ) {
  29559. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29560. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  29561. }
  29562. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  29563. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  29564. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29565. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  29566. }
  29567. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  29568. } else {
  29569. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29570. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29571. }
  29572. let shadowPassVertical = texture( depthTexture );
  29573. if ( depthTexture.isArrayTexture ) {
  29574. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  29575. }
  29576. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  29577. if ( depthTexture.isArrayTexture ) {
  29578. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  29579. }
  29580. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  29581. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29582. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29583. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  29584. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29585. material.name = 'VSMVertical';
  29586. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  29587. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29588. material.name = 'VSMHorizontal';
  29589. }
  29590. //
  29591. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  29592. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  29593. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  29594. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  29595. //
  29596. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  29597. if ( filterFn === null ) {
  29598. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  29599. }
  29600. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  29601. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  29602. let shadowColor = texture( shadowMap.texture, shadowCoord );
  29603. if ( depthTexture.isArrayTexture ) {
  29604. shadowColor = shadowColor.depth( this.depthLayer );
  29605. }
  29606. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  29607. this.shadowMap = shadowMap;
  29608. this.shadow.map = shadowMap;
  29609. return shadowOutput;
  29610. }
  29611. /**
  29612. * The implementation performs the setup of the output node. An output is only
  29613. * produces if shadow mapping is globally enabled in the renderer.
  29614. *
  29615. * @param {NodeBuilder} builder - A reference to the current node builder.
  29616. * @return {ShaderCallNodeInternal} The output node.
  29617. */
  29618. setup( builder ) {
  29619. if ( builder.renderer.shadowMap.enabled === false ) return;
  29620. return Fn( () => {
  29621. let node = this._node;
  29622. this.setupShadowPosition( builder );
  29623. if ( node === null ) {
  29624. this._node = node = this.setupShadow( builder );
  29625. }
  29626. if ( builder.material.shadowNode ) { // @deprecated, r171
  29627. warn( 'NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  29628. }
  29629. if ( builder.material.receivedShadowNode ) {
  29630. node = builder.material.receivedShadowNode( node );
  29631. }
  29632. return node;
  29633. } )();
  29634. }
  29635. /**
  29636. * Renders the shadow. The logic of this function could be included
  29637. * into {@link ShadowNode#updateShadow} however more specialized shadow
  29638. * nodes might require a custom shadow map rendering. By having a
  29639. * dedicated method, it's easier to overwrite the default behavior.
  29640. *
  29641. * @param {NodeFrame} frame - A reference to the current node frame.
  29642. */
  29643. renderShadow( frame ) {
  29644. const { shadow, shadowMap, light } = this;
  29645. const { renderer, scene } = frame;
  29646. shadow.updateMatrices( light );
  29647. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  29648. renderer.render( scene, shadow.camera );
  29649. }
  29650. /**
  29651. * Updates the shadow.
  29652. *
  29653. * @param {NodeFrame} frame - A reference to the current node frame.
  29654. */
  29655. updateShadow( frame ) {
  29656. const { shadowMap, light, shadow } = this;
  29657. const { renderer, scene, camera } = frame;
  29658. const shadowType = renderer.shadowMap.type;
  29659. const depthVersion = shadowMap.depthTexture.version;
  29660. this._depthVersionCached = depthVersion;
  29661. const _shadowCameraLayer = shadow.camera.layers.mask;
  29662. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  29663. shadow.camera.layers.mask = camera.layers.mask;
  29664. }
  29665. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  29666. const currentMRT = renderer.getMRT();
  29667. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  29668. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  29669. scene.overrideMaterial = getShadowMaterial( light );
  29670. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  29671. renderer.setClearColor( 0x000000, 0 );
  29672. renderer.setRenderTarget( shadowMap );
  29673. this.renderShadow( frame );
  29674. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  29675. // vsm blur pass
  29676. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29677. this.vsmPass( renderer );
  29678. }
  29679. shadow.camera.layers.mask = _shadowCameraLayer;
  29680. restoreRendererAndSceneState( renderer, scene, _rendererState );
  29681. }
  29682. /**
  29683. * For VSM additional render passes are required.
  29684. *
  29685. * @param {Renderer} renderer - A reference to the current renderer.
  29686. */
  29687. vsmPass( renderer ) {
  29688. const { shadow } = this;
  29689. const depth = this.shadowMap.depth;
  29690. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29691. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29692. renderer.setRenderTarget( this.vsmShadowMapVertical );
  29693. _quadMesh.material = this.vsmMaterialVertical;
  29694. _quadMesh.render( renderer );
  29695. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  29696. _quadMesh.material = this.vsmMaterialHorizontal;
  29697. _quadMesh.render( renderer );
  29698. }
  29699. /**
  29700. * Frees the internal resources of this shadow node.
  29701. */
  29702. dispose() {
  29703. this.shadowMap.dispose();
  29704. this.shadowMap = null;
  29705. if ( this.vsmShadowMapVertical !== null ) {
  29706. this.vsmShadowMapVertical.dispose();
  29707. this.vsmShadowMapVertical = null;
  29708. this.vsmMaterialVertical.dispose();
  29709. this.vsmMaterialVertical = null;
  29710. }
  29711. if ( this.vsmShadowMapHorizontal !== null ) {
  29712. this.vsmShadowMapHorizontal.dispose();
  29713. this.vsmShadowMapHorizontal = null;
  29714. this.vsmMaterialHorizontal.dispose();
  29715. this.vsmMaterialHorizontal = null;
  29716. }
  29717. super.dispose();
  29718. }
  29719. /**
  29720. * The implementation performs the update of the shadow map if necessary.
  29721. *
  29722. * @param {NodeFrame} frame - A reference to the current node frame.
  29723. */
  29724. updateBefore( frame ) {
  29725. const { shadow } = this;
  29726. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  29727. if ( needsUpdate ) {
  29728. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  29729. needsUpdate = false;
  29730. }
  29731. this._cameraFrameId[ frame.camera ] = frame.frameId;
  29732. }
  29733. if ( needsUpdate ) {
  29734. this.updateShadow( frame );
  29735. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  29736. shadow.needsUpdate = false;
  29737. }
  29738. }
  29739. }
  29740. }
  29741. /**
  29742. * TSL function for creating an instance of `ShadowNode`.
  29743. *
  29744. * @tsl
  29745. * @function
  29746. * @param {Light} light - The shadow casting light.
  29747. * @param {?LightShadow} [shadow] - The light shadow.
  29748. * @return {ShadowNode} The created shadow node.
  29749. */
  29750. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  29751. const _clearColor$1 = /*@__PURE__*/ new Color();
  29752. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  29753. // vector suitable for 2D texture mapping. This code uses the following layout for the
  29754. // 2D texture:
  29755. //
  29756. // xzXZ
  29757. // y Y
  29758. //
  29759. // Y - Positive y direction
  29760. // y - Negative y direction
  29761. // X - Positive x direction
  29762. // x - Negative x direction
  29763. // Z - Positive z direction
  29764. // z - Negative z direction
  29765. //
  29766. // Source and test bed:
  29767. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  29768. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  29769. const v = pos.toVar();
  29770. // Number of texels to avoid at the edge of each square
  29771. const absV = abs( v );
  29772. // Intersect unit cube
  29773. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  29774. absV.mulAssign( scaleToCube );
  29775. // Apply scale to avoid seams
  29776. // two texels less per square (one texel will do for NEAREST)
  29777. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  29778. // Unwrap
  29779. // space: -1 ... 1 range for each square
  29780. //
  29781. // #X## dim := ( 4 , 2 )
  29782. // # # center := ( 1 , 1 )
  29783. const planar = vec2( v.xy ).toVar();
  29784. const almostATexel = texelSizeY.mul( 1.5 );
  29785. const almostOne = almostATexel.oneMinus();
  29786. If( absV.z.greaterThanEqual( almostOne ), () => {
  29787. If( v.z.greaterThan( 0.0 ), () => {
  29788. planar.x.assign( sub( 4.0, v.x ) );
  29789. } );
  29790. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  29791. const signX = sign( v.x );
  29792. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  29793. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  29794. const signY = sign( v.y );
  29795. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  29796. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  29797. } );
  29798. // Transform to UV space
  29799. // scale := 0.5 / dim
  29800. // translate := ( center + 0.5 ) / dim
  29801. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  29802. } ).setLayout( {
  29803. name: 'cubeToUV',
  29804. type: 'vec2',
  29805. inputs: [
  29806. { name: 'pos', type: 'vec3' },
  29807. { name: 'texelSizeY', type: 'float' }
  29808. ]
  29809. } );
  29810. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  29811. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  29812. } );
  29813. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  29814. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29815. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  29816. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  29817. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  29818. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  29819. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  29820. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  29821. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  29822. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  29823. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  29824. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  29825. .mul( 1.0 / 9.0 );
  29826. } );
  29827. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  29828. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  29829. // the vector from the light to the world-space position of the fragment.
  29830. const lightToPosition = shadowCoord.xyz.toVar();
  29831. const lightToPositionLength = lightToPosition.length();
  29832. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  29833. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  29834. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29835. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  29836. const result = float( 1.0 ).toVar();
  29837. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  29838. // dp = normalized distance from light to fragment position
  29839. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  29840. dp.addAssign( bias );
  29841. // bd3D = base direction 3D
  29842. const bd3D = lightToPosition.normalize();
  29843. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  29844. // percentage-closer filtering
  29845. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  29846. } );
  29847. return result;
  29848. } );
  29849. const _viewport = /*@__PURE__*/ new Vector4();
  29850. const _viewportSize = /*@__PURE__*/ new Vector2();
  29851. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  29852. /**
  29853. * Represents the shadow implementation for point light nodes.
  29854. *
  29855. * @augments ShadowNode
  29856. */
  29857. class PointShadowNode extends ShadowNode {
  29858. static get type() {
  29859. return 'PointShadowNode';
  29860. }
  29861. /**
  29862. * Constructs a new point shadow node.
  29863. *
  29864. * @param {PointLight} light - The shadow casting point light.
  29865. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  29866. */
  29867. constructor( light, shadow = null ) {
  29868. super( light, shadow );
  29869. }
  29870. /**
  29871. * Overwrites the default implementation to return point light shadow specific
  29872. * filtering functions.
  29873. *
  29874. * @param {number} type - The shadow type.
  29875. * @return {Function} The filtering function.
  29876. */
  29877. getShadowFilterFn( type ) {
  29878. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  29879. }
  29880. /**
  29881. * Overwrites the default implementation so the unaltered shadow position is used.
  29882. *
  29883. * @param {NodeBuilder} builder - A reference to the current node builder.
  29884. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29885. * @return {Node<vec3>} The shadow coordinates.
  29886. */
  29887. setupShadowCoord( builder, shadowPosition ) {
  29888. return shadowPosition;
  29889. }
  29890. /**
  29891. * Overwrites the default implementation to only use point light specific
  29892. * shadow filter functions.
  29893. *
  29894. * @param {NodeBuilder} builder - A reference to the current node builder.
  29895. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29896. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29897. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  29898. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29899. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29900. * @param {LightShadow} inputs.shadow - The light shadow.
  29901. * @return {Node<float>} The result node of the shadow filtering.
  29902. */
  29903. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  29904. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  29905. }
  29906. /**
  29907. * Overwrites the default implementation with point light specific
  29908. * rendering code.
  29909. *
  29910. * @param {NodeFrame} frame - A reference to the current node frame.
  29911. */
  29912. renderShadow( frame ) {
  29913. const { shadow, shadowMap, light } = this;
  29914. const { renderer, scene } = frame;
  29915. const shadowFrameExtents = shadow.getFrameExtents();
  29916. _shadowMapSize.copy( shadow.mapSize );
  29917. _shadowMapSize.multiply( shadowFrameExtents );
  29918. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  29919. _viewportSize.copy( shadow.mapSize );
  29920. //
  29921. const previousAutoClear = renderer.autoClear;
  29922. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  29923. const previousClearAlpha = renderer.getClearAlpha();
  29924. renderer.autoClear = false;
  29925. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  29926. renderer.clear();
  29927. const viewportCount = shadow.getViewportCount();
  29928. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  29929. const viewport = shadow.getViewport( vp );
  29930. const x = _viewportSize.x * viewport.x;
  29931. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  29932. _viewport.set(
  29933. x,
  29934. y,
  29935. _viewportSize.x * viewport.z,
  29936. _viewportSize.y * viewport.w
  29937. );
  29938. shadowMap.viewport.copy( _viewport );
  29939. shadow.updateMatrices( light, vp );
  29940. renderer.render( scene, shadow.camera );
  29941. }
  29942. //
  29943. renderer.autoClear = previousAutoClear;
  29944. renderer.setClearColor( previousClearColor, previousClearAlpha );
  29945. }
  29946. }
  29947. /**
  29948. * TSL function for creating an instance of `PointShadowNode`.
  29949. *
  29950. * @tsl
  29951. * @function
  29952. * @param {PointLight} light - The shadow casting point light.
  29953. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  29954. * @return {PointShadowNode} The created point shadow node.
  29955. */
  29956. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  29957. /**
  29958. * Base class for analytic light nodes.
  29959. *
  29960. * @augments LightingNode
  29961. */
  29962. class AnalyticLightNode extends LightingNode {
  29963. static get type() {
  29964. return 'AnalyticLightNode';
  29965. }
  29966. /**
  29967. * Constructs a new analytic light node.
  29968. *
  29969. * @param {?Light} [light=null] - The light source.
  29970. */
  29971. constructor( light = null ) {
  29972. super();
  29973. /**
  29974. * The light source.
  29975. *
  29976. * @type {?Light}
  29977. * @default null
  29978. */
  29979. this.light = light;
  29980. /**
  29981. * The light's color value.
  29982. *
  29983. * @type {Color}
  29984. */
  29985. this.color = new Color();
  29986. /**
  29987. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  29988. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  29989. *
  29990. * @type {Node}
  29991. */
  29992. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  29993. /**
  29994. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  29995. * The final color node is represented by a different node when using shadows.
  29996. *
  29997. * @type {?Node}
  29998. * @default null
  29999. */
  30000. this.baseColorNode = null;
  30001. /**
  30002. * Represents the light's shadow.
  30003. *
  30004. * @type {?ShadowNode}
  30005. * @default null
  30006. */
  30007. this.shadowNode = null;
  30008. /**
  30009. * Represents the light's shadow color.
  30010. *
  30011. * @type {?Node}
  30012. * @default null
  30013. */
  30014. this.shadowColorNode = null;
  30015. /**
  30016. * This flag can be used for type testing.
  30017. *
  30018. * @type {boolean}
  30019. * @readonly
  30020. * @default true
  30021. */
  30022. this.isAnalyticLightNode = true;
  30023. /**
  30024. * Overwritten since analytic light nodes are updated
  30025. * once per frame.
  30026. *
  30027. * @type {string}
  30028. * @default 'frame'
  30029. */
  30030. this.updateType = NodeUpdateType.FRAME;
  30031. }
  30032. getHash() {
  30033. return this.light.uuid;
  30034. }
  30035. /**
  30036. * Returns a node representing a direction vector which points from the current
  30037. * position in view space to the light's position in view space.
  30038. *
  30039. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30040. * @return {Node<vec3>} The light vector node.
  30041. */
  30042. getLightVector( builder ) {
  30043. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  30044. }
  30045. /**
  30046. * Sets up the direct lighting for the analytic light node.
  30047. *
  30048. * @abstract
  30049. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30050. * @return {Object|undefined} The direct light data (color and direction).
  30051. */
  30052. setupDirect( /*builder*/ ) { }
  30053. /**
  30054. * Sets up the direct rect area lighting for the analytic light node.
  30055. *
  30056. * @abstract
  30057. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  30058. * @return {Object|undefined} The direct rect area light data.
  30059. */
  30060. setupDirectRectArea( /*builder*/ ) { }
  30061. /**
  30062. * Setups the shadow node for this light. The method exists so concrete light classes
  30063. * can setup different types of shadow nodes.
  30064. *
  30065. * @return {ShadowNode} The created shadow node.
  30066. */
  30067. setupShadowNode() {
  30068. return shadow( this.light );
  30069. }
  30070. /**
  30071. * Setups the shadow for this light. This method is only executed if the light
  30072. * cast shadows and the current build object receives shadows. It incorporates
  30073. * shadows into the lighting computation.
  30074. *
  30075. * @param {NodeBuilder} builder - The current node builder.
  30076. */
  30077. setupShadow( builder ) {
  30078. const { renderer } = builder;
  30079. if ( renderer.shadowMap.enabled === false ) return;
  30080. let shadowColorNode = this.shadowColorNode;
  30081. if ( shadowColorNode === null ) {
  30082. const customShadowNode = this.light.shadow.shadowNode;
  30083. let shadowNode;
  30084. if ( customShadowNode !== undefined ) {
  30085. shadowNode = nodeObject( customShadowNode );
  30086. } else {
  30087. shadowNode = this.setupShadowNode();
  30088. }
  30089. this.shadowNode = shadowNode;
  30090. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  30091. this.baseColorNode = this.colorNode;
  30092. }
  30093. //
  30094. this.colorNode = shadowColorNode;
  30095. }
  30096. /**
  30097. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  30098. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  30099. * invocate the respective interface methods.
  30100. *
  30101. * @param {NodeBuilder} builder - The current node builder.
  30102. */
  30103. setup( builder ) {
  30104. this.colorNode = this.baseColorNode || this.colorNode;
  30105. if ( this.light.castShadow ) {
  30106. if ( builder.object.receiveShadow ) {
  30107. this.setupShadow( builder );
  30108. }
  30109. } else if ( this.shadowNode !== null ) {
  30110. this.shadowNode.dispose();
  30111. this.shadowNode = null;
  30112. this.shadowColorNode = null;
  30113. }
  30114. const directLightData = this.setupDirect( builder );
  30115. const directRectAreaLightData = this.setupDirectRectArea( builder );
  30116. if ( directLightData ) {
  30117. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  30118. }
  30119. if ( directRectAreaLightData ) {
  30120. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  30121. }
  30122. }
  30123. /**
  30124. * The update method is used to update light uniforms per frame.
  30125. * Potentially overwritten in concrete light nodes to update light
  30126. * specific uniforms.
  30127. *
  30128. * @param {NodeFrame} frame - A reference to the current node frame.
  30129. */
  30130. update( /*frame*/ ) {
  30131. const { light } = this;
  30132. this.color.copy( light.color ).multiplyScalar( light.intensity );
  30133. }
  30134. }
  30135. /**
  30136. * Represents a `discard` shader operation in TSL.
  30137. *
  30138. * @method
  30139. * @param {Object} inputs - The input parameter object.
  30140. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  30141. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  30142. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  30143. * @return {Node<float>} The distance falloff.
  30144. */
  30145. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  30146. // based upon Frostbite 3 Moving to Physically-based Rendering
  30147. // page 32, equation 26: E[window1]
  30148. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  30149. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  30150. return cutoffDistance.greaterThan( 0 ).select(
  30151. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  30152. distanceFalloff
  30153. );
  30154. } ); // validated
  30155. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  30156. const lightDirection = lightVector.normalize();
  30157. const lightDistance = lightVector.length();
  30158. const attenuation = getDistanceAttenuation( {
  30159. lightDistance,
  30160. cutoffDistance,
  30161. decayExponent
  30162. } );
  30163. const lightColor = color.mul( attenuation );
  30164. return { lightDirection, lightColor };
  30165. };
  30166. /**
  30167. * Module for representing point lights as nodes.
  30168. *
  30169. * @augments AnalyticLightNode
  30170. */
  30171. class PointLightNode extends AnalyticLightNode {
  30172. static get type() {
  30173. return 'PointLightNode';
  30174. }
  30175. /**
  30176. * Constructs a new point light node.
  30177. *
  30178. * @param {?PointLight} [light=null] - The point light source.
  30179. */
  30180. constructor( light = null ) {
  30181. super( light );
  30182. /**
  30183. * Uniform node representing the cutoff distance.
  30184. *
  30185. * @type {UniformNode<float>}
  30186. */
  30187. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  30188. /**
  30189. * Uniform node representing the decay exponent.
  30190. *
  30191. * @type {UniformNode<float>}
  30192. */
  30193. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  30194. }
  30195. /**
  30196. * Overwritten to updated point light specific uniforms.
  30197. *
  30198. * @param {NodeFrame} frame - A reference to the current node frame.
  30199. */
  30200. update( frame ) {
  30201. const { light } = this;
  30202. super.update( frame );
  30203. this.cutoffDistanceNode.value = light.distance;
  30204. this.decayExponentNode.value = light.decay;
  30205. }
  30206. /**
  30207. * Overwritten to setup point light specific shadow.
  30208. *
  30209. * @return {PointShadowNode}
  30210. */
  30211. setupShadowNode() {
  30212. return pointShadow( this.light );
  30213. }
  30214. setupDirect( builder ) {
  30215. return directPointLight( {
  30216. color: this.colorNode,
  30217. lightVector: this.getLightVector( builder ),
  30218. cutoffDistance: this.cutoffDistanceNode,
  30219. decayExponent: this.decayExponentNode
  30220. } );
  30221. }
  30222. }
  30223. /**
  30224. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  30225. *
  30226. * @tsl
  30227. * @function
  30228. * @param {Node<vec2>} coord - The uv coordinates.
  30229. * @return {Node<float>} The result data.
  30230. */
  30231. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  30232. const uv = coord.mul( 2.0 );
  30233. const cx = uv.x.floor();
  30234. const cy = uv.y.floor();
  30235. const result = cx.add( cy ).mod( 2.0 );
  30236. return result.sign();
  30237. } );
  30238. /**
  30239. * Generates a circle based on the uv coordinates.
  30240. *
  30241. * @tsl
  30242. * @function
  30243. * @param {Node<vec2>} coord - The uv to generate the circle.
  30244. * @return {Node<float>} The circle shape.
  30245. */
  30246. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  30247. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  30248. let alpha;
  30249. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  30250. const dlen = float( len2.fwidth() ).toVar();
  30251. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  30252. } else {
  30253. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  30254. }
  30255. return alpha;
  30256. } );
  30257. // Three.js Transpiler
  30258. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  30259. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  30260. const f = float( f_immutable ).toVar();
  30261. const t = float( t_immutable ).toVar();
  30262. const b = bool( b_immutable ).toVar();
  30263. return select( b, t, f );
  30264. } ).setLayout( {
  30265. name: 'mx_select',
  30266. type: 'float',
  30267. inputs: [
  30268. { name: 'b', type: 'bool' },
  30269. { name: 't', type: 'float' },
  30270. { name: 'f', type: 'float' }
  30271. ]
  30272. } );
  30273. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  30274. const b = bool( b_immutable ).toVar();
  30275. const val = float( val_immutable ).toVar();
  30276. return select( b, val.negate(), val );
  30277. } ).setLayout( {
  30278. name: 'mx_negate_if',
  30279. type: 'float',
  30280. inputs: [
  30281. { name: 'val', type: 'float' },
  30282. { name: 'b', type: 'bool' }
  30283. ]
  30284. } );
  30285. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30286. const x = float( x_immutable ).toVar();
  30287. return int( floor( x ) );
  30288. } ).setLayout( {
  30289. name: 'mx_floor',
  30290. type: 'int',
  30291. inputs: [
  30292. { name: 'x', type: 'float' }
  30293. ]
  30294. } );
  30295. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  30296. const x = float( x_immutable ).toVar();
  30297. i.assign( mx_floor( x ) );
  30298. return x.sub( float( i ) );
  30299. } );
  30300. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30301. const t = float( t_immutable ).toVar();
  30302. const s = float( s_immutable ).toVar();
  30303. const v3 = float( v3_immutable ).toVar();
  30304. const v2 = float( v2_immutable ).toVar();
  30305. const v1 = float( v1_immutable ).toVar();
  30306. const v0 = float( v0_immutable ).toVar();
  30307. const s1 = float( sub( 1.0, s ) ).toVar();
  30308. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30309. } ).setLayout( {
  30310. name: 'mx_bilerp_0',
  30311. type: 'float',
  30312. inputs: [
  30313. { name: 'v0', type: 'float' },
  30314. { name: 'v1', type: 'float' },
  30315. { name: 'v2', type: 'float' },
  30316. { name: 'v3', type: 'float' },
  30317. { name: 's', type: 'float' },
  30318. { name: 't', type: 'float' }
  30319. ]
  30320. } );
  30321. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30322. const t = float( t_immutable ).toVar();
  30323. const s = float( s_immutable ).toVar();
  30324. const v3 = vec3( v3_immutable ).toVar();
  30325. const v2 = vec3( v2_immutable ).toVar();
  30326. const v1 = vec3( v1_immutable ).toVar();
  30327. const v0 = vec3( v0_immutable ).toVar();
  30328. const s1 = float( sub( 1.0, s ) ).toVar();
  30329. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30330. } ).setLayout( {
  30331. name: 'mx_bilerp_1',
  30332. type: 'vec3',
  30333. inputs: [
  30334. { name: 'v0', type: 'vec3' },
  30335. { name: 'v1', type: 'vec3' },
  30336. { name: 'v2', type: 'vec3' },
  30337. { name: 'v3', type: 'vec3' },
  30338. { name: 's', type: 'float' },
  30339. { name: 't', type: 'float' }
  30340. ]
  30341. } );
  30342. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  30343. 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 ] ) => {
  30344. const r = float( r_immutable ).toVar();
  30345. const t = float( t_immutable ).toVar();
  30346. const s = float( s_immutable ).toVar();
  30347. const v7 = float( v7_immutable ).toVar();
  30348. const v6 = float( v6_immutable ).toVar();
  30349. const v5 = float( v5_immutable ).toVar();
  30350. const v4 = float( v4_immutable ).toVar();
  30351. const v3 = float( v3_immutable ).toVar();
  30352. const v2 = float( v2_immutable ).toVar();
  30353. const v1 = float( v1_immutable ).toVar();
  30354. const v0 = float( v0_immutable ).toVar();
  30355. const s1 = float( sub( 1.0, s ) ).toVar();
  30356. const t1 = float( sub( 1.0, t ) ).toVar();
  30357. const r1 = float( sub( 1.0, r ) ).toVar();
  30358. 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 ) ) ) ) ) );
  30359. } ).setLayout( {
  30360. name: 'mx_trilerp_0',
  30361. type: 'float',
  30362. inputs: [
  30363. { name: 'v0', type: 'float' },
  30364. { name: 'v1', type: 'float' },
  30365. { name: 'v2', type: 'float' },
  30366. { name: 'v3', type: 'float' },
  30367. { name: 'v4', type: 'float' },
  30368. { name: 'v5', type: 'float' },
  30369. { name: 'v6', type: 'float' },
  30370. { name: 'v7', type: 'float' },
  30371. { name: 's', type: 'float' },
  30372. { name: 't', type: 'float' },
  30373. { name: 'r', type: 'float' }
  30374. ]
  30375. } );
  30376. 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 ] ) => {
  30377. const r = float( r_immutable ).toVar();
  30378. const t = float( t_immutable ).toVar();
  30379. const s = float( s_immutable ).toVar();
  30380. const v7 = vec3( v7_immutable ).toVar();
  30381. const v6 = vec3( v6_immutable ).toVar();
  30382. const v5 = vec3( v5_immutable ).toVar();
  30383. const v4 = vec3( v4_immutable ).toVar();
  30384. const v3 = vec3( v3_immutable ).toVar();
  30385. const v2 = vec3( v2_immutable ).toVar();
  30386. const v1 = vec3( v1_immutable ).toVar();
  30387. const v0 = vec3( v0_immutable ).toVar();
  30388. const s1 = float( sub( 1.0, s ) ).toVar();
  30389. const t1 = float( sub( 1.0, t ) ).toVar();
  30390. const r1 = float( sub( 1.0, r ) ).toVar();
  30391. 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 ) ) ) ) ) );
  30392. } ).setLayout( {
  30393. name: 'mx_trilerp_1',
  30394. type: 'vec3',
  30395. inputs: [
  30396. { name: 'v0', type: 'vec3' },
  30397. { name: 'v1', type: 'vec3' },
  30398. { name: 'v2', type: 'vec3' },
  30399. { name: 'v3', type: 'vec3' },
  30400. { name: 'v4', type: 'vec3' },
  30401. { name: 'v5', type: 'vec3' },
  30402. { name: 'v6', type: 'vec3' },
  30403. { name: 'v7', type: 'vec3' },
  30404. { name: 's', type: 'float' },
  30405. { name: 't', type: 'float' },
  30406. { name: 'r', type: 'float' }
  30407. ]
  30408. } );
  30409. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  30410. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30411. const y = float( y_immutable ).toVar();
  30412. const x = float( x_immutable ).toVar();
  30413. const hash = uint( hash_immutable ).toVar();
  30414. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  30415. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  30416. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  30417. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30418. } ).setLayout( {
  30419. name: 'mx_gradient_float_0',
  30420. type: 'float',
  30421. inputs: [
  30422. { name: 'hash', type: 'uint' },
  30423. { name: 'x', type: 'float' },
  30424. { name: 'y', type: 'float' }
  30425. ]
  30426. } );
  30427. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30428. const z = float( z_immutable ).toVar();
  30429. const y = float( y_immutable ).toVar();
  30430. const x = float( x_immutable ).toVar();
  30431. const hash = uint( hash_immutable ).toVar();
  30432. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  30433. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  30434. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  30435. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30436. } ).setLayout( {
  30437. name: 'mx_gradient_float_1',
  30438. type: 'float',
  30439. inputs: [
  30440. { name: 'hash', type: 'uint' },
  30441. { name: 'x', type: 'float' },
  30442. { name: 'y', type: 'float' },
  30443. { name: 'z', type: 'float' }
  30444. ]
  30445. } );
  30446. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  30447. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30448. const y = float( y_immutable ).toVar();
  30449. const x = float( x_immutable ).toVar();
  30450. const hash = uvec3( hash_immutable ).toVar();
  30451. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  30452. } ).setLayout( {
  30453. name: 'mx_gradient_vec3_0',
  30454. type: 'vec3',
  30455. inputs: [
  30456. { name: 'hash', type: 'uvec3' },
  30457. { name: 'x', type: 'float' },
  30458. { name: 'y', type: 'float' }
  30459. ]
  30460. } );
  30461. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30462. const z = float( z_immutable ).toVar();
  30463. const y = float( y_immutable ).toVar();
  30464. const x = float( x_immutable ).toVar();
  30465. const hash = uvec3( hash_immutable ).toVar();
  30466. 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 ) );
  30467. } ).setLayout( {
  30468. name: 'mx_gradient_vec3_1',
  30469. type: 'vec3',
  30470. inputs: [
  30471. { name: 'hash', type: 'uvec3' },
  30472. { name: 'x', type: 'float' },
  30473. { name: 'y', type: 'float' },
  30474. { name: 'z', type: 'float' }
  30475. ]
  30476. } );
  30477. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  30478. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30479. const v = float( v_immutable ).toVar();
  30480. return mul( 0.6616, v );
  30481. } ).setLayout( {
  30482. name: 'mx_gradient_scale2d_0',
  30483. type: 'float',
  30484. inputs: [
  30485. { name: 'v', type: 'float' }
  30486. ]
  30487. } );
  30488. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30489. const v = float( v_immutable ).toVar();
  30490. return mul( 0.9820, v );
  30491. } ).setLayout( {
  30492. name: 'mx_gradient_scale3d_0',
  30493. type: 'float',
  30494. inputs: [
  30495. { name: 'v', type: 'float' }
  30496. ]
  30497. } );
  30498. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30499. const v = vec3( v_immutable ).toVar();
  30500. return mul( 0.6616, v );
  30501. } ).setLayout( {
  30502. name: 'mx_gradient_scale2d_1',
  30503. type: 'vec3',
  30504. inputs: [
  30505. { name: 'v', type: 'vec3' }
  30506. ]
  30507. } );
  30508. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  30509. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30510. const v = vec3( v_immutable ).toVar();
  30511. return mul( 0.9820, v );
  30512. } ).setLayout( {
  30513. name: 'mx_gradient_scale3d_1',
  30514. type: 'vec3',
  30515. inputs: [
  30516. { name: 'v', type: 'vec3' }
  30517. ]
  30518. } );
  30519. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  30520. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  30521. const k = int( k_immutable ).toVar();
  30522. const x = uint( x_immutable ).toVar();
  30523. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  30524. } ).setLayout( {
  30525. name: 'mx_rotl32',
  30526. type: 'uint',
  30527. inputs: [
  30528. { name: 'x', type: 'uint' },
  30529. { name: 'k', type: 'int' }
  30530. ]
  30531. } );
  30532. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  30533. a.subAssign( c );
  30534. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  30535. c.addAssign( b );
  30536. b.subAssign( a );
  30537. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  30538. a.addAssign( c );
  30539. c.subAssign( b );
  30540. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  30541. b.addAssign( a );
  30542. a.subAssign( c );
  30543. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  30544. c.addAssign( b );
  30545. b.subAssign( a );
  30546. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  30547. a.addAssign( c );
  30548. c.subAssign( b );
  30549. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  30550. b.addAssign( a );
  30551. } );
  30552. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  30553. const c = uint( c_immutable ).toVar();
  30554. const b = uint( b_immutable ).toVar();
  30555. const a = uint( a_immutable ).toVar();
  30556. c.bitXorAssign( b );
  30557. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  30558. a.bitXorAssign( c );
  30559. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  30560. b.bitXorAssign( a );
  30561. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  30562. c.bitXorAssign( b );
  30563. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  30564. a.bitXorAssign( c );
  30565. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  30566. b.bitXorAssign( a );
  30567. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  30568. c.bitXorAssign( b );
  30569. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  30570. return c;
  30571. } ).setLayout( {
  30572. name: 'mx_bjfinal',
  30573. type: 'uint',
  30574. inputs: [
  30575. { name: 'a', type: 'uint' },
  30576. { name: 'b', type: 'uint' },
  30577. { name: 'c', type: 'uint' }
  30578. ]
  30579. } );
  30580. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  30581. const bits = uint( bits_immutable ).toVar();
  30582. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  30583. } ).setLayout( {
  30584. name: 'mx_bits_to_01',
  30585. type: 'float',
  30586. inputs: [
  30587. { name: 'bits', type: 'uint' }
  30588. ]
  30589. } );
  30590. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  30591. const t = float( t_immutable ).toVar();
  30592. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  30593. } ).setLayout( {
  30594. name: 'mx_fade',
  30595. type: 'float',
  30596. inputs: [
  30597. { name: 't', type: 'float' }
  30598. ]
  30599. } );
  30600. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30601. const x = int( x_immutable ).toVar();
  30602. const len = uint( uint( 1 ) ).toVar();
  30603. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  30604. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  30605. } ).setLayout( {
  30606. name: 'mx_hash_int_0',
  30607. type: 'uint',
  30608. inputs: [
  30609. { name: 'x', type: 'int' }
  30610. ]
  30611. } );
  30612. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30613. const y = int( y_immutable ).toVar();
  30614. const x = int( x_immutable ).toVar();
  30615. const len = uint( uint( 2 ) ).toVar();
  30616. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30617. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30618. a.addAssign( uint( x ) );
  30619. b.addAssign( uint( y ) );
  30620. return mx_bjfinal( a, b, c );
  30621. } ).setLayout( {
  30622. name: 'mx_hash_int_1',
  30623. type: 'uint',
  30624. inputs: [
  30625. { name: 'x', type: 'int' },
  30626. { name: 'y', type: 'int' }
  30627. ]
  30628. } );
  30629. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30630. const z = int( z_immutable ).toVar();
  30631. const y = int( y_immutable ).toVar();
  30632. const x = int( x_immutable ).toVar();
  30633. const len = uint( uint( 3 ) ).toVar();
  30634. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30635. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30636. a.addAssign( uint( x ) );
  30637. b.addAssign( uint( y ) );
  30638. c.addAssign( uint( z ) );
  30639. return mx_bjfinal( a, b, c );
  30640. } ).setLayout( {
  30641. name: 'mx_hash_int_2',
  30642. type: 'uint',
  30643. inputs: [
  30644. { name: 'x', type: 'int' },
  30645. { name: 'y', type: 'int' },
  30646. { name: 'z', type: 'int' }
  30647. ]
  30648. } );
  30649. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  30650. const xx = int( xx_immutable ).toVar();
  30651. const z = int( z_immutable ).toVar();
  30652. const y = int( y_immutable ).toVar();
  30653. const x = int( x_immutable ).toVar();
  30654. const len = uint( uint( 4 ) ).toVar();
  30655. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30656. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30657. a.addAssign( uint( x ) );
  30658. b.addAssign( uint( y ) );
  30659. c.addAssign( uint( z ) );
  30660. mx_bjmix( a, b, c );
  30661. a.addAssign( uint( xx ) );
  30662. return mx_bjfinal( a, b, c );
  30663. } ).setLayout( {
  30664. name: 'mx_hash_int_3',
  30665. type: 'uint',
  30666. inputs: [
  30667. { name: 'x', type: 'int' },
  30668. { name: 'y', type: 'int' },
  30669. { name: 'z', type: 'int' },
  30670. { name: 'xx', type: 'int' }
  30671. ]
  30672. } );
  30673. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  30674. const yy = int( yy_immutable ).toVar();
  30675. const xx = int( xx_immutable ).toVar();
  30676. const z = int( z_immutable ).toVar();
  30677. const y = int( y_immutable ).toVar();
  30678. const x = int( x_immutable ).toVar();
  30679. const len = uint( uint( 5 ) ).toVar();
  30680. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30681. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30682. a.addAssign( uint( x ) );
  30683. b.addAssign( uint( y ) );
  30684. c.addAssign( uint( z ) );
  30685. mx_bjmix( a, b, c );
  30686. a.addAssign( uint( xx ) );
  30687. b.addAssign( uint( yy ) );
  30688. return mx_bjfinal( a, b, c );
  30689. } ).setLayout( {
  30690. name: 'mx_hash_int_4',
  30691. type: 'uint',
  30692. inputs: [
  30693. { name: 'x', type: 'int' },
  30694. { name: 'y', type: 'int' },
  30695. { name: 'z', type: 'int' },
  30696. { name: 'xx', type: 'int' },
  30697. { name: 'yy', type: 'int' }
  30698. ]
  30699. } );
  30700. 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 ] );
  30701. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30702. const y = int( y_immutable ).toVar();
  30703. const x = int( x_immutable ).toVar();
  30704. const h = uint( mx_hash_int( x, y ) ).toVar();
  30705. const result = uvec3().toVar();
  30706. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30707. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30708. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30709. return result;
  30710. } ).setLayout( {
  30711. name: 'mx_hash_vec3_0',
  30712. type: 'uvec3',
  30713. inputs: [
  30714. { name: 'x', type: 'int' },
  30715. { name: 'y', type: 'int' }
  30716. ]
  30717. } );
  30718. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30719. const z = int( z_immutable ).toVar();
  30720. const y = int( y_immutable ).toVar();
  30721. const x = int( x_immutable ).toVar();
  30722. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  30723. const result = uvec3().toVar();
  30724. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30725. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30726. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30727. return result;
  30728. } ).setLayout( {
  30729. name: 'mx_hash_vec3_1',
  30730. type: 'uvec3',
  30731. inputs: [
  30732. { name: 'x', type: 'int' },
  30733. { name: 'y', type: 'int' },
  30734. { name: 'z', type: 'int' }
  30735. ]
  30736. } );
  30737. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  30738. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30739. const p = vec2( p_immutable ).toVar();
  30740. const X = int().toVar(), Y = int().toVar();
  30741. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30742. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30743. const u = float( mx_fade( fx ) ).toVar();
  30744. const v = float( mx_fade( fy ) ).toVar();
  30745. 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();
  30746. return mx_gradient_scale2d( result );
  30747. } ).setLayout( {
  30748. name: 'mx_perlin_noise_float_0',
  30749. type: 'float',
  30750. inputs: [
  30751. { name: 'p', type: 'vec2' }
  30752. ]
  30753. } );
  30754. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30755. const p = vec3( p_immutable ).toVar();
  30756. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30757. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30758. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30759. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  30760. const u = float( mx_fade( fx ) ).toVar();
  30761. const v = float( mx_fade( fy ) ).toVar();
  30762. const w = float( mx_fade( fz ) ).toVar();
  30763. 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();
  30764. return mx_gradient_scale3d( result );
  30765. } ).setLayout( {
  30766. name: 'mx_perlin_noise_float_1',
  30767. type: 'float',
  30768. inputs: [
  30769. { name: 'p', type: 'vec3' }
  30770. ]
  30771. } );
  30772. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  30773. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30774. const p = vec2( p_immutable ).toVar();
  30775. const X = int().toVar(), Y = int().toVar();
  30776. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30777. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30778. const u = float( mx_fade( fx ) ).toVar();
  30779. const v = float( mx_fade( fy ) ).toVar();
  30780. 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();
  30781. return mx_gradient_scale2d( result );
  30782. } ).setLayout( {
  30783. name: 'mx_perlin_noise_vec3_0',
  30784. type: 'vec3',
  30785. inputs: [
  30786. { name: 'p', type: 'vec2' }
  30787. ]
  30788. } );
  30789. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30790. const p = vec3( p_immutable ).toVar();
  30791. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30792. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30793. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30794. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  30795. const u = float( mx_fade( fx ) ).toVar();
  30796. const v = float( mx_fade( fy ) ).toVar();
  30797. const w = float( mx_fade( fz ) ).toVar();
  30798. 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();
  30799. return mx_gradient_scale3d( result );
  30800. } ).setLayout( {
  30801. name: 'mx_perlin_noise_vec3_1',
  30802. type: 'vec3',
  30803. inputs: [
  30804. { name: 'p', type: 'vec3' }
  30805. ]
  30806. } );
  30807. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  30808. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30809. const p = float( p_immutable ).toVar();
  30810. const ix = int( mx_floor( p ) ).toVar();
  30811. return mx_bits_to_01( mx_hash_int( ix ) );
  30812. } ).setLayout( {
  30813. name: 'mx_cell_noise_float_0',
  30814. type: 'float',
  30815. inputs: [
  30816. { name: 'p', type: 'float' }
  30817. ]
  30818. } );
  30819. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30820. const p = vec2( p_immutable ).toVar();
  30821. const ix = int( mx_floor( p.x ) ).toVar();
  30822. const iy = int( mx_floor( p.y ) ).toVar();
  30823. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  30824. } ).setLayout( {
  30825. name: 'mx_cell_noise_float_1',
  30826. type: 'float',
  30827. inputs: [
  30828. { name: 'p', type: 'vec2' }
  30829. ]
  30830. } );
  30831. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30832. const p = vec3( p_immutable ).toVar();
  30833. const ix = int( mx_floor( p.x ) ).toVar();
  30834. const iy = int( mx_floor( p.y ) ).toVar();
  30835. const iz = int( mx_floor( p.z ) ).toVar();
  30836. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  30837. } ).setLayout( {
  30838. name: 'mx_cell_noise_float_2',
  30839. type: 'float',
  30840. inputs: [
  30841. { name: 'p', type: 'vec3' }
  30842. ]
  30843. } );
  30844. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30845. const p = vec4( p_immutable ).toVar();
  30846. const ix = int( mx_floor( p.x ) ).toVar();
  30847. const iy = int( mx_floor( p.y ) ).toVar();
  30848. const iz = int( mx_floor( p.z ) ).toVar();
  30849. const iw = int( mx_floor( p.w ) ).toVar();
  30850. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  30851. } ).setLayout( {
  30852. name: 'mx_cell_noise_float_3',
  30853. type: 'float',
  30854. inputs: [
  30855. { name: 'p', type: 'vec4' }
  30856. ]
  30857. } );
  30858. 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 ] );
  30859. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30860. const p = float( p_immutable ).toVar();
  30861. const ix = int( mx_floor( p ) ).toVar();
  30862. 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 ) ) ) );
  30863. } ).setLayout( {
  30864. name: 'mx_cell_noise_vec3_0',
  30865. type: 'vec3',
  30866. inputs: [
  30867. { name: 'p', type: 'float' }
  30868. ]
  30869. } );
  30870. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30871. const p = vec2( p_immutable ).toVar();
  30872. const ix = int( mx_floor( p.x ) ).toVar();
  30873. const iy = int( mx_floor( p.y ) ).toVar();
  30874. 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 ) ) ) );
  30875. } ).setLayout( {
  30876. name: 'mx_cell_noise_vec3_1',
  30877. type: 'vec3',
  30878. inputs: [
  30879. { name: 'p', type: 'vec2' }
  30880. ]
  30881. } );
  30882. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30883. const p = vec3( p_immutable ).toVar();
  30884. const ix = int( mx_floor( p.x ) ).toVar();
  30885. const iy = int( mx_floor( p.y ) ).toVar();
  30886. const iz = int( mx_floor( p.z ) ).toVar();
  30887. 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 ) ) ) );
  30888. } ).setLayout( {
  30889. name: 'mx_cell_noise_vec3_2',
  30890. type: 'vec3',
  30891. inputs: [
  30892. { name: 'p', type: 'vec3' }
  30893. ]
  30894. } );
  30895. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30896. const p = vec4( p_immutable ).toVar();
  30897. const ix = int( mx_floor( p.x ) ).toVar();
  30898. const iy = int( mx_floor( p.y ) ).toVar();
  30899. const iz = int( mx_floor( p.z ) ).toVar();
  30900. const iw = int( mx_floor( p.w ) ).toVar();
  30901. 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 ) ) ) );
  30902. } ).setLayout( {
  30903. name: 'mx_cell_noise_vec3_3',
  30904. type: 'vec3',
  30905. inputs: [
  30906. { name: 'p', type: 'vec4' }
  30907. ]
  30908. } );
  30909. 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 ] );
  30910. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30911. const diminish = float( diminish_immutable ).toVar();
  30912. const lacunarity = float( lacunarity_immutable ).toVar();
  30913. const octaves = int( octaves_immutable ).toVar();
  30914. const p = vec3( p_immutable ).toVar();
  30915. const result = float( 0.0 ).toVar();
  30916. const amplitude = float( 1.0 ).toVar();
  30917. Loop( octaves, () => {
  30918. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  30919. amplitude.mulAssign( diminish );
  30920. p.mulAssign( lacunarity );
  30921. } );
  30922. return result;
  30923. } ).setLayout( {
  30924. name: 'mx_fractal_noise_float',
  30925. type: 'float',
  30926. inputs: [
  30927. { name: 'p', type: 'vec3' },
  30928. { name: 'octaves', type: 'int' },
  30929. { name: 'lacunarity', type: 'float' },
  30930. { name: 'diminish', type: 'float' }
  30931. ]
  30932. } );
  30933. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30934. const diminish = float( diminish_immutable ).toVar();
  30935. const lacunarity = float( lacunarity_immutable ).toVar();
  30936. const octaves = int( octaves_immutable ).toVar();
  30937. const p = vec3( p_immutable ).toVar();
  30938. const result = vec3( 0.0 ).toVar();
  30939. const amplitude = float( 1.0 ).toVar();
  30940. Loop( octaves, () => {
  30941. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  30942. amplitude.mulAssign( diminish );
  30943. p.mulAssign( lacunarity );
  30944. } );
  30945. return result;
  30946. } ).setLayout( {
  30947. name: 'mx_fractal_noise_vec3',
  30948. type: 'vec3',
  30949. inputs: [
  30950. { name: 'p', type: 'vec3' },
  30951. { name: 'octaves', type: 'int' },
  30952. { name: 'lacunarity', type: 'float' },
  30953. { name: 'diminish', type: 'float' }
  30954. ]
  30955. } );
  30956. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30957. const diminish = float( diminish_immutable ).toVar();
  30958. const lacunarity = float( lacunarity_immutable ).toVar();
  30959. const octaves = int( octaves_immutable ).toVar();
  30960. const p = vec3( p_immutable ).toVar();
  30961. 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 ) );
  30962. } ).setLayout( {
  30963. name: 'mx_fractal_noise_vec2',
  30964. type: 'vec2',
  30965. inputs: [
  30966. { name: 'p', type: 'vec3' },
  30967. { name: 'octaves', type: 'int' },
  30968. { name: 'lacunarity', type: 'float' },
  30969. { name: 'diminish', type: 'float' }
  30970. ]
  30971. } );
  30972. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30973. const diminish = float( diminish_immutable ).toVar();
  30974. const lacunarity = float( lacunarity_immutable ).toVar();
  30975. const octaves = int( octaves_immutable ).toVar();
  30976. const p = vec3( p_immutable ).toVar();
  30977. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  30978. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  30979. return vec4( c, f );
  30980. } ).setLayout( {
  30981. name: 'mx_fractal_noise_vec4',
  30982. type: 'vec4',
  30983. inputs: [
  30984. { name: 'p', type: 'vec3' },
  30985. { name: 'octaves', type: 'int' },
  30986. { name: 'lacunarity', type: 'float' },
  30987. { name: 'diminish', type: 'float' }
  30988. ]
  30989. } );
  30990. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  30991. const metric = int( metric_immutable ).toVar();
  30992. const jitter = float( jitter_immutable ).toVar();
  30993. const yoff = int( yoff_immutable ).toVar();
  30994. const xoff = int( xoff_immutable ).toVar();
  30995. const y = int( y_immutable ).toVar();
  30996. const x = int( x_immutable ).toVar();
  30997. const p = vec2( p_immutable ).toVar();
  30998. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  30999. const off = vec2( tmp.x, tmp.y ).toVar();
  31000. off.subAssign( 0.5 );
  31001. off.mulAssign( jitter );
  31002. off.addAssign( 0.5 );
  31003. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  31004. const diff = vec2( cellpos.sub( p ) ).toVar();
  31005. If( metric.equal( int( 2 ) ), () => {
  31006. return abs( diff.x ).add( abs( diff.y ) );
  31007. } );
  31008. If( metric.equal( int( 3 ) ), () => {
  31009. return max$1( abs( diff.x ), abs( diff.y ) );
  31010. } );
  31011. return dot( diff, diff );
  31012. } ).setLayout( {
  31013. name: 'mx_worley_distance_0',
  31014. type: 'float',
  31015. inputs: [
  31016. { name: 'p', type: 'vec2' },
  31017. { name: 'x', type: 'int' },
  31018. { name: 'y', type: 'int' },
  31019. { name: 'xoff', type: 'int' },
  31020. { name: 'yoff', type: 'int' },
  31021. { name: 'jitter', type: 'float' },
  31022. { name: 'metric', type: 'int' }
  31023. ]
  31024. } );
  31025. 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 ] ) => {
  31026. const metric = int( metric_immutable ).toVar();
  31027. const jitter = float( jitter_immutable ).toVar();
  31028. const zoff = int( zoff_immutable ).toVar();
  31029. const yoff = int( yoff_immutable ).toVar();
  31030. const xoff = int( xoff_immutable ).toVar();
  31031. const z = int( z_immutable ).toVar();
  31032. const y = int( y_immutable ).toVar();
  31033. const x = int( x_immutable ).toVar();
  31034. const p = vec3( p_immutable ).toVar();
  31035. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  31036. off.subAssign( 0.5 );
  31037. off.mulAssign( jitter );
  31038. off.addAssign( 0.5 );
  31039. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  31040. const diff = vec3( cellpos.sub( p ) ).toVar();
  31041. If( metric.equal( int( 2 ) ), () => {
  31042. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  31043. } );
  31044. If( metric.equal( int( 3 ) ), () => {
  31045. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  31046. } );
  31047. return dot( diff, diff );
  31048. } ).setLayout( {
  31049. name: 'mx_worley_distance_1',
  31050. type: 'float',
  31051. inputs: [
  31052. { name: 'p', type: 'vec3' },
  31053. { name: 'x', type: 'int' },
  31054. { name: 'y', type: 'int' },
  31055. { name: 'z', type: 'int' },
  31056. { name: 'xoff', type: 'int' },
  31057. { name: 'yoff', type: 'int' },
  31058. { name: 'zoff', type: 'int' },
  31059. { name: 'jitter', type: 'float' },
  31060. { name: 'metric', type: 'int' }
  31061. ]
  31062. } );
  31063. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  31064. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31065. const metric = int( metric_immutable ).toVar();
  31066. const jitter = float( jitter_immutable ).toVar();
  31067. const p = vec2( p_immutable ).toVar();
  31068. const X = int().toVar(), Y = int().toVar();
  31069. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31070. const sqdist = float( 1e6 ).toVar();
  31071. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31072. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31073. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31074. sqdist.assign( min$1( sqdist, dist ) );
  31075. } );
  31076. } );
  31077. If( metric.equal( int( 0 ) ), () => {
  31078. sqdist.assign( sqrt( sqdist ) );
  31079. } );
  31080. return sqdist;
  31081. } ).setLayout( {
  31082. name: 'mx_worley_noise_float_0',
  31083. type: 'float',
  31084. inputs: [
  31085. { name: 'p', type: 'vec2' },
  31086. { name: 'jitter', type: 'float' },
  31087. { name: 'metric', type: 'int' }
  31088. ]
  31089. } );
  31090. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31091. const metric = int( metric_immutable ).toVar();
  31092. const jitter = float( jitter_immutable ).toVar();
  31093. const p = vec2( p_immutable ).toVar();
  31094. const X = int().toVar(), Y = int().toVar();
  31095. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31096. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31097. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31098. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31099. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31100. If( dist.lessThan( sqdist.x ), () => {
  31101. sqdist.y.assign( sqdist.x );
  31102. sqdist.x.assign( dist );
  31103. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31104. sqdist.y.assign( dist );
  31105. } );
  31106. } );
  31107. } );
  31108. If( metric.equal( int( 0 ) ), () => {
  31109. sqdist.assign( sqrt( sqdist ) );
  31110. } );
  31111. return sqdist;
  31112. } ).setLayout( {
  31113. name: 'mx_worley_noise_vec2_0',
  31114. type: 'vec2',
  31115. inputs: [
  31116. { name: 'p', type: 'vec2' },
  31117. { name: 'jitter', type: 'float' },
  31118. { name: 'metric', type: 'int' }
  31119. ]
  31120. } );
  31121. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31122. const metric = int( metric_immutable ).toVar();
  31123. const jitter = float( jitter_immutable ).toVar();
  31124. const p = vec2( p_immutable ).toVar();
  31125. const X = int().toVar(), Y = int().toVar();
  31126. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31127. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31128. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31129. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31130. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31131. If( dist.lessThan( sqdist.x ), () => {
  31132. sqdist.z.assign( sqdist.y );
  31133. sqdist.y.assign( sqdist.x );
  31134. sqdist.x.assign( dist );
  31135. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31136. sqdist.z.assign( sqdist.y );
  31137. sqdist.y.assign( dist );
  31138. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31139. sqdist.z.assign( dist );
  31140. } );
  31141. } );
  31142. } );
  31143. If( metric.equal( int( 0 ) ), () => {
  31144. sqdist.assign( sqrt( sqdist ) );
  31145. } );
  31146. return sqdist;
  31147. } ).setLayout( {
  31148. name: 'mx_worley_noise_vec3_0',
  31149. type: 'vec3',
  31150. inputs: [
  31151. { name: 'p', type: 'vec2' },
  31152. { name: 'jitter', type: 'float' },
  31153. { name: 'metric', type: 'int' }
  31154. ]
  31155. } );
  31156. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31157. const metric = int( metric_immutable ).toVar();
  31158. const jitter = float( jitter_immutable ).toVar();
  31159. const p = vec3( p_immutable ).toVar();
  31160. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31161. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31162. const sqdist = float( 1e6 ).toVar();
  31163. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31164. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31165. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31166. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31167. sqdist.assign( min$1( sqdist, dist ) );
  31168. } );
  31169. } );
  31170. } );
  31171. If( metric.equal( int( 0 ) ), () => {
  31172. sqdist.assign( sqrt( sqdist ) );
  31173. } );
  31174. return sqdist;
  31175. } ).setLayout( {
  31176. name: 'mx_worley_noise_float_1',
  31177. type: 'float',
  31178. inputs: [
  31179. { name: 'p', type: 'vec3' },
  31180. { name: 'jitter', type: 'float' },
  31181. { name: 'metric', type: 'int' }
  31182. ]
  31183. } );
  31184. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  31185. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31186. const metric = int( metric_immutable ).toVar();
  31187. const jitter = float( jitter_immutable ).toVar();
  31188. const p = vec3( p_immutable ).toVar();
  31189. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31190. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31191. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31192. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31193. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31194. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31195. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31196. If( dist.lessThan( sqdist.x ), () => {
  31197. sqdist.y.assign( sqdist.x );
  31198. sqdist.x.assign( dist );
  31199. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31200. sqdist.y.assign( dist );
  31201. } );
  31202. } );
  31203. } );
  31204. } );
  31205. If( metric.equal( int( 0 ) ), () => {
  31206. sqdist.assign( sqrt( sqdist ) );
  31207. } );
  31208. return sqdist;
  31209. } ).setLayout( {
  31210. name: 'mx_worley_noise_vec2_1',
  31211. type: 'vec2',
  31212. inputs: [
  31213. { name: 'p', type: 'vec3' },
  31214. { name: 'jitter', type: 'float' },
  31215. { name: 'metric', type: 'int' }
  31216. ]
  31217. } );
  31218. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  31219. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31220. const metric = int( metric_immutable ).toVar();
  31221. const jitter = float( jitter_immutable ).toVar();
  31222. const p = vec3( p_immutable ).toVar();
  31223. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31224. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31225. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31226. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31227. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31228. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31229. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31230. If( dist.lessThan( sqdist.x ), () => {
  31231. sqdist.z.assign( sqdist.y );
  31232. sqdist.y.assign( sqdist.x );
  31233. sqdist.x.assign( dist );
  31234. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31235. sqdist.z.assign( sqdist.y );
  31236. sqdist.y.assign( dist );
  31237. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31238. sqdist.z.assign( dist );
  31239. } );
  31240. } );
  31241. } );
  31242. } );
  31243. If( metric.equal( int( 0 ) ), () => {
  31244. sqdist.assign( sqrt( sqdist ) );
  31245. } );
  31246. return sqdist;
  31247. } ).setLayout( {
  31248. name: 'mx_worley_noise_vec3_1',
  31249. type: 'vec3',
  31250. inputs: [
  31251. { name: 'p', type: 'vec3' },
  31252. { name: 'jitter', type: 'float' },
  31253. { name: 'metric', type: 'int' }
  31254. ]
  31255. } );
  31256. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  31257. // Unified Noise 2D
  31258. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  31259. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  31260. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31261. octaves_immutable, lacunarity_immutable, diminish_immutable
  31262. ] ) => {
  31263. const noiseType = int( noiseType_immutable ).toVar();
  31264. const texcoord = vec2( texcoord_immutable ).toVar();
  31265. const freq = vec2( freq_immutable ).toVar();
  31266. const offset = vec2( offset_immutable ).toVar();
  31267. const jitter = float( jitter_immutable ).toVar();
  31268. const outmin = float( outmin_immutable ).toVar();
  31269. const outmax = float( outmax_immutable ).toVar();
  31270. const clampoutput = bool( clampoutput_immutable ).toVar();
  31271. const octaves = int( octaves_immutable ).toVar();
  31272. const lacunarity = float( lacunarity_immutable ).toVar();
  31273. const diminish = float( diminish_immutable ).toVar();
  31274. // Compute input position
  31275. const p = texcoord.mul( freq ).add( offset );
  31276. const result = float( 0.0 ).toVar();
  31277. // Perlin
  31278. If( noiseType.equal( int( 0 ) ), () => {
  31279. result.assign( mx_perlin_noise_vec3( p ) );
  31280. } );
  31281. // Cell
  31282. If( noiseType.equal( int( 1 ) ), () => {
  31283. result.assign( mx_cell_noise_vec3( p ) );
  31284. } );
  31285. // Worley (metric=0 = euclidean)
  31286. If( noiseType.equal( int( 2 ) ), () => {
  31287. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31288. } );
  31289. // Fractal (use vec3(p, 0.0) for 2D input)
  31290. If( noiseType.equal( int( 3 ) ), () => {
  31291. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  31292. } );
  31293. // Remap output to [outmin, outmax]
  31294. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31295. // Clamp if requested
  31296. If( clampoutput, () => {
  31297. result.assign( clamp( result, outmin, outmax ) );
  31298. } );
  31299. return result;
  31300. } ).setLayout( {
  31301. name: 'mx_unifiednoise2d',
  31302. type: 'float',
  31303. inputs: [
  31304. { name: 'noiseType', type: 'int' },
  31305. { name: 'texcoord', type: 'vec2' },
  31306. { name: 'freq', type: 'vec2' },
  31307. { name: 'offset', type: 'vec2' },
  31308. { name: 'jitter', type: 'float' },
  31309. { name: 'outmin', type: 'float' },
  31310. { name: 'outmax', type: 'float' },
  31311. { name: 'clampoutput', type: 'bool' },
  31312. { name: 'octaves', type: 'int' },
  31313. { name: 'lacunarity', type: 'float' },
  31314. { name: 'diminish', type: 'float' }
  31315. ]
  31316. } );
  31317. // Unified Noise 3D
  31318. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  31319. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  31320. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31321. octaves_immutable, lacunarity_immutable, diminish_immutable
  31322. ] ) => {
  31323. const noiseType = int( noiseType_immutable ).toVar();
  31324. const position = vec3( position_immutable ).toVar();
  31325. const freq = vec3( freq_immutable ).toVar();
  31326. const offset = vec3( offset_immutable ).toVar();
  31327. const jitter = float( jitter_immutable ).toVar();
  31328. const outmin = float( outmin_immutable ).toVar();
  31329. const outmax = float( outmax_immutable ).toVar();
  31330. const clampoutput = bool( clampoutput_immutable ).toVar();
  31331. const octaves = int( octaves_immutable ).toVar();
  31332. const lacunarity = float( lacunarity_immutable ).toVar();
  31333. const diminish = float( diminish_immutable ).toVar();
  31334. // Compute input position
  31335. const p = position.mul( freq ).add( offset );
  31336. const result = float( 0.0 ).toVar();
  31337. // Perlin
  31338. If( noiseType.equal( int( 0 ) ), () => {
  31339. result.assign( mx_perlin_noise_vec3( p ) );
  31340. } );
  31341. // Cell
  31342. If( noiseType.equal( int( 1 ) ), () => {
  31343. result.assign( mx_cell_noise_vec3( p ) );
  31344. } );
  31345. // Worley (metric=0 = euclidean)
  31346. If( noiseType.equal( int( 2 ) ), () => {
  31347. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31348. } );
  31349. // Fractal
  31350. If( noiseType.equal( int( 3 ) ), () => {
  31351. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  31352. } );
  31353. // Remap output to [outmin, outmax]
  31354. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31355. // Clamp if requested
  31356. If( clampoutput, () => {
  31357. result.assign( clamp( result, outmin, outmax ) );
  31358. } );
  31359. return result;
  31360. } ).setLayout( {
  31361. name: 'mx_unifiednoise3d',
  31362. type: 'float',
  31363. inputs: [
  31364. { name: 'noiseType', type: 'int' },
  31365. { name: 'position', type: 'vec3' },
  31366. { name: 'freq', type: 'vec3' },
  31367. { name: 'offset', type: 'vec3' },
  31368. { name: 'jitter', type: 'float' },
  31369. { name: 'outmin', type: 'float' },
  31370. { name: 'outmax', type: 'float' },
  31371. { name: 'clampoutput', type: 'bool' },
  31372. { name: 'octaves', type: 'int' },
  31373. { name: 'lacunarity', type: 'float' },
  31374. { name: 'diminish', type: 'float' }
  31375. ]
  31376. } );
  31377. // Three.js Transpiler
  31378. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  31379. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  31380. const s = hsv.y;
  31381. const v = hsv.z;
  31382. const result = vec3().toVar();
  31383. If( s.lessThan( 0.0001 ), () => {
  31384. result.assign( vec3( v, v, v ) );
  31385. } ).Else( () => {
  31386. let h = hsv.x;
  31387. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  31388. const hi = int( trunc( h ) );
  31389. const f = h.sub( float( hi ) );
  31390. const p = v.mul( s.oneMinus() );
  31391. const q = v.mul( s.mul( f ).oneMinus() );
  31392. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  31393. If( hi.equal( int( 0 ) ), () => {
  31394. result.assign( vec3( v, t, p ) );
  31395. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  31396. result.assign( vec3( q, v, p ) );
  31397. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  31398. result.assign( vec3( p, v, t ) );
  31399. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  31400. result.assign( vec3( p, q, v ) );
  31401. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  31402. result.assign( vec3( t, p, v ) );
  31403. } ).Else( () => {
  31404. result.assign( vec3( v, p, q ) );
  31405. } );
  31406. } );
  31407. return result;
  31408. } ).setLayout( {
  31409. name: 'mx_hsvtorgb',
  31410. type: 'vec3',
  31411. inputs: [
  31412. { name: 'hsv', type: 'vec3' }
  31413. ]
  31414. } );
  31415. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  31416. const c = vec3( c_immutable ).toVar();
  31417. const r = float( c.x ).toVar();
  31418. const g = float( c.y ).toVar();
  31419. const b = float( c.z ).toVar();
  31420. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  31421. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  31422. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  31423. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  31424. v.assign( maxcomp );
  31425. If( maxcomp.greaterThan( 0.0 ), () => {
  31426. s.assign( delta.div( maxcomp ) );
  31427. } ).Else( () => {
  31428. s.assign( 0.0 );
  31429. } );
  31430. If( s.lessThanEqual( 0.0 ), () => {
  31431. h.assign( 0.0 );
  31432. } ).Else( () => {
  31433. If( r.greaterThanEqual( maxcomp ), () => {
  31434. h.assign( g.sub( b ).div( delta ) );
  31435. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  31436. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  31437. } ).Else( () => {
  31438. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  31439. } );
  31440. h.mulAssign( 1.0 / 6.0 );
  31441. If( h.lessThan( 0.0 ), () => {
  31442. h.addAssign( 1.0 );
  31443. } );
  31444. } );
  31445. return vec3( h, s, v );
  31446. } ).setLayout( {
  31447. name: 'mx_rgbtohsv',
  31448. type: 'vec3',
  31449. inputs: [
  31450. { name: 'c', type: 'vec3' }
  31451. ]
  31452. } );
  31453. // Three.js Transpiler
  31454. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  31455. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  31456. const color = vec3( color_immutable ).toVar();
  31457. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  31458. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  31459. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  31460. return mix( linSeg, powSeg, isAbove );
  31461. } ).setLayout( {
  31462. name: 'mx_srgb_texture_to_lin_rec709',
  31463. type: 'vec3',
  31464. inputs: [
  31465. { name: 'color', type: 'vec3' }
  31466. ]
  31467. } );
  31468. const mx_aastep = ( threshold, value ) => {
  31469. threshold = float( threshold );
  31470. value = float( value );
  31471. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  31472. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  31473. };
  31474. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  31475. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  31476. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  31477. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  31478. const mx_ramp4 = (
  31479. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  31480. ) => {
  31481. const u = texcoord.x.clamp();
  31482. const v = texcoord.y.clamp();
  31483. const top = mix( valuetl, valuetr, u );
  31484. const bottom = mix( valuebl, valuebr, u );
  31485. return mix( top, bottom, v );
  31486. };
  31487. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  31488. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  31489. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  31490. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  31491. const mx_safepower = ( in1, in2 = 1 ) => {
  31492. in1 = float( in1 );
  31493. return in1.abs().pow( in2 ).mul( in1.sign() );
  31494. };
  31495. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  31496. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31497. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31498. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31499. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  31500. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  31501. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  31502. return noise_vec4.mul( amplitude ).add( pivot );
  31503. };
  31504. 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 );
  31505. 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 );
  31506. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31507. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31508. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31509. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  31510. 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 );
  31511. 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 );
  31512. 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 );
  31513. 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 );
  31514. // === Moved from MaterialXLoader.js ===
  31515. // Math ops
  31516. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  31517. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  31518. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  31519. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  31520. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  31521. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  31522. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  31523. const mx_timer = () => time;
  31524. const mx_frame = () => frameId;
  31525. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  31526. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  31527. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  31528. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  31529. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  31530. const mx_separate = ( in1, channelOrOut = null ) => {
  31531. if ( typeof channelOrOut === 'string' ) {
  31532. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31533. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  31534. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  31535. }
  31536. if ( typeof channelOrOut === 'number' ) {
  31537. return in1.element( channelOrOut );
  31538. }
  31539. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  31540. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31541. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  31542. }
  31543. return in1;
  31544. };
  31545. const mx_place2d = (
  31546. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  31547. ) => {
  31548. let uv = texcoord;
  31549. if ( pivot ) uv = uv.sub( pivot );
  31550. if ( scale ) uv = uv.mul( scale );
  31551. if ( rotate ) {
  31552. const rad = rotate.mul( Math.PI / 180.0 );
  31553. const cosR = rad.cos();
  31554. const sinR = rad.sin();
  31555. uv = vec2(
  31556. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  31557. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  31558. );
  31559. }
  31560. if ( pivot ) uv = uv.add( pivot );
  31561. if ( offset ) uv = uv.add( offset );
  31562. return uv;
  31563. };
  31564. const mx_rotate2d = ( input, amount ) => {
  31565. input = vec2( input );
  31566. amount = float( amount );
  31567. const radians = amount.mul( Math.PI / 180.0 );
  31568. return rotate( input, radians );
  31569. };
  31570. const mx_rotate3d = ( input, amount, axis ) => {
  31571. input = vec3( input );
  31572. amount = float( amount );
  31573. axis = vec3( axis );
  31574. const radians = amount.mul( Math.PI / 180.0 );
  31575. const nAxis = axis.normalize();
  31576. const cosA = radians.cos();
  31577. const sinA = radians.sin();
  31578. const oneMinusCosA = float( 1 ).sub( cosA );
  31579. const rot =
  31580. input.mul( cosA )
  31581. .add( nAxis.cross( input ).mul( sinA ) )
  31582. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  31583. return rot;
  31584. };
  31585. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  31586. input = vec3( input );
  31587. scale = float( scale );
  31588. return bumpMap( input, scale );
  31589. };
  31590. /**
  31591. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  31592. *
  31593. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  31594. *
  31595. * ```js
  31596. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  31597. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  31598. * ```
  31599. *
  31600. * @tsl
  31601. * @function
  31602. * @param {Node<vec3>} normal - The normal to correct.
  31603. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  31604. * @param {Node<vec3>} cubePos - The cube position.
  31605. * @return {Node<vec3>} The parallax corrected normal.
  31606. */
  31607. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  31608. const nDir = normalize( normal ).toVar();
  31609. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31610. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31611. const rbminmax = vec3().toVar();
  31612. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  31613. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  31614. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  31615. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  31616. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  31617. return boxIntersection.sub( cubePos );
  31618. } );
  31619. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  31620. // normal is assumed to have unit length
  31621. const x = normal.x, y = normal.y, z = normal.z;
  31622. // band 0
  31623. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  31624. // band 1
  31625. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  31626. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  31627. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  31628. // band 2
  31629. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  31630. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  31631. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  31632. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  31633. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  31634. return result;
  31635. } );
  31636. // constants
  31637. var TSL = /*#__PURE__*/Object.freeze({
  31638. __proto__: null,
  31639. BRDF_GGX: BRDF_GGX,
  31640. BRDF_Lambert: BRDF_Lambert,
  31641. BasicPointShadowFilter: BasicPointShadowFilter,
  31642. BasicShadowFilter: BasicShadowFilter,
  31643. Break: Break,
  31644. Const: Const,
  31645. Continue: Continue,
  31646. DFGApprox: DFGApprox,
  31647. D_GGX: D_GGX,
  31648. Discard: Discard,
  31649. EPSILON: EPSILON,
  31650. F_Schlick: F_Schlick,
  31651. Fn: Fn,
  31652. HALF_PI: HALF_PI,
  31653. INFINITY: INFINITY,
  31654. If: If,
  31655. Loop: Loop,
  31656. NodeAccess: NodeAccess,
  31657. NodeShaderStage: NodeShaderStage,
  31658. NodeType: NodeType,
  31659. NodeUpdateType: NodeUpdateType,
  31660. OnMaterialUpdate: OnMaterialUpdate,
  31661. OnObjectUpdate: OnObjectUpdate,
  31662. PCFShadowFilter: PCFShadowFilter,
  31663. PCFSoftShadowFilter: PCFSoftShadowFilter,
  31664. PI: PI,
  31665. PI2: PI2,
  31666. PointShadowFilter: PointShadowFilter,
  31667. Return: Return,
  31668. Schlick_to_F0: Schlick_to_F0,
  31669. ScriptableNodeResources: ScriptableNodeResources,
  31670. ShaderNode: ShaderNode,
  31671. Stack: Stack,
  31672. Switch: Switch,
  31673. TBNViewMatrix: TBNViewMatrix,
  31674. TWO_PI: TWO_PI,
  31675. VSMShadowFilter: VSMShadowFilter,
  31676. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  31677. Var: Var,
  31678. VarIntent: VarIntent,
  31679. abs: abs,
  31680. acesFilmicToneMapping: acesFilmicToneMapping,
  31681. acos: acos,
  31682. add: add,
  31683. addMethodChaining: addMethodChaining,
  31684. addNodeElement: addNodeElement,
  31685. agxToneMapping: agxToneMapping,
  31686. all: all,
  31687. alphaT: alphaT,
  31688. and: and,
  31689. anisotropy: anisotropy,
  31690. anisotropyB: anisotropyB,
  31691. anisotropyT: anisotropyT,
  31692. any: any,
  31693. append: append,
  31694. array: array,
  31695. arrayBuffer: arrayBuffer,
  31696. asin: asin,
  31697. assign: assign,
  31698. atan: atan,
  31699. atan2: atan2,
  31700. atomicAdd: atomicAdd,
  31701. atomicAnd: atomicAnd,
  31702. atomicFunc: atomicFunc,
  31703. atomicLoad: atomicLoad,
  31704. atomicMax: atomicMax,
  31705. atomicMin: atomicMin,
  31706. atomicOr: atomicOr,
  31707. atomicStore: atomicStore,
  31708. atomicSub: atomicSub,
  31709. atomicXor: atomicXor,
  31710. attenuationColor: attenuationColor,
  31711. attenuationDistance: attenuationDistance,
  31712. attribute: attribute,
  31713. attributeArray: attributeArray,
  31714. backgroundBlurriness: backgroundBlurriness,
  31715. backgroundIntensity: backgroundIntensity,
  31716. backgroundRotation: backgroundRotation,
  31717. batch: batch,
  31718. bentNormalView: bentNormalView,
  31719. billboarding: billboarding,
  31720. bitAnd: bitAnd,
  31721. bitNot: bitNot,
  31722. bitOr: bitOr,
  31723. bitXor: bitXor,
  31724. bitangentGeometry: bitangentGeometry,
  31725. bitangentLocal: bitangentLocal,
  31726. bitangentView: bitangentView,
  31727. bitangentWorld: bitangentWorld,
  31728. bitcast: bitcast,
  31729. blendBurn: blendBurn,
  31730. blendColor: blendColor,
  31731. blendDodge: blendDodge,
  31732. blendOverlay: blendOverlay,
  31733. blendScreen: blendScreen,
  31734. blur: blur,
  31735. bool: bool,
  31736. buffer: buffer,
  31737. bufferAttribute: bufferAttribute,
  31738. builtin: builtin,
  31739. bumpMap: bumpMap,
  31740. burn: burn,
  31741. bvec2: bvec2,
  31742. bvec3: bvec3,
  31743. bvec4: bvec4,
  31744. bypass: bypass,
  31745. cache: cache,
  31746. call: call,
  31747. cameraFar: cameraFar,
  31748. cameraIndex: cameraIndex,
  31749. cameraNear: cameraNear,
  31750. cameraNormalMatrix: cameraNormalMatrix,
  31751. cameraPosition: cameraPosition,
  31752. cameraProjectionMatrix: cameraProjectionMatrix,
  31753. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  31754. cameraViewMatrix: cameraViewMatrix,
  31755. cameraViewport: cameraViewport,
  31756. cameraWorldMatrix: cameraWorldMatrix,
  31757. cbrt: cbrt,
  31758. cdl: cdl,
  31759. ceil: ceil,
  31760. checker: checker,
  31761. cineonToneMapping: cineonToneMapping,
  31762. clamp: clamp,
  31763. clearcoat: clearcoat,
  31764. clearcoatNormalView: clearcoatNormalView,
  31765. clearcoatRoughness: clearcoatRoughness,
  31766. code: code,
  31767. color: color,
  31768. colorSpaceToWorking: colorSpaceToWorking,
  31769. colorToDirection: colorToDirection,
  31770. compute: compute,
  31771. computeKernel: computeKernel,
  31772. computeSkinning: computeSkinning,
  31773. context: context,
  31774. convert: convert,
  31775. convertColorSpace: convertColorSpace,
  31776. convertToTexture: convertToTexture,
  31777. cos: cos,
  31778. cross: cross,
  31779. cubeTexture: cubeTexture,
  31780. cubeTextureBase: cubeTextureBase,
  31781. cubeToUV: cubeToUV,
  31782. dFdx: dFdx,
  31783. dFdy: dFdy,
  31784. dashSize: dashSize,
  31785. debug: debug,
  31786. decrement: decrement,
  31787. decrementBefore: decrementBefore,
  31788. defaultBuildStages: defaultBuildStages,
  31789. defaultShaderStages: defaultShaderStages,
  31790. defined: defined,
  31791. degrees: degrees,
  31792. deltaTime: deltaTime,
  31793. densityFog: densityFog,
  31794. densityFogFactor: densityFogFactor,
  31795. depth: depth,
  31796. depthPass: depthPass,
  31797. determinant: determinant,
  31798. difference: difference,
  31799. diffuseColor: diffuseColor,
  31800. directPointLight: directPointLight,
  31801. directionToColor: directionToColor,
  31802. directionToFaceDirection: directionToFaceDirection,
  31803. dispersion: dispersion,
  31804. distance: distance,
  31805. div: div,
  31806. dodge: dodge,
  31807. dot: dot,
  31808. drawIndex: drawIndex,
  31809. dynamicBufferAttribute: dynamicBufferAttribute,
  31810. element: element,
  31811. emissive: emissive,
  31812. equal: equal,
  31813. equals: equals,
  31814. equirectUV: equirectUV,
  31815. exp: exp,
  31816. exp2: exp2,
  31817. expression: expression,
  31818. faceDirection: faceDirection,
  31819. faceForward: faceForward,
  31820. faceforward: faceforward,
  31821. float: float,
  31822. floatBitsToInt: floatBitsToInt,
  31823. floatBitsToUint: floatBitsToUint,
  31824. floor: floor,
  31825. fog: fog,
  31826. fract: fract,
  31827. frameGroup: frameGroup,
  31828. frameId: frameId,
  31829. frontFacing: frontFacing,
  31830. fwidth: fwidth,
  31831. gain: gain,
  31832. gapSize: gapSize,
  31833. getConstNodeType: getConstNodeType,
  31834. getCurrentStack: getCurrentStack,
  31835. getDirection: getDirection,
  31836. getDistanceAttenuation: getDistanceAttenuation,
  31837. getGeometryRoughness: getGeometryRoughness,
  31838. getNormalFromDepth: getNormalFromDepth,
  31839. getParallaxCorrectNormal: getParallaxCorrectNormal,
  31840. getRoughness: getRoughness,
  31841. getScreenPosition: getScreenPosition,
  31842. getShIrradianceAt: getShIrradianceAt,
  31843. getShadowMaterial: getShadowMaterial,
  31844. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  31845. getTextureIndex: getTextureIndex,
  31846. getViewPosition: getViewPosition,
  31847. globalId: globalId,
  31848. glsl: glsl,
  31849. glslFn: glslFn,
  31850. grayscale: grayscale,
  31851. greaterThan: greaterThan,
  31852. greaterThanEqual: greaterThanEqual,
  31853. hash: hash,
  31854. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  31855. highpModelViewMatrix: highpModelViewMatrix,
  31856. hue: hue,
  31857. increment: increment,
  31858. incrementBefore: incrementBefore,
  31859. instance: instance,
  31860. instanceIndex: instanceIndex,
  31861. instancedArray: instancedArray,
  31862. instancedBufferAttribute: instancedBufferAttribute,
  31863. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  31864. instancedMesh: instancedMesh,
  31865. int: int,
  31866. intBitsToFloat: intBitsToFloat,
  31867. inverse: inverse,
  31868. inverseSqrt: inverseSqrt,
  31869. inversesqrt: inversesqrt,
  31870. invocationLocalIndex: invocationLocalIndex,
  31871. invocationSubgroupIndex: invocationSubgroupIndex,
  31872. ior: ior,
  31873. iridescence: iridescence,
  31874. iridescenceIOR: iridescenceIOR,
  31875. iridescenceThickness: iridescenceThickness,
  31876. ivec2: ivec2,
  31877. ivec3: ivec3,
  31878. ivec4: ivec4,
  31879. js: js,
  31880. label: label,
  31881. length: length,
  31882. lengthSq: lengthSq,
  31883. lessThan: lessThan,
  31884. lessThanEqual: lessThanEqual,
  31885. lightPosition: lightPosition,
  31886. lightProjectionUV: lightProjectionUV,
  31887. lightShadowMatrix: lightShadowMatrix,
  31888. lightTargetDirection: lightTargetDirection,
  31889. lightTargetPosition: lightTargetPosition,
  31890. lightViewPosition: lightViewPosition,
  31891. lightingContext: lightingContext,
  31892. lights: lights,
  31893. linearDepth: linearDepth,
  31894. linearToneMapping: linearToneMapping,
  31895. localId: localId,
  31896. log: log,
  31897. log2: log2,
  31898. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  31899. luminance: luminance,
  31900. mat2: mat2,
  31901. mat3: mat3,
  31902. mat4: mat4,
  31903. matcapUV: matcapUV,
  31904. materialAO: materialAO,
  31905. materialAlphaTest: materialAlphaTest,
  31906. materialAnisotropy: materialAnisotropy,
  31907. materialAnisotropyVector: materialAnisotropyVector,
  31908. materialAttenuationColor: materialAttenuationColor,
  31909. materialAttenuationDistance: materialAttenuationDistance,
  31910. materialClearcoat: materialClearcoat,
  31911. materialClearcoatNormal: materialClearcoatNormal,
  31912. materialClearcoatRoughness: materialClearcoatRoughness,
  31913. materialColor: materialColor,
  31914. materialDispersion: materialDispersion,
  31915. materialEmissive: materialEmissive,
  31916. materialEnvIntensity: materialEnvIntensity,
  31917. materialEnvRotation: materialEnvRotation,
  31918. materialIOR: materialIOR,
  31919. materialIridescence: materialIridescence,
  31920. materialIridescenceIOR: materialIridescenceIOR,
  31921. materialIridescenceThickness: materialIridescenceThickness,
  31922. materialLightMap: materialLightMap,
  31923. materialLineDashOffset: materialLineDashOffset,
  31924. materialLineDashSize: materialLineDashSize,
  31925. materialLineGapSize: materialLineGapSize,
  31926. materialLineScale: materialLineScale,
  31927. materialLineWidth: materialLineWidth,
  31928. materialMetalness: materialMetalness,
  31929. materialNormal: materialNormal,
  31930. materialOpacity: materialOpacity,
  31931. materialPointSize: materialPointSize,
  31932. materialReference: materialReference,
  31933. materialReflectivity: materialReflectivity,
  31934. materialRefractionRatio: materialRefractionRatio,
  31935. materialRotation: materialRotation,
  31936. materialRoughness: materialRoughness,
  31937. materialSheen: materialSheen,
  31938. materialSheenRoughness: materialSheenRoughness,
  31939. materialShininess: materialShininess,
  31940. materialSpecular: materialSpecular,
  31941. materialSpecularColor: materialSpecularColor,
  31942. materialSpecularIntensity: materialSpecularIntensity,
  31943. materialSpecularStrength: materialSpecularStrength,
  31944. materialThickness: materialThickness,
  31945. materialTransmission: materialTransmission,
  31946. max: max$1,
  31947. maxMipLevel: maxMipLevel,
  31948. mediumpModelViewMatrix: mediumpModelViewMatrix,
  31949. metalness: metalness,
  31950. min: min$1,
  31951. mix: mix,
  31952. mixElement: mixElement,
  31953. mod: mod,
  31954. modInt: modInt,
  31955. modelDirection: modelDirection,
  31956. modelNormalMatrix: modelNormalMatrix,
  31957. modelPosition: modelPosition,
  31958. modelRadius: modelRadius,
  31959. modelScale: modelScale,
  31960. modelViewMatrix: modelViewMatrix,
  31961. modelViewPosition: modelViewPosition,
  31962. modelViewProjection: modelViewProjection,
  31963. modelWorldMatrix: modelWorldMatrix,
  31964. modelWorldMatrixInverse: modelWorldMatrixInverse,
  31965. morphReference: morphReference,
  31966. mrt: mrt,
  31967. mul: mul,
  31968. mx_aastep: mx_aastep,
  31969. mx_add: mx_add,
  31970. mx_atan2: mx_atan2,
  31971. mx_cell_noise_float: mx_cell_noise_float,
  31972. mx_contrast: mx_contrast,
  31973. mx_divide: mx_divide,
  31974. mx_fractal_noise_float: mx_fractal_noise_float,
  31975. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  31976. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  31977. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  31978. mx_frame: mx_frame,
  31979. mx_heighttonormal: mx_heighttonormal,
  31980. mx_hsvtorgb: mx_hsvtorgb,
  31981. mx_ifequal: mx_ifequal,
  31982. mx_ifgreater: mx_ifgreater,
  31983. mx_ifgreatereq: mx_ifgreatereq,
  31984. mx_invert: mx_invert,
  31985. mx_modulo: mx_modulo,
  31986. mx_multiply: mx_multiply,
  31987. mx_noise_float: mx_noise_float,
  31988. mx_noise_vec3: mx_noise_vec3,
  31989. mx_noise_vec4: mx_noise_vec4,
  31990. mx_place2d: mx_place2d,
  31991. mx_power: mx_power,
  31992. mx_ramp4: mx_ramp4,
  31993. mx_ramplr: mx_ramplr,
  31994. mx_ramptb: mx_ramptb,
  31995. mx_rgbtohsv: mx_rgbtohsv,
  31996. mx_rotate2d: mx_rotate2d,
  31997. mx_rotate3d: mx_rotate3d,
  31998. mx_safepower: mx_safepower,
  31999. mx_separate: mx_separate,
  32000. mx_splitlr: mx_splitlr,
  32001. mx_splittb: mx_splittb,
  32002. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  32003. mx_subtract: mx_subtract,
  32004. mx_timer: mx_timer,
  32005. mx_transform_uv: mx_transform_uv,
  32006. mx_unifiednoise2d: mx_unifiednoise2d,
  32007. mx_unifiednoise3d: mx_unifiednoise3d,
  32008. mx_worley_noise_float: mx_worley_noise_float,
  32009. mx_worley_noise_vec2: mx_worley_noise_vec2,
  32010. mx_worley_noise_vec3: mx_worley_noise_vec3,
  32011. negate: negate,
  32012. neutralToneMapping: neutralToneMapping,
  32013. nodeArray: nodeArray,
  32014. nodeImmutable: nodeImmutable,
  32015. nodeObject: nodeObject,
  32016. nodeObjectIntent: nodeObjectIntent,
  32017. nodeObjects: nodeObjects,
  32018. nodeProxy: nodeProxy,
  32019. nodeProxyIntent: nodeProxyIntent,
  32020. normalFlat: normalFlat,
  32021. normalGeometry: normalGeometry,
  32022. normalLocal: normalLocal,
  32023. normalMap: normalMap,
  32024. normalView: normalView,
  32025. normalViewGeometry: normalViewGeometry,
  32026. normalWorld: normalWorld,
  32027. normalWorldGeometry: normalWorldGeometry,
  32028. normalize: normalize,
  32029. not: not,
  32030. notEqual: notEqual,
  32031. numWorkgroups: numWorkgroups,
  32032. objectDirection: objectDirection,
  32033. objectGroup: objectGroup,
  32034. objectPosition: objectPosition,
  32035. objectRadius: objectRadius,
  32036. objectScale: objectScale,
  32037. objectViewPosition: objectViewPosition,
  32038. objectWorldMatrix: objectWorldMatrix,
  32039. oneMinus: oneMinus,
  32040. or: or,
  32041. orthographicDepthToViewZ: orthographicDepthToViewZ,
  32042. oscSawtooth: oscSawtooth,
  32043. oscSine: oscSine,
  32044. oscSquare: oscSquare,
  32045. oscTriangle: oscTriangle,
  32046. output: output,
  32047. outputStruct: outputStruct,
  32048. overlay: overlay,
  32049. overloadingFn: overloadingFn,
  32050. parabola: parabola,
  32051. parallaxDirection: parallaxDirection,
  32052. parallaxUV: parallaxUV,
  32053. parameter: parameter,
  32054. pass: pass,
  32055. passTexture: passTexture,
  32056. pcurve: pcurve,
  32057. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  32058. pmremTexture: pmremTexture,
  32059. pointShadow: pointShadow,
  32060. pointUV: pointUV,
  32061. pointWidth: pointWidth,
  32062. positionGeometry: positionGeometry,
  32063. positionLocal: positionLocal,
  32064. positionPrevious: positionPrevious,
  32065. positionView: positionView,
  32066. positionViewDirection: positionViewDirection,
  32067. positionWorld: positionWorld,
  32068. positionWorldDirection: positionWorldDirection,
  32069. posterize: posterize,
  32070. pow: pow,
  32071. pow2: pow2,
  32072. pow3: pow3,
  32073. pow4: pow4,
  32074. premultiplyAlpha: premultiplyAlpha,
  32075. property: property,
  32076. quadBroadcast: quadBroadcast,
  32077. quadSwapDiagonal: quadSwapDiagonal,
  32078. quadSwapX: quadSwapX,
  32079. quadSwapY: quadSwapY,
  32080. radians: radians,
  32081. rand: rand,
  32082. range: range,
  32083. rangeFog: rangeFog,
  32084. rangeFogFactor: rangeFogFactor,
  32085. reciprocal: reciprocal,
  32086. reference: reference,
  32087. referenceBuffer: referenceBuffer,
  32088. reflect: reflect,
  32089. reflectVector: reflectVector,
  32090. reflectView: reflectView,
  32091. reflector: reflector,
  32092. refract: refract,
  32093. refractVector: refractVector,
  32094. refractView: refractView,
  32095. reinhardToneMapping: reinhardToneMapping,
  32096. remap: remap,
  32097. remapClamp: remapClamp,
  32098. renderGroup: renderGroup,
  32099. renderOutput: renderOutput,
  32100. rendererReference: rendererReference,
  32101. rotate: rotate,
  32102. rotateUV: rotateUV,
  32103. roughness: roughness,
  32104. round: round,
  32105. rtt: rtt,
  32106. sRGBTransferEOTF: sRGBTransferEOTF,
  32107. sRGBTransferOETF: sRGBTransferOETF,
  32108. sample: sample,
  32109. sampler: sampler,
  32110. samplerComparison: samplerComparison,
  32111. saturate: saturate,
  32112. saturation: saturation,
  32113. screen: screen,
  32114. screenCoordinate: screenCoordinate,
  32115. screenDPR: screenDPR,
  32116. screenSize: screenSize,
  32117. screenUV: screenUV,
  32118. scriptable: scriptable,
  32119. scriptableValue: scriptableValue,
  32120. select: select,
  32121. setCurrentStack: setCurrentStack,
  32122. setName: setName,
  32123. shaderStages: shaderStages,
  32124. shadow: shadow,
  32125. shadowPositionWorld: shadowPositionWorld,
  32126. shapeCircle: shapeCircle,
  32127. sharedUniformGroup: sharedUniformGroup,
  32128. sheen: sheen,
  32129. sheenRoughness: sheenRoughness,
  32130. shiftLeft: shiftLeft,
  32131. shiftRight: shiftRight,
  32132. shininess: shininess,
  32133. sign: sign,
  32134. sin: sin,
  32135. sinc: sinc,
  32136. skinning: skinning,
  32137. smoothstep: smoothstep,
  32138. smoothstepElement: smoothstepElement,
  32139. specularColor: specularColor,
  32140. specularF90: specularF90,
  32141. spherizeUV: spherizeUV,
  32142. split: split,
  32143. spritesheetUV: spritesheetUV,
  32144. sqrt: sqrt,
  32145. stack: stack,
  32146. step: step,
  32147. stepElement: stepElement,
  32148. storage: storage,
  32149. storageBarrier: storageBarrier,
  32150. storageObject: storageObject,
  32151. storageTexture: storageTexture,
  32152. string: string,
  32153. struct: struct,
  32154. sub: sub,
  32155. subBuild: subBuild,
  32156. subgroupAdd: subgroupAdd,
  32157. subgroupAll: subgroupAll,
  32158. subgroupAnd: subgroupAnd,
  32159. subgroupAny: subgroupAny,
  32160. subgroupBallot: subgroupBallot,
  32161. subgroupBroadcast: subgroupBroadcast,
  32162. subgroupBroadcastFirst: subgroupBroadcastFirst,
  32163. subgroupElect: subgroupElect,
  32164. subgroupExclusiveAdd: subgroupExclusiveAdd,
  32165. subgroupExclusiveMul: subgroupExclusiveMul,
  32166. subgroupInclusiveAdd: subgroupInclusiveAdd,
  32167. subgroupInclusiveMul: subgroupInclusiveMul,
  32168. subgroupIndex: subgroupIndex,
  32169. subgroupMax: subgroupMax,
  32170. subgroupMin: subgroupMin,
  32171. subgroupMul: subgroupMul,
  32172. subgroupOr: subgroupOr,
  32173. subgroupShuffle: subgroupShuffle,
  32174. subgroupShuffleDown: subgroupShuffleDown,
  32175. subgroupShuffleUp: subgroupShuffleUp,
  32176. subgroupShuffleXor: subgroupShuffleXor,
  32177. subgroupSize: subgroupSize,
  32178. subgroupXor: subgroupXor,
  32179. tan: tan,
  32180. tangentGeometry: tangentGeometry,
  32181. tangentLocal: tangentLocal,
  32182. tangentView: tangentView,
  32183. tangentWorld: tangentWorld,
  32184. texture: texture,
  32185. texture3D: texture3D,
  32186. textureBarrier: textureBarrier,
  32187. textureBicubic: textureBicubic,
  32188. textureBicubicLevel: textureBicubicLevel,
  32189. textureCubeUV: textureCubeUV,
  32190. textureLoad: textureLoad,
  32191. textureSize: textureSize,
  32192. textureStore: textureStore,
  32193. thickness: thickness,
  32194. time: time,
  32195. toneMapping: toneMapping,
  32196. toneMappingExposure: toneMappingExposure,
  32197. toonOutlinePass: toonOutlinePass,
  32198. transformDirection: transformDirection,
  32199. transformNormal: transformNormal,
  32200. transformNormalToView: transformNormalToView,
  32201. transformedClearcoatNormalView: transformedClearcoatNormalView,
  32202. transformedNormalView: transformedNormalView,
  32203. transformedNormalWorld: transformedNormalWorld,
  32204. transmission: transmission,
  32205. transpose: transpose,
  32206. triNoise3D: triNoise3D,
  32207. triplanarTexture: triplanarTexture,
  32208. triplanarTextures: triplanarTextures,
  32209. trunc: trunc,
  32210. uint: uint,
  32211. uintBitsToFloat: uintBitsToFloat,
  32212. uniform: uniform,
  32213. uniformArray: uniformArray,
  32214. uniformCubeTexture: uniformCubeTexture,
  32215. uniformFlow: uniformFlow,
  32216. uniformGroup: uniformGroup,
  32217. uniformTexture: uniformTexture,
  32218. unpremultiplyAlpha: unpremultiplyAlpha,
  32219. userData: userData,
  32220. uv: uv$1,
  32221. uvec2: uvec2,
  32222. uvec3: uvec3,
  32223. uvec4: uvec4,
  32224. varying: varying,
  32225. varyingProperty: varyingProperty,
  32226. vec2: vec2,
  32227. vec3: vec3,
  32228. vec4: vec4,
  32229. vectorComponents: vectorComponents,
  32230. velocity: velocity,
  32231. vertexColor: vertexColor,
  32232. vertexIndex: vertexIndex,
  32233. vertexStage: vertexStage,
  32234. vibrance: vibrance,
  32235. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  32236. viewZToOrthographicDepth: viewZToOrthographicDepth,
  32237. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  32238. viewport: viewport,
  32239. viewportCoordinate: viewportCoordinate,
  32240. viewportDepthTexture: viewportDepthTexture,
  32241. viewportLinearDepth: viewportLinearDepth,
  32242. viewportMipTexture: viewportMipTexture,
  32243. viewportResolution: viewportResolution,
  32244. viewportSafeUV: viewportSafeUV,
  32245. viewportSharedTexture: viewportSharedTexture,
  32246. viewportSize: viewportSize,
  32247. viewportTexture: viewportTexture,
  32248. viewportUV: viewportUV,
  32249. wgsl: wgsl,
  32250. wgslFn: wgslFn,
  32251. workgroupArray: workgroupArray,
  32252. workgroupBarrier: workgroupBarrier,
  32253. workgroupId: workgroupId,
  32254. workingToColorSpace: workingToColorSpace,
  32255. xor: xor
  32256. });
  32257. const _clearColor = /*@__PURE__*/ new Color4();
  32258. /**
  32259. * This renderer module manages the background.
  32260. *
  32261. * @private
  32262. * @augments DataMap
  32263. */
  32264. class Background extends DataMap {
  32265. /**
  32266. * Constructs a new background management component.
  32267. *
  32268. * @param {Renderer} renderer - The renderer.
  32269. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  32270. */
  32271. constructor( renderer, nodes ) {
  32272. super();
  32273. /**
  32274. * The renderer.
  32275. *
  32276. * @type {Renderer}
  32277. */
  32278. this.renderer = renderer;
  32279. /**
  32280. * Renderer component for managing nodes related logic.
  32281. *
  32282. * @type {Nodes}
  32283. */
  32284. this.nodes = nodes;
  32285. }
  32286. /**
  32287. * Updates the background for the given scene. Depending on how `Scene.background`
  32288. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  32289. * or add a mesh to the render list for rendering the background as a textured plane
  32290. * or skybox.
  32291. *
  32292. * @param {Scene} scene - The scene.
  32293. * @param {RenderList} renderList - The current render list.
  32294. * @param {RenderContext} renderContext - The current render context.
  32295. */
  32296. update( scene, renderList, renderContext ) {
  32297. const renderer = this.renderer;
  32298. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  32299. let forceClear = false;
  32300. if ( background === null ) {
  32301. // no background settings, use clear color configuration from the renderer
  32302. renderer._clearColor.getRGB( _clearColor );
  32303. _clearColor.a = renderer._clearColor.a;
  32304. } else if ( background.isColor === true ) {
  32305. // background is an opaque color
  32306. background.getRGB( _clearColor );
  32307. _clearColor.a = 1;
  32308. forceClear = true;
  32309. } else if ( background.isNode === true ) {
  32310. const sceneData = this.get( scene );
  32311. const backgroundNode = background;
  32312. _clearColor.copy( renderer._clearColor );
  32313. let backgroundMesh = sceneData.backgroundMesh;
  32314. if ( backgroundMesh === undefined ) {
  32315. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  32316. // @TODO: Add Texture2D support using node context
  32317. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  32318. getTextureLevel: () => backgroundBlurriness
  32319. } );
  32320. let viewProj = modelViewProjection;
  32321. viewProj = viewProj.setZ( viewProj.w );
  32322. const nodeMaterial = new NodeMaterial();
  32323. nodeMaterial.name = 'Background.material';
  32324. nodeMaterial.side = BackSide;
  32325. nodeMaterial.depthTest = false;
  32326. nodeMaterial.depthWrite = false;
  32327. nodeMaterial.allowOverride = false;
  32328. nodeMaterial.fog = false;
  32329. nodeMaterial.lights = false;
  32330. nodeMaterial.vertexNode = viewProj;
  32331. nodeMaterial.colorNode = backgroundMeshNode;
  32332. sceneData.backgroundMeshNode = backgroundMeshNode;
  32333. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  32334. backgroundMesh.frustumCulled = false;
  32335. backgroundMesh.name = 'Background.mesh';
  32336. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  32337. this.matrixWorld.copyPosition( camera.matrixWorld );
  32338. };
  32339. function onBackgroundDispose() {
  32340. background.removeEventListener( 'dispose', onBackgroundDispose );
  32341. backgroundMesh.material.dispose();
  32342. backgroundMesh.geometry.dispose();
  32343. }
  32344. background.addEventListener( 'dispose', onBackgroundDispose );
  32345. }
  32346. const backgroundCacheKey = backgroundNode.getCacheKey();
  32347. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  32348. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  32349. sceneData.backgroundMeshNode.needsUpdate = true;
  32350. backgroundMesh.material.needsUpdate = true;
  32351. sceneData.backgroundCacheKey = backgroundCacheKey;
  32352. }
  32353. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  32354. } else {
  32355. error( 'Renderer: Unsupported background configuration.', background );
  32356. }
  32357. //
  32358. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  32359. if ( environmentBlendMode === 'additive' ) {
  32360. _clearColor.set( 0, 0, 0, 1 );
  32361. } else if ( environmentBlendMode === 'alpha-blend' ) {
  32362. _clearColor.set( 0, 0, 0, 0 );
  32363. }
  32364. //
  32365. if ( renderer.autoClear === true || forceClear === true ) {
  32366. const clearColorValue = renderContext.clearColorValue;
  32367. clearColorValue.r = _clearColor.r;
  32368. clearColorValue.g = _clearColor.g;
  32369. clearColorValue.b = _clearColor.b;
  32370. clearColorValue.a = _clearColor.a;
  32371. // premultiply alpha
  32372. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  32373. clearColorValue.r *= clearColorValue.a;
  32374. clearColorValue.g *= clearColorValue.a;
  32375. clearColorValue.b *= clearColorValue.a;
  32376. }
  32377. //
  32378. renderContext.depthClearValue = renderer._clearDepth;
  32379. renderContext.stencilClearValue = renderer._clearStencil;
  32380. renderContext.clearColor = renderer.autoClearColor === true;
  32381. renderContext.clearDepth = renderer.autoClearDepth === true;
  32382. renderContext.clearStencil = renderer.autoClearStencil === true;
  32383. } else {
  32384. renderContext.clearColor = false;
  32385. renderContext.clearDepth = false;
  32386. renderContext.clearStencil = false;
  32387. }
  32388. }
  32389. }
  32390. let _id$6 = 0;
  32391. /**
  32392. * A bind group represents a collection of bindings and thus a collection
  32393. * or resources. Bind groups are assigned to pipelines to provide them
  32394. * with the required resources (like uniform buffers or textures).
  32395. *
  32396. * @private
  32397. */
  32398. class BindGroup {
  32399. /**
  32400. * Constructs a new bind group.
  32401. *
  32402. * @param {string} name - The bind group's name.
  32403. * @param {Array<Binding>} bindings - An array of bindings.
  32404. * @param {number} index - The group index.
  32405. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  32406. */
  32407. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  32408. /**
  32409. * The bind group's name.
  32410. *
  32411. * @type {string}
  32412. */
  32413. this.name = name;
  32414. /**
  32415. * An array of bindings.
  32416. *
  32417. * @type {Array<Binding>}
  32418. */
  32419. this.bindings = bindings;
  32420. /**
  32421. * The group index.
  32422. *
  32423. * @type {number}
  32424. */
  32425. this.index = index;
  32426. /**
  32427. * An array of reference bindings.
  32428. *
  32429. * @type {Array<Binding>}
  32430. */
  32431. this.bindingsReference = bindingsReference;
  32432. /**
  32433. * The group's ID.
  32434. *
  32435. * @type {number}
  32436. */
  32437. this.id = _id$6 ++;
  32438. }
  32439. }
  32440. /**
  32441. * This module represents the state of a node builder after it was
  32442. * used to build the nodes for a render object. The state holds the
  32443. * results of the build for further processing in the renderer.
  32444. *
  32445. * Render objects with identical cache keys share the same node builder state.
  32446. *
  32447. * @private
  32448. */
  32449. class NodeBuilderState {
  32450. /**
  32451. * Constructs a new node builder state.
  32452. *
  32453. * @param {string} vertexShader - The native vertex shader code.
  32454. * @param {string} fragmentShader - The native fragment shader code.
  32455. * @param {string} computeShader - The native compute shader code.
  32456. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  32457. * @param {Array<BindGroup>} bindings - An array of bind groups.
  32458. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  32459. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  32460. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  32461. * @param {NodeMaterialObserver} observer - A node material observer.
  32462. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  32463. */
  32464. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  32465. /**
  32466. * The native vertex shader code.
  32467. *
  32468. * @type {string}
  32469. */
  32470. this.vertexShader = vertexShader;
  32471. /**
  32472. * The native fragment shader code.
  32473. *
  32474. * @type {string}
  32475. */
  32476. this.fragmentShader = fragmentShader;
  32477. /**
  32478. * The native compute shader code.
  32479. *
  32480. * @type {string}
  32481. */
  32482. this.computeShader = computeShader;
  32483. /**
  32484. * An array with transform attribute objects.
  32485. * Only relevant when using compute shaders with WebGL 2.
  32486. *
  32487. * @type {Array<Object>}
  32488. */
  32489. this.transforms = transforms;
  32490. /**
  32491. * An array of node attributes representing
  32492. * the attributes of the shaders.
  32493. *
  32494. * @type {Array<NodeAttribute>}
  32495. */
  32496. this.nodeAttributes = nodeAttributes;
  32497. /**
  32498. * An array of bind groups representing the uniform or storage
  32499. * buffers, texture or samplers of the shader.
  32500. *
  32501. * @type {Array<BindGroup>}
  32502. */
  32503. this.bindings = bindings;
  32504. /**
  32505. * An array of nodes that implement their `update()` method.
  32506. *
  32507. * @type {Array<Node>}
  32508. */
  32509. this.updateNodes = updateNodes;
  32510. /**
  32511. * An array of nodes that implement their `updateBefore()` method.
  32512. *
  32513. * @type {Array<Node>}
  32514. */
  32515. this.updateBeforeNodes = updateBeforeNodes;
  32516. /**
  32517. * An array of nodes that implement their `updateAfter()` method.
  32518. *
  32519. * @type {Array<Node>}
  32520. */
  32521. this.updateAfterNodes = updateAfterNodes;
  32522. /**
  32523. * A node material observer.
  32524. *
  32525. * @type {NodeMaterialObserver}
  32526. */
  32527. this.observer = observer;
  32528. /**
  32529. * How often this state is used by render objects.
  32530. *
  32531. * @type {number}
  32532. */
  32533. this.usedTimes = 0;
  32534. }
  32535. /**
  32536. * This method is used to create a array of bind groups based
  32537. * on the existing bind groups of this state. Shared groups are
  32538. * not cloned.
  32539. *
  32540. * @return {Array<BindGroup>} A array of bind groups.
  32541. */
  32542. createBindings() {
  32543. const bindings = [];
  32544. for ( const instanceGroup of this.bindings ) {
  32545. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  32546. if ( shared !== true ) {
  32547. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  32548. bindings.push( bindingsGroup );
  32549. for ( const instanceBinding of instanceGroup.bindings ) {
  32550. bindingsGroup.bindings.push( instanceBinding.clone() );
  32551. }
  32552. } else {
  32553. bindings.push( instanceGroup );
  32554. }
  32555. }
  32556. return bindings;
  32557. }
  32558. }
  32559. /**
  32560. * {@link NodeBuilder} is going to create instances of this class during the build process
  32561. * of nodes. They represent the final shader attributes that are going to be generated
  32562. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  32563. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  32564. */
  32565. class NodeAttribute {
  32566. /**
  32567. * Constructs a new node attribute.
  32568. *
  32569. * @param {string} name - The name of the attribute.
  32570. * @param {string} type - The type of the attribute.
  32571. * @param {?Node} node - An optional reference to the node.
  32572. */
  32573. constructor( name, type, node = null ) {
  32574. /**
  32575. * This flag can be used for type testing.
  32576. *
  32577. * @type {boolean}
  32578. * @readonly
  32579. * @default true
  32580. */
  32581. this.isNodeAttribute = true;
  32582. /**
  32583. * The name of the attribute.
  32584. *
  32585. * @type {string}
  32586. */
  32587. this.name = name;
  32588. /**
  32589. * The type of the attribute.
  32590. *
  32591. * @type {string}
  32592. */
  32593. this.type = type;
  32594. /**
  32595. * An optional reference to the node.
  32596. *
  32597. * @type {?Node}
  32598. * @default null
  32599. */
  32600. this.node = node;
  32601. }
  32602. }
  32603. /**
  32604. * {@link NodeBuilder} is going to create instances of this class during the build process
  32605. * of nodes. They represent the final shader uniforms that are going to be generated
  32606. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  32607. * for this purpose.
  32608. */
  32609. class NodeUniform {
  32610. /**
  32611. * Constructs a new node uniform.
  32612. *
  32613. * @param {string} name - The name of the uniform.
  32614. * @param {string} type - The type of the uniform.
  32615. * @param {UniformNode} node - An reference to the node.
  32616. */
  32617. constructor( name, type, node ) {
  32618. /**
  32619. * This flag can be used for type testing.
  32620. *
  32621. * @type {boolean}
  32622. * @readonly
  32623. * @default true
  32624. */
  32625. this.isNodeUniform = true;
  32626. /**
  32627. * The name of the uniform.
  32628. *
  32629. * @type {string}
  32630. */
  32631. this.name = name;
  32632. /**
  32633. * The type of the uniform.
  32634. *
  32635. * @type {string}
  32636. */
  32637. this.type = type;
  32638. /**
  32639. * An reference to the node.
  32640. *
  32641. * @type {UniformNode}
  32642. */
  32643. this.node = node;
  32644. }
  32645. /**
  32646. * The value of the uniform node.
  32647. *
  32648. * @type {any}
  32649. */
  32650. get value() {
  32651. return this.node.value;
  32652. }
  32653. set value( val ) {
  32654. this.node.value = val;
  32655. }
  32656. /**
  32657. * The id of the uniform node.
  32658. *
  32659. * @type {number}
  32660. */
  32661. get id() {
  32662. return this.node.id;
  32663. }
  32664. /**
  32665. * The uniform node's group.
  32666. *
  32667. * @type {UniformGroupNode}
  32668. */
  32669. get groupNode() {
  32670. return this.node.groupNode;
  32671. }
  32672. }
  32673. /**
  32674. * {@link NodeBuilder} is going to create instances of this class during the build process
  32675. * of nodes. They represent the final shader variables that are going to be generated
  32676. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  32677. * this purpose.
  32678. */
  32679. class NodeVar {
  32680. /**
  32681. * Constructs a new node variable.
  32682. *
  32683. * @param {string} name - The name of the variable.
  32684. * @param {string} type - The type of the variable.
  32685. * @param {boolean} [readOnly=false] - The read-only flag.
  32686. * @param {?number} [count=null] - The size.
  32687. */
  32688. constructor( name, type, readOnly = false, count = null ) {
  32689. /**
  32690. * This flag can be used for type testing.
  32691. *
  32692. * @type {boolean}
  32693. * @readonly
  32694. * @default true
  32695. */
  32696. this.isNodeVar = true;
  32697. /**
  32698. * The name of the variable.
  32699. *
  32700. * @type {string}
  32701. */
  32702. this.name = name;
  32703. /**
  32704. * The type of the variable.
  32705. *
  32706. * @type {string}
  32707. */
  32708. this.type = type;
  32709. /**
  32710. * The read-only flag.
  32711. *
  32712. * @type {boolean}
  32713. */
  32714. this.readOnly = readOnly;
  32715. /**
  32716. * The size.
  32717. *
  32718. * @type {?number}
  32719. */
  32720. this.count = count;
  32721. }
  32722. }
  32723. /**
  32724. * {@link NodeBuilder} is going to create instances of this class during the build process
  32725. * of nodes. They represent the final shader varyings that are going to be generated
  32726. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  32727. * this purpose.
  32728. *
  32729. * @augments NodeVar
  32730. */
  32731. class NodeVarying extends NodeVar {
  32732. /**
  32733. * Constructs a new node varying.
  32734. *
  32735. * @param {string} name - The name of the varying.
  32736. * @param {string} type - The type of the varying.
  32737. * @param {?string} interpolationType - The interpolation type of the varying.
  32738. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32739. */
  32740. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  32741. super( name, type );
  32742. /**
  32743. * Whether this varying requires interpolation or not. This property can be used
  32744. * to check if the varying can be optimized for a variable.
  32745. *
  32746. * @type {boolean}
  32747. * @default false
  32748. */
  32749. this.needsInterpolation = false;
  32750. /**
  32751. * This flag can be used for type testing.
  32752. *
  32753. * @type {boolean}
  32754. * @readonly
  32755. * @default true
  32756. */
  32757. this.isNodeVarying = true;
  32758. /**
  32759. * The interpolation type of the varying data.
  32760. *
  32761. * @type {?string}
  32762. * @default null
  32763. */
  32764. this.interpolationType = interpolationType;
  32765. /**
  32766. * The interpolation sampling type of varying data.
  32767. *
  32768. * @type {?string}
  32769. * @default null
  32770. */
  32771. this.interpolationSampling = interpolationSampling;
  32772. }
  32773. }
  32774. /**
  32775. * {@link NodeBuilder} is going to create instances of this class during the build process
  32776. * of nodes. They represent user-defined, native shader code portions that are going to be
  32777. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  32778. * for this purpose.
  32779. */
  32780. class NodeCode {
  32781. /**
  32782. * Constructs a new code node.
  32783. *
  32784. * @param {string} name - The name of the code.
  32785. * @param {string} type - The node type.
  32786. * @param {string} [code=''] - The native shader code.
  32787. */
  32788. constructor( name, type, code = '' ) {
  32789. /**
  32790. * The name of the code.
  32791. *
  32792. * @type {string}
  32793. */
  32794. this.name = name;
  32795. /**
  32796. * The node type.
  32797. *
  32798. * @type {string}
  32799. */
  32800. this.type = type;
  32801. /**
  32802. * The native shader code.
  32803. *
  32804. * @type {string}
  32805. * @default ''
  32806. */
  32807. this.code = code;
  32808. Object.defineProperty( this, 'isNodeCode', { value: true } );
  32809. }
  32810. }
  32811. let _id$5 = 0;
  32812. /**
  32813. * This utility class is used in {@link NodeBuilder} as an internal
  32814. * cache data structure for node data.
  32815. */
  32816. class NodeCache {
  32817. /**
  32818. * Constructs a new node cache.
  32819. *
  32820. * @param {?NodeCache} parent - A reference to a parent cache.
  32821. */
  32822. constructor( parent = null ) {
  32823. /**
  32824. * The id of the cache.
  32825. *
  32826. * @type {number}
  32827. * @readonly
  32828. */
  32829. this.id = _id$5 ++;
  32830. /**
  32831. * A weak map for managing node data.
  32832. *
  32833. * @type {WeakMap<Node, Object>}
  32834. */
  32835. this.nodesData = new WeakMap();
  32836. /**
  32837. * Reference to a parent node cache.
  32838. *
  32839. * @type {?NodeCache}
  32840. * @default null
  32841. */
  32842. this.parent = parent;
  32843. }
  32844. /**
  32845. * Returns the data for the given node.
  32846. *
  32847. * @param {Node} node - The node.
  32848. * @return {?Object} The data for the node.
  32849. */
  32850. getData( node ) {
  32851. let data = this.nodesData.get( node );
  32852. if ( data === undefined && this.parent !== null ) {
  32853. data = this.parent.getData( node );
  32854. }
  32855. return data;
  32856. }
  32857. /**
  32858. * Sets the data for a given node.
  32859. *
  32860. * @param {Node} node - The node.
  32861. * @param {Object} data - The data that should be cached.
  32862. */
  32863. setData( node, data ) {
  32864. this.nodesData.set( node, data );
  32865. }
  32866. }
  32867. class StructType {
  32868. constructor( name, members ) {
  32869. this.name = name;
  32870. this.members = members;
  32871. this.output = false;
  32872. }
  32873. }
  32874. /**
  32875. * Abstract base class for uniforms.
  32876. *
  32877. * @abstract
  32878. * @private
  32879. */
  32880. class Uniform {
  32881. /**
  32882. * Constructs a new uniform.
  32883. *
  32884. * @param {string} name - The uniform's name.
  32885. * @param {any} value - The uniform's value.
  32886. */
  32887. constructor( name, value ) {
  32888. /**
  32889. * The uniform's name.
  32890. *
  32891. * @type {string}
  32892. */
  32893. this.name = name;
  32894. /**
  32895. * The uniform's value.
  32896. *
  32897. * @type {any}
  32898. */
  32899. this.value = value;
  32900. /**
  32901. * Used to build the uniform buffer according to the STD140 layout.
  32902. * Derived uniforms will set this property to a data type specific
  32903. * value.
  32904. *
  32905. * @type {number}
  32906. */
  32907. this.boundary = 0;
  32908. /**
  32909. * The item size. Derived uniforms will set this property to a data
  32910. * type specific value.
  32911. *
  32912. * @type {number}
  32913. */
  32914. this.itemSize = 0;
  32915. /**
  32916. * This property is set by {@link UniformsGroup} and marks
  32917. * the start position in the uniform buffer.
  32918. *
  32919. * @type {number}
  32920. */
  32921. this.offset = 0;
  32922. }
  32923. /**
  32924. * Sets the uniform's value.
  32925. *
  32926. * @param {any} value - The value to set.
  32927. */
  32928. setValue( value ) {
  32929. this.value = value;
  32930. }
  32931. /**
  32932. * Returns the uniform's value.
  32933. *
  32934. * @return {any} The value.
  32935. */
  32936. getValue() {
  32937. return this.value;
  32938. }
  32939. }
  32940. /**
  32941. * Represents a Number uniform.
  32942. *
  32943. * @private
  32944. * @augments Uniform
  32945. */
  32946. class NumberUniform extends Uniform {
  32947. /**
  32948. * Constructs a new Number uniform.
  32949. *
  32950. * @param {string} name - The uniform's name.
  32951. * @param {number} value - The uniform's value.
  32952. */
  32953. constructor( name, value = 0 ) {
  32954. super( name, value );
  32955. /**
  32956. * This flag can be used for type testing.
  32957. *
  32958. * @type {boolean}
  32959. * @readonly
  32960. * @default true
  32961. */
  32962. this.isNumberUniform = true;
  32963. this.boundary = 4;
  32964. this.itemSize = 1;
  32965. }
  32966. }
  32967. /**
  32968. * Represents a Vector2 uniform.
  32969. *
  32970. * @private
  32971. * @augments Uniform
  32972. */
  32973. class Vector2Uniform extends Uniform {
  32974. /**
  32975. * Constructs a new Number uniform.
  32976. *
  32977. * @param {string} name - The uniform's name.
  32978. * @param {Vector2} value - The uniform's value.
  32979. */
  32980. constructor( name, value = new Vector2() ) {
  32981. super( name, value );
  32982. /**
  32983. * This flag can be used for type testing.
  32984. *
  32985. * @type {boolean}
  32986. * @readonly
  32987. * @default true
  32988. */
  32989. this.isVector2Uniform = true;
  32990. this.boundary = 8;
  32991. this.itemSize = 2;
  32992. }
  32993. }
  32994. /**
  32995. * Represents a Vector3 uniform.
  32996. *
  32997. * @private
  32998. * @augments Uniform
  32999. */
  33000. class Vector3Uniform extends Uniform {
  33001. /**
  33002. * Constructs a new Number uniform.
  33003. *
  33004. * @param {string} name - The uniform's name.
  33005. * @param {Vector3} value - The uniform's value.
  33006. */
  33007. constructor( name, value = new Vector3() ) {
  33008. super( name, value );
  33009. /**
  33010. * This flag can be used for type testing.
  33011. *
  33012. * @type {boolean}
  33013. * @readonly
  33014. * @default true
  33015. */
  33016. this.isVector3Uniform = true;
  33017. this.boundary = 16;
  33018. this.itemSize = 3;
  33019. }
  33020. }
  33021. /**
  33022. * Represents a Vector4 uniform.
  33023. *
  33024. * @private
  33025. * @augments Uniform
  33026. */
  33027. class Vector4Uniform extends Uniform {
  33028. /**
  33029. * Constructs a new Number uniform.
  33030. *
  33031. * @param {string} name - The uniform's name.
  33032. * @param {Vector4} value - The uniform's value.
  33033. */
  33034. constructor( name, value = new Vector4() ) {
  33035. super( name, value );
  33036. /**
  33037. * This flag can be used for type testing.
  33038. *
  33039. * @type {boolean}
  33040. * @readonly
  33041. * @default true
  33042. */
  33043. this.isVector4Uniform = true;
  33044. this.boundary = 16;
  33045. this.itemSize = 4;
  33046. }
  33047. }
  33048. /**
  33049. * Represents a Color uniform.
  33050. *
  33051. * @private
  33052. * @augments Uniform
  33053. */
  33054. class ColorUniform extends Uniform {
  33055. /**
  33056. * Constructs a new Number uniform.
  33057. *
  33058. * @param {string} name - The uniform's name.
  33059. * @param {Color} value - The uniform's value.
  33060. */
  33061. constructor( name, value = new Color() ) {
  33062. super( name, value );
  33063. /**
  33064. * This flag can be used for type testing.
  33065. *
  33066. * @type {boolean}
  33067. * @readonly
  33068. * @default true
  33069. */
  33070. this.isColorUniform = true;
  33071. this.boundary = 16;
  33072. this.itemSize = 3;
  33073. }
  33074. }
  33075. /**
  33076. * Represents a Matrix2 uniform.
  33077. *
  33078. * @private
  33079. * @augments Uniform
  33080. */
  33081. class Matrix2Uniform extends Uniform {
  33082. /**
  33083. * Constructs a new Number uniform.
  33084. *
  33085. * @param {string} name - The uniform's name.
  33086. * @param {Matrix2} value - The uniform's value.
  33087. */
  33088. constructor( name, value = new Matrix2() ) {
  33089. super( name, value );
  33090. /**
  33091. * This flag can be used for type testing.
  33092. *
  33093. * @type {boolean}
  33094. * @readonly
  33095. * @default true
  33096. */
  33097. this.isMatrix2Uniform = true;
  33098. this.boundary = 8;
  33099. this.itemSize = 4;
  33100. }
  33101. }
  33102. /**
  33103. * Represents a Matrix3 uniform.
  33104. *
  33105. * @private
  33106. * @augments Uniform
  33107. */
  33108. class Matrix3Uniform extends Uniform {
  33109. /**
  33110. * Constructs a new Number uniform.
  33111. *
  33112. * @param {string} name - The uniform's name.
  33113. * @param {Matrix3} value - The uniform's value.
  33114. */
  33115. constructor( name, value = new Matrix3() ) {
  33116. super( name, value );
  33117. /**
  33118. * This flag can be used for type testing.
  33119. *
  33120. * @type {boolean}
  33121. * @readonly
  33122. * @default true
  33123. */
  33124. this.isMatrix3Uniform = true;
  33125. this.boundary = 48;
  33126. this.itemSize = 12;
  33127. }
  33128. }
  33129. /**
  33130. * Represents a Matrix4 uniform.
  33131. *
  33132. * @private
  33133. * @augments Uniform
  33134. */
  33135. class Matrix4Uniform extends Uniform {
  33136. /**
  33137. * Constructs a new Number uniform.
  33138. *
  33139. * @param {string} name - The uniform's name.
  33140. * @param {Matrix4} value - The uniform's value.
  33141. */
  33142. constructor( name, value = new Matrix4() ) {
  33143. super( name, value );
  33144. /**
  33145. * This flag can be used for type testing.
  33146. *
  33147. * @type {boolean}
  33148. * @readonly
  33149. * @default true
  33150. */
  33151. this.isMatrix4Uniform = true;
  33152. this.boundary = 64;
  33153. this.itemSize = 16;
  33154. }
  33155. }
  33156. /**
  33157. * A special form of Number uniform binding type.
  33158. * It's value is managed by a node object.
  33159. *
  33160. * @private
  33161. * @augments NumberUniform
  33162. */
  33163. class NumberNodeUniform extends NumberUniform {
  33164. /**
  33165. * Constructs a new node-based Number uniform.
  33166. *
  33167. * @param {NodeUniform} nodeUniform - The node uniform.
  33168. */
  33169. constructor( nodeUniform ) {
  33170. super( nodeUniform.name, nodeUniform.value );
  33171. /**
  33172. * The node uniform.
  33173. *
  33174. * @type {NodeUniform}
  33175. */
  33176. this.nodeUniform = nodeUniform;
  33177. }
  33178. /**
  33179. * Overwritten to return the value of the node uniform.
  33180. *
  33181. * @return {number} The value.
  33182. */
  33183. getValue() {
  33184. return this.nodeUniform.value;
  33185. }
  33186. /**
  33187. * Returns the node uniform data type.
  33188. *
  33189. * @return {string} The data type.
  33190. */
  33191. getType() {
  33192. return this.nodeUniform.type;
  33193. }
  33194. }
  33195. /**
  33196. * A special form of Vector2 uniform binding type.
  33197. * It's value is managed by a node object.
  33198. *
  33199. * @private
  33200. * @augments Vector2Uniform
  33201. */
  33202. class Vector2NodeUniform extends Vector2Uniform {
  33203. /**
  33204. * Constructs a new node-based Vector2 uniform.
  33205. *
  33206. * @param {NodeUniform} nodeUniform - The node uniform.
  33207. */
  33208. constructor( nodeUniform ) {
  33209. super( nodeUniform.name, nodeUniform.value );
  33210. /**
  33211. * The node uniform.
  33212. *
  33213. * @type {NodeUniform}
  33214. */
  33215. this.nodeUniform = nodeUniform;
  33216. }
  33217. /**
  33218. * Overwritten to return the value of the node uniform.
  33219. *
  33220. * @return {Vector2} The value.
  33221. */
  33222. getValue() {
  33223. return this.nodeUniform.value;
  33224. }
  33225. /**
  33226. * Returns the node uniform data type.
  33227. *
  33228. * @return {string} The data type.
  33229. */
  33230. getType() {
  33231. return this.nodeUniform.type;
  33232. }
  33233. }
  33234. /**
  33235. * A special form of Vector3 uniform binding type.
  33236. * It's value is managed by a node object.
  33237. *
  33238. * @private
  33239. * @augments Vector3Uniform
  33240. */
  33241. class Vector3NodeUniform extends Vector3Uniform {
  33242. /**
  33243. * Constructs a new node-based Vector3 uniform.
  33244. *
  33245. * @param {NodeUniform} nodeUniform - The node uniform.
  33246. */
  33247. constructor( nodeUniform ) {
  33248. super( nodeUniform.name, nodeUniform.value );
  33249. /**
  33250. * The node uniform.
  33251. *
  33252. * @type {NodeUniform}
  33253. */
  33254. this.nodeUniform = nodeUniform;
  33255. }
  33256. /**
  33257. * Overwritten to return the value of the node uniform.
  33258. *
  33259. * @return {Vector3} The value.
  33260. */
  33261. getValue() {
  33262. return this.nodeUniform.value;
  33263. }
  33264. /**
  33265. * Returns the node uniform data type.
  33266. *
  33267. * @return {string} The data type.
  33268. */
  33269. getType() {
  33270. return this.nodeUniform.type;
  33271. }
  33272. }
  33273. /**
  33274. * A special form of Vector4 uniform binding type.
  33275. * It's value is managed by a node object.
  33276. *
  33277. * @private
  33278. * @augments Vector4Uniform
  33279. */
  33280. class Vector4NodeUniform extends Vector4Uniform {
  33281. /**
  33282. * Constructs a new node-based Vector4 uniform.
  33283. *
  33284. * @param {NodeUniform} nodeUniform - The node uniform.
  33285. */
  33286. constructor( nodeUniform ) {
  33287. super( nodeUniform.name, nodeUniform.value );
  33288. /**
  33289. * The node uniform.
  33290. *
  33291. * @type {NodeUniform}
  33292. */
  33293. this.nodeUniform = nodeUniform;
  33294. }
  33295. /**
  33296. * Overwritten to return the value of the node uniform.
  33297. *
  33298. * @return {Vector4} The value.
  33299. */
  33300. getValue() {
  33301. return this.nodeUniform.value;
  33302. }
  33303. /**
  33304. * Returns the node uniform data type.
  33305. *
  33306. * @return {string} The data type.
  33307. */
  33308. getType() {
  33309. return this.nodeUniform.type;
  33310. }
  33311. }
  33312. /**
  33313. * A special form of Color uniform binding type.
  33314. * It's value is managed by a node object.
  33315. *
  33316. * @private
  33317. * @augments ColorUniform
  33318. */
  33319. class ColorNodeUniform extends ColorUniform {
  33320. /**
  33321. * Constructs a new node-based Color uniform.
  33322. *
  33323. * @param {NodeUniform} nodeUniform - The node uniform.
  33324. */
  33325. constructor( nodeUniform ) {
  33326. super( nodeUniform.name, nodeUniform.value );
  33327. /**
  33328. * The node uniform.
  33329. *
  33330. * @type {NodeUniform}
  33331. */
  33332. this.nodeUniform = nodeUniform;
  33333. }
  33334. /**
  33335. * Overwritten to return the value of the node uniform.
  33336. *
  33337. * @return {Color} The value.
  33338. */
  33339. getValue() {
  33340. return this.nodeUniform.value;
  33341. }
  33342. /**
  33343. * Returns the node uniform data type.
  33344. *
  33345. * @return {string} The data type.
  33346. */
  33347. getType() {
  33348. return this.nodeUniform.type;
  33349. }
  33350. }
  33351. /**
  33352. * A special form of Matrix2 uniform binding type.
  33353. * It's value is managed by a node object.
  33354. *
  33355. * @private
  33356. * @augments Matrix2Uniform
  33357. */
  33358. class Matrix2NodeUniform extends Matrix2Uniform {
  33359. /**
  33360. * Constructs a new node-based Matrix2 uniform.
  33361. *
  33362. * @param {NodeUniform} nodeUniform - The node uniform.
  33363. */
  33364. constructor( nodeUniform ) {
  33365. super( nodeUniform.name, nodeUniform.value );
  33366. /**
  33367. * The node uniform.
  33368. *
  33369. * @type {NodeUniform}
  33370. */
  33371. this.nodeUniform = nodeUniform;
  33372. }
  33373. /**
  33374. * Overwritten to return the value of the node uniform.
  33375. *
  33376. * @return {Matrix2} The value.
  33377. */
  33378. getValue() {
  33379. return this.nodeUniform.value;
  33380. }
  33381. /**
  33382. * Returns the node uniform data type.
  33383. *
  33384. * @return {string} The data type.
  33385. */
  33386. getType() {
  33387. return this.nodeUniform.type;
  33388. }
  33389. }
  33390. /**
  33391. * A special form of Matrix3 uniform binding type.
  33392. * It's value is managed by a node object.
  33393. *
  33394. * @private
  33395. * @augments Matrix3Uniform
  33396. */
  33397. class Matrix3NodeUniform extends Matrix3Uniform {
  33398. /**
  33399. * Constructs a new node-based Matrix3 uniform.
  33400. *
  33401. * @param {NodeUniform} nodeUniform - The node uniform.
  33402. */
  33403. constructor( nodeUniform ) {
  33404. super( nodeUniform.name, nodeUniform.value );
  33405. /**
  33406. * The node uniform.
  33407. *
  33408. * @type {NodeUniform}
  33409. */
  33410. this.nodeUniform = nodeUniform;
  33411. }
  33412. /**
  33413. * Overwritten to return the value of the node uniform.
  33414. *
  33415. * @return {Matrix3} The value.
  33416. */
  33417. getValue() {
  33418. return this.nodeUniform.value;
  33419. }
  33420. /**
  33421. * Returns the node uniform data type.
  33422. *
  33423. * @return {string} The data type.
  33424. */
  33425. getType() {
  33426. return this.nodeUniform.type;
  33427. }
  33428. }
  33429. /**
  33430. * A special form of Matrix4 uniform binding type.
  33431. * It's value is managed by a node object.
  33432. *
  33433. * @private
  33434. * @augments Matrix4Uniform
  33435. */
  33436. class Matrix4NodeUniform extends Matrix4Uniform {
  33437. /**
  33438. * Constructs a new node-based Matrix4 uniform.
  33439. *
  33440. * @param {NodeUniform} nodeUniform - The node uniform.
  33441. */
  33442. constructor( nodeUniform ) {
  33443. super( nodeUniform.name, nodeUniform.value );
  33444. /**
  33445. * The node uniform.
  33446. *
  33447. * @type {NodeUniform}
  33448. */
  33449. this.nodeUniform = nodeUniform;
  33450. }
  33451. /**
  33452. * Overwritten to return the value of the node uniform.
  33453. *
  33454. * @return {Matrix4} The value.
  33455. */
  33456. getValue() {
  33457. return this.nodeUniform.value;
  33458. }
  33459. /**
  33460. * Returns the node uniform data type.
  33461. *
  33462. * @return {string} The data type.
  33463. */
  33464. getType() {
  33465. return this.nodeUniform.type;
  33466. }
  33467. }
  33468. const rendererCache = new WeakMap();
  33469. const typeFromArray = new Map( [
  33470. [ Int8Array, 'int' ],
  33471. [ Int16Array, 'int' ],
  33472. [ Int32Array, 'int' ],
  33473. [ Uint8Array, 'uint' ],
  33474. [ Uint16Array, 'uint' ],
  33475. [ Uint32Array, 'uint' ],
  33476. [ Float32Array, 'float' ]
  33477. ] );
  33478. const toFloat = ( value ) => {
  33479. if ( /e/g.test( value ) ) {
  33480. return String( value ).replace( /\+/g, '' );
  33481. } else {
  33482. value = Number( value );
  33483. return value + ( value % 1 ? '' : '.0' );
  33484. }
  33485. };
  33486. /**
  33487. * Base class for builders which generate a shader program based
  33488. * on a 3D object and its node material definition.
  33489. */
  33490. class NodeBuilder {
  33491. /**
  33492. * Constructs a new node builder.
  33493. *
  33494. * @param {Object3D} object - The 3D object.
  33495. * @param {Renderer} renderer - The current renderer.
  33496. * @param {NodeParser} parser - A reference to a node parser.
  33497. */
  33498. constructor( object, renderer, parser ) {
  33499. /**
  33500. * The 3D object.
  33501. *
  33502. * @type {Object3D}
  33503. */
  33504. this.object = object;
  33505. /**
  33506. * The material of the 3D object.
  33507. *
  33508. * @type {?Material}
  33509. */
  33510. this.material = ( object && object.material ) || null;
  33511. /**
  33512. * The geometry of the 3D object.
  33513. *
  33514. * @type {?BufferGeometry}
  33515. */
  33516. this.geometry = ( object && object.geometry ) || null;
  33517. /**
  33518. * The current renderer.
  33519. *
  33520. * @type {Renderer}
  33521. */
  33522. this.renderer = renderer;
  33523. /**
  33524. * A reference to a node parser.
  33525. *
  33526. * @type {NodeParser}
  33527. */
  33528. this.parser = parser;
  33529. /**
  33530. * The scene the 3D object belongs to.
  33531. *
  33532. * @type {?Scene}
  33533. * @default null
  33534. */
  33535. this.scene = null;
  33536. /**
  33537. * The camera the 3D object is rendered with.
  33538. *
  33539. * @type {?Camera}
  33540. * @default null
  33541. */
  33542. this.camera = null;
  33543. /**
  33544. * A list of all nodes the builder is processing
  33545. * for this 3D object.
  33546. *
  33547. * @type {Array<Node>}
  33548. */
  33549. this.nodes = [];
  33550. /**
  33551. * A list of all sequential nodes.
  33552. *
  33553. * @type {Array<Node>}
  33554. */
  33555. this.sequentialNodes = [];
  33556. /**
  33557. * A list of all nodes which {@link Node#update} method should be executed.
  33558. *
  33559. * @type {Array<Node>}
  33560. */
  33561. this.updateNodes = [];
  33562. /**
  33563. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  33564. *
  33565. * @type {Array<Node>}
  33566. */
  33567. this.updateBeforeNodes = [];
  33568. /**
  33569. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  33570. *
  33571. * @type {Array<Node>}
  33572. */
  33573. this.updateAfterNodes = [];
  33574. /**
  33575. * A dictionary that assigns each node to a unique hash.
  33576. *
  33577. * @type {Object<number,Node>}
  33578. */
  33579. this.hashNodes = {};
  33580. /**
  33581. * A reference to a node material observer.
  33582. *
  33583. * @type {?NodeMaterialObserver}
  33584. * @default null
  33585. */
  33586. this.observer = null;
  33587. /**
  33588. * A reference to the current lights node.
  33589. *
  33590. * @type {?LightsNode}
  33591. * @default null
  33592. */
  33593. this.lightsNode = null;
  33594. /**
  33595. * A reference to the current environment node.
  33596. *
  33597. * @type {?Node}
  33598. * @default null
  33599. */
  33600. this.environmentNode = null;
  33601. /**
  33602. * A reference to the current fog node.
  33603. *
  33604. * @type {?Node}
  33605. * @default null
  33606. */
  33607. this.fogNode = null;
  33608. /**
  33609. * The current clipping context.
  33610. *
  33611. * @type {?ClippingContext}
  33612. */
  33613. this.clippingContext = null;
  33614. /**
  33615. * The generated vertex shader.
  33616. *
  33617. * @type {?string}
  33618. */
  33619. this.vertexShader = null;
  33620. /**
  33621. * The generated fragment shader.
  33622. *
  33623. * @type {?string}
  33624. */
  33625. this.fragmentShader = null;
  33626. /**
  33627. * The generated compute shader.
  33628. *
  33629. * @type {?string}
  33630. */
  33631. this.computeShader = null;
  33632. /**
  33633. * Nodes used in the primary flow of code generation.
  33634. *
  33635. * @type {Object<string,Array<Node>>}
  33636. */
  33637. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  33638. /**
  33639. * Nodes code from `.flowNodes`.
  33640. *
  33641. * @type {Object<string,string>}
  33642. */
  33643. this.flowCode = { vertex: '', fragment: '', compute: '' };
  33644. /**
  33645. * This dictionary holds the node uniforms of the builder.
  33646. * The uniforms are maintained in an array for each shader stage.
  33647. *
  33648. * @type {Object}
  33649. */
  33650. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  33651. /**
  33652. * This dictionary holds the output structs of the builder.
  33653. * The structs are maintained in an array for each shader stage.
  33654. *
  33655. * @type {Object}
  33656. */
  33657. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  33658. /**
  33659. * This dictionary holds the types of the builder.
  33660. *
  33661. * @type {Object}
  33662. */
  33663. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  33664. /**
  33665. * This dictionary holds the bindings for each shader stage.
  33666. *
  33667. * @type {Object}
  33668. */
  33669. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  33670. /**
  33671. * This dictionary maintains the binding indices per bind group.
  33672. *
  33673. * @type {Object}
  33674. */
  33675. this.bindingsIndexes = {};
  33676. /**
  33677. * Reference to the array of bind groups.
  33678. *
  33679. * @type {?Array<BindGroup>}
  33680. */
  33681. this.bindGroups = null;
  33682. /**
  33683. * This array holds the node attributes of this builder
  33684. * created via {@link AttributeNode}.
  33685. *
  33686. * @type {Array<NodeAttribute>}
  33687. */
  33688. this.attributes = [];
  33689. /**
  33690. * This array holds the node attributes of this builder
  33691. * created via {@link BufferAttributeNode}.
  33692. *
  33693. * @type {Array<NodeAttribute>}
  33694. */
  33695. this.bufferAttributes = [];
  33696. /**
  33697. * This array holds the node varyings of this builder.
  33698. *
  33699. * @type {Array<NodeVarying>}
  33700. */
  33701. this.varyings = [];
  33702. /**
  33703. * This dictionary holds the (native) node codes of this builder.
  33704. * The codes are maintained in an array for each shader stage.
  33705. *
  33706. * @type {Object<string,Array<NodeCode>>}
  33707. */
  33708. this.codes = {};
  33709. /**
  33710. * This dictionary holds the node variables of this builder.
  33711. * The variables are maintained in an array for each shader stage.
  33712. * This dictionary is also used to count the number of variables
  33713. * according to their type (const, vars).
  33714. *
  33715. * @type {Object<string,Array<NodeVar>|number>}
  33716. */
  33717. this.vars = {};
  33718. /**
  33719. * This dictionary holds the declarations for each shader stage.
  33720. *
  33721. * @type {Object}
  33722. */
  33723. this.declarations = {};
  33724. /**
  33725. * Current code flow.
  33726. * All code generated in this stack will be stored in `.flow`.
  33727. *
  33728. * @type {{code: string}}
  33729. */
  33730. this.flow = { code: '' };
  33731. /**
  33732. * A chain of nodes.
  33733. * Used to check recursive calls in node-graph.
  33734. *
  33735. * @type {Array<Node>}
  33736. */
  33737. this.chaining = [];
  33738. /**
  33739. * The current stack.
  33740. * This reflects the current process in the code block hierarchy,
  33741. * it is useful to know if the current process is inside a conditional for example.
  33742. *
  33743. * @type {StackNode}
  33744. */
  33745. this.stack = stack();
  33746. /**
  33747. * List of stack nodes.
  33748. * The current stack hierarchy is stored in an array.
  33749. *
  33750. * @type {Array<StackNode>}
  33751. */
  33752. this.stacks = [];
  33753. /**
  33754. * A tab value. Used for shader string generation.
  33755. *
  33756. * @type {string}
  33757. * @default '\t'
  33758. */
  33759. this.tab = '\t';
  33760. /**
  33761. * Reference to the current function node.
  33762. *
  33763. * @type {?FunctionNode}
  33764. * @default null
  33765. */
  33766. this.currentFunctionNode = null;
  33767. /**
  33768. * The builder's context.
  33769. *
  33770. * @type {Object}
  33771. */
  33772. this.context = {
  33773. material: this.material
  33774. };
  33775. /**
  33776. * The builder's cache.
  33777. *
  33778. * @type {NodeCache}
  33779. */
  33780. this.cache = new NodeCache();
  33781. /**
  33782. * Since the {@link NodeBuilder#cache} might be temporarily
  33783. * overwritten by other caches, this member retains the reference
  33784. * to the builder's own cache.
  33785. *
  33786. * @type {NodeCache}
  33787. * @default this.cache
  33788. */
  33789. this.globalCache = this.cache;
  33790. this.flowsData = new WeakMap();
  33791. /**
  33792. * The current shader stage.
  33793. *
  33794. * @type {?('vertex'|'fragment'|'compute'|'any')}
  33795. */
  33796. this.shaderStage = null;
  33797. /**
  33798. * The current build stage.
  33799. *
  33800. * @type {?('setup'|'analyze'|'generate')}
  33801. */
  33802. this.buildStage = null;
  33803. /**
  33804. * The sub-build layers.
  33805. *
  33806. * @type {Array<SubBuildNode>}
  33807. * @default []
  33808. */
  33809. this.subBuildLayers = [];
  33810. /**
  33811. * The current stack of nodes.
  33812. *
  33813. * @type {?StackNode}
  33814. * @default null
  33815. */
  33816. this.currentStack = null;
  33817. /**
  33818. * The current sub-build TSL function(Fn).
  33819. *
  33820. * @type {?string}
  33821. * @default null
  33822. */
  33823. this.subBuildFn = null;
  33824. }
  33825. /**
  33826. * Returns the bind groups of the current renderer.
  33827. *
  33828. * @return {ChainMap} The cache.
  33829. */
  33830. getBindGroupsCache() {
  33831. let bindGroupsCache = rendererCache.get( this.renderer );
  33832. if ( bindGroupsCache === undefined ) {
  33833. bindGroupsCache = new ChainMap();
  33834. rendererCache.set( this.renderer, bindGroupsCache );
  33835. }
  33836. return bindGroupsCache;
  33837. }
  33838. /**
  33839. * Factory method for creating an instance of {@link RenderTarget} with the given
  33840. * dimensions and options.
  33841. *
  33842. * @param {number} width - The width of the render target.
  33843. * @param {number} height - The height of the render target.
  33844. * @param {Object} options - The options of the render target.
  33845. * @return {RenderTarget} The render target.
  33846. */
  33847. createRenderTarget( width, height, options ) {
  33848. return new RenderTarget( width, height, options );
  33849. }
  33850. /**
  33851. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  33852. * dimensions and options.
  33853. *
  33854. * @param {number} size - The size of the cube render target.
  33855. * @param {Object} options - The options of the cube render target.
  33856. * @return {CubeRenderTarget} The cube render target.
  33857. */
  33858. createCubeRenderTarget( size, options ) {
  33859. return new CubeRenderTarget( size, options );
  33860. }
  33861. /**
  33862. * Whether the given node is included in the internal array of nodes or not.
  33863. *
  33864. * @param {Node} node - The node to test.
  33865. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  33866. */
  33867. includes( node ) {
  33868. return this.nodes.includes( node );
  33869. }
  33870. /**
  33871. * Returns the output struct name which is required by
  33872. * {@link OutputStructNode}.
  33873. *
  33874. * @abstract
  33875. * @return {string} The name of the output struct.
  33876. */
  33877. getOutputStructName() {}
  33878. /**
  33879. * Returns a bind group for the given group name and binding.
  33880. *
  33881. * @private
  33882. * @param {string} groupName - The group name.
  33883. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  33884. * @return {BindGroup} The bind group
  33885. */
  33886. _getBindGroup( groupName, bindings ) {
  33887. const bindGroupsCache = this.getBindGroupsCache();
  33888. //
  33889. const bindingsArray = [];
  33890. let sharedGroup = true;
  33891. for ( const binding of bindings ) {
  33892. bindingsArray.push( binding );
  33893. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  33894. }
  33895. //
  33896. let bindGroup;
  33897. if ( sharedGroup ) {
  33898. bindGroup = bindGroupsCache.get( bindingsArray );
  33899. if ( bindGroup === undefined ) {
  33900. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  33901. bindGroupsCache.set( bindingsArray, bindGroup );
  33902. }
  33903. } else {
  33904. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  33905. }
  33906. return bindGroup;
  33907. }
  33908. /**
  33909. * Returns an array of node uniform groups for the given group name and shader stage.
  33910. *
  33911. * @param {string} groupName - The group name.
  33912. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33913. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  33914. */
  33915. getBindGroupArray( groupName, shaderStage ) {
  33916. const bindings = this.bindings[ shaderStage ];
  33917. let bindGroup = bindings[ groupName ];
  33918. if ( bindGroup === undefined ) {
  33919. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  33920. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  33921. }
  33922. bindings[ groupName ] = bindGroup = [];
  33923. }
  33924. return bindGroup;
  33925. }
  33926. /**
  33927. * Returns a list bindings of all shader stages separated by groups.
  33928. *
  33929. * @return {Array<BindGroup>} The list of bindings.
  33930. */
  33931. getBindings() {
  33932. let bindingsGroups = this.bindGroups;
  33933. if ( bindingsGroups === null ) {
  33934. const groups = {};
  33935. const bindings = this.bindings;
  33936. for ( const shaderStage of shaderStages ) {
  33937. for ( const groupName in bindings[ shaderStage ] ) {
  33938. const uniforms = bindings[ shaderStage ][ groupName ];
  33939. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  33940. groupUniforms.push( ...uniforms );
  33941. }
  33942. }
  33943. bindingsGroups = [];
  33944. for ( const groupName in groups ) {
  33945. const group = groups[ groupName ];
  33946. const bindingsGroup = this._getBindGroup( groupName, group );
  33947. bindingsGroups.push( bindingsGroup );
  33948. }
  33949. this.bindGroups = bindingsGroups;
  33950. }
  33951. return bindingsGroups;
  33952. }
  33953. /**
  33954. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  33955. */
  33956. sortBindingGroups() {
  33957. const bindingsGroups = this.getBindings();
  33958. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  33959. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  33960. const bindingGroup = bindingsGroups[ i ];
  33961. this.bindingsIndexes[ bindingGroup.name ].group = i;
  33962. bindingGroup.index = i;
  33963. }
  33964. }
  33965. /**
  33966. * The builder maintains each node in a hash-based dictionary.
  33967. * This method sets the given node (value) with the given hash (key) into this dictionary.
  33968. *
  33969. * @param {Node} node - The node to add.
  33970. * @param {number} hash - The hash of the node.
  33971. */
  33972. setHashNode( node, hash ) {
  33973. this.hashNodes[ hash ] = node;
  33974. }
  33975. /**
  33976. * Adds a node to this builder.
  33977. *
  33978. * @param {Node} node - The node to add.
  33979. */
  33980. addNode( node ) {
  33981. if ( this.nodes.includes( node ) === false ) {
  33982. this.nodes.push( node );
  33983. this.setHashNode( node, node.getHash( this ) );
  33984. }
  33985. }
  33986. /**
  33987. * It is used to add Nodes that will be used as FRAME and RENDER events,
  33988. * and need to follow a certain sequence in the calls to work correctly.
  33989. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  33990. *
  33991. * @param {Node} node - The node to add.
  33992. */
  33993. addSequentialNode( node ) {
  33994. if ( this.sequentialNodes.includes( node ) === false ) {
  33995. this.sequentialNodes.push( node );
  33996. }
  33997. }
  33998. /**
  33999. * Checks the update types of nodes
  34000. */
  34001. buildUpdateNodes() {
  34002. for ( const node of this.nodes ) {
  34003. const updateType = node.getUpdateType();
  34004. if ( updateType !== NodeUpdateType.NONE ) {
  34005. this.updateNodes.push( node );
  34006. }
  34007. }
  34008. for ( const node of this.sequentialNodes ) {
  34009. const updateBeforeType = node.getUpdateBeforeType();
  34010. const updateAfterType = node.getUpdateAfterType();
  34011. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  34012. this.updateBeforeNodes.push( node );
  34013. }
  34014. if ( updateAfterType !== NodeUpdateType.NONE ) {
  34015. this.updateAfterNodes.push( node );
  34016. }
  34017. }
  34018. }
  34019. /**
  34020. * A reference the current node which is the
  34021. * last node in the chain of nodes.
  34022. *
  34023. * @type {Node}
  34024. */
  34025. get currentNode() {
  34026. return this.chaining[ this.chaining.length - 1 ];
  34027. }
  34028. /**
  34029. * Whether the given texture is filtered or not.
  34030. *
  34031. * @param {Texture} texture - The texture to check.
  34032. * @return {boolean} Whether the given texture is filtered or not.
  34033. */
  34034. isFilteredTexture( texture ) {
  34035. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  34036. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  34037. }
  34038. /**
  34039. * Adds the given node to the internal node chain.
  34040. * This is used to check recursive calls in node-graph.
  34041. *
  34042. * @param {Node} node - The node to add.
  34043. */
  34044. addChain( node ) {
  34045. /*
  34046. if ( this.chaining.indexOf( node ) !== - 1 ) {
  34047. warn( 'Recursive node: ', node );
  34048. }
  34049. */
  34050. this.chaining.push( node );
  34051. }
  34052. /**
  34053. * Removes the given node from the internal node chain.
  34054. *
  34055. * @param {Node} node - The node to remove.
  34056. */
  34057. removeChain( node ) {
  34058. const lastChain = this.chaining.pop();
  34059. if ( lastChain !== node ) {
  34060. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  34061. }
  34062. }
  34063. /**
  34064. * Returns the native shader method name for a given generic name. E.g.
  34065. * the method name `textureDimensions` matches the WGSL name but must be
  34066. * resolved to `textureSize` in GLSL.
  34067. *
  34068. * @abstract
  34069. * @param {string} method - The method name to resolve.
  34070. * @return {string} The resolved method name.
  34071. */
  34072. getMethod( method ) {
  34073. return method;
  34074. }
  34075. /**
  34076. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  34077. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  34078. *
  34079. * @abstract
  34080. * @param {string} condSnippet - The condition determining which expression gets resolved.
  34081. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  34082. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  34083. * @return {string} The resolved method name.
  34084. */
  34085. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  34086. return null;
  34087. }
  34088. /**
  34089. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  34090. *
  34091. * @param {number} hash - The hash of the node.
  34092. * @return {Node} The found node.
  34093. */
  34094. getNodeFromHash( hash ) {
  34095. return this.hashNodes[ hash ];
  34096. }
  34097. /**
  34098. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  34099. *
  34100. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  34101. * @param {Node} node - The node to add.
  34102. * @return {Node} The node.
  34103. */
  34104. addFlow( shaderStage, node ) {
  34105. this.flowNodes[ shaderStage ].push( node );
  34106. return node;
  34107. }
  34108. /**
  34109. * Sets builder's context.
  34110. *
  34111. * @param {Object} context - The context to set.
  34112. */
  34113. setContext( context ) {
  34114. this.context = context;
  34115. }
  34116. /**
  34117. * Returns the builder's current context.
  34118. *
  34119. * @return {Object} The builder's current context.
  34120. */
  34121. getContext() {
  34122. return this.context;
  34123. }
  34124. /**
  34125. * Gets a context used in shader construction that can be shared across different materials.
  34126. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  34127. *
  34128. * @return {Object} The builder's current context without material.
  34129. */
  34130. getSharedContext() {
  34131. ({ ...this.context });
  34132. return this.context;
  34133. }
  34134. /**
  34135. * Sets builder's cache.
  34136. *
  34137. * @param {NodeCache} cache - The cache to set.
  34138. */
  34139. setCache( cache ) {
  34140. this.cache = cache;
  34141. }
  34142. /**
  34143. * Returns the builder's current cache.
  34144. *
  34145. * @return {NodeCache} The builder's current cache.
  34146. */
  34147. getCache() {
  34148. return this.cache;
  34149. }
  34150. /**
  34151. * Returns a cache for the given node.
  34152. *
  34153. * @param {Node} node - The node.
  34154. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  34155. * @return {NodeCache} The cache.
  34156. */
  34157. getCacheFromNode( node, parent = true ) {
  34158. const data = this.getDataFromNode( node );
  34159. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  34160. return data.cache;
  34161. }
  34162. /**
  34163. * Whether the requested feature is available or not.
  34164. *
  34165. * @abstract
  34166. * @param {string} name - The requested feature.
  34167. * @return {boolean} Whether the requested feature is supported or not.
  34168. */
  34169. isAvailable( /*name*/ ) {
  34170. return false;
  34171. }
  34172. /**
  34173. * Returns the vertexIndex input variable as a native shader string.
  34174. *
  34175. * @abstract
  34176. * @return {string} The instanceIndex shader string.
  34177. */
  34178. getVertexIndex() {
  34179. warn( 'Abstract function.' );
  34180. }
  34181. /**
  34182. * Returns the instanceIndex input variable as a native shader string.
  34183. *
  34184. * @abstract
  34185. * @return {string} The instanceIndex shader string.
  34186. */
  34187. getInstanceIndex() {
  34188. warn( 'Abstract function.' );
  34189. }
  34190. /**
  34191. * Returns the drawIndex input variable as a native shader string.
  34192. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  34193. *
  34194. * @abstract
  34195. * @return {?string} The drawIndex shader string.
  34196. */
  34197. getDrawIndex() {
  34198. warn( 'Abstract function.' );
  34199. }
  34200. /**
  34201. * Returns the frontFacing input variable as a native shader string.
  34202. *
  34203. * @abstract
  34204. * @return {string} The frontFacing shader string.
  34205. */
  34206. getFrontFacing() {
  34207. warn( 'Abstract function.' );
  34208. }
  34209. /**
  34210. * Returns the fragCoord input variable as a native shader string.
  34211. *
  34212. * @abstract
  34213. * @return {string} The fragCoord shader string.
  34214. */
  34215. getFragCoord() {
  34216. warn( 'Abstract function.' );
  34217. }
  34218. /**
  34219. * Whether to flip texture data along its vertical axis or not. WebGL needs
  34220. * this method evaluate to `true`, WebGPU to `false`.
  34221. *
  34222. * @abstract
  34223. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  34224. */
  34225. isFlipY() {
  34226. return false;
  34227. }
  34228. /**
  34229. * Calling this method increases the usage count for the given node by one.
  34230. *
  34231. * @param {Node} node - The node to increase the usage count for.
  34232. * @return {number} The updated usage count.
  34233. */
  34234. increaseUsage( node ) {
  34235. const nodeData = this.getDataFromNode( node );
  34236. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  34237. return nodeData.usageCount;
  34238. }
  34239. /**
  34240. * Generates a texture sample shader string for the given texture data.
  34241. *
  34242. * @abstract
  34243. * @param {Texture} texture - The texture.
  34244. * @param {string} textureProperty - The texture property name.
  34245. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34246. * @return {string} The generated shader string.
  34247. */
  34248. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  34249. warn( 'Abstract function.' );
  34250. }
  34251. /**
  34252. * Generates a texture LOD shader string for the given texture data.
  34253. *
  34254. * @abstract
  34255. * @param {Texture} texture - The texture.
  34256. * @param {string} textureProperty - The texture property name.
  34257. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34258. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  34259. * @param {string} levelSnippet - Snippet defining the mip level.
  34260. * @return {string} The generated shader string.
  34261. */
  34262. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  34263. warn( 'Abstract function.' );
  34264. }
  34265. /**
  34266. * Generates the array declaration string.
  34267. *
  34268. * @param {string} type - The type.
  34269. * @param {?number} [count] - The count.
  34270. * @return {string} The generated value as a shader string.
  34271. */
  34272. generateArrayDeclaration( type, count ) {
  34273. return this.getType( type ) + '[ ' + count + ' ]';
  34274. }
  34275. /**
  34276. * Generates the array shader string for the given type and value.
  34277. *
  34278. * @param {string} type - The type.
  34279. * @param {?number} [count] - The count.
  34280. * @param {?Array<Node>} [values=null] - The default values.
  34281. * @return {string} The generated value as a shader string.
  34282. */
  34283. generateArray( type, count, values = null ) {
  34284. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  34285. for ( let i = 0; i < count; i ++ ) {
  34286. const value = values ? values[ i ] : null;
  34287. if ( value !== null ) {
  34288. snippet += value.build( this, type );
  34289. } else {
  34290. snippet += this.generateConst( type );
  34291. }
  34292. if ( i < count - 1 ) snippet += ', ';
  34293. }
  34294. snippet += ' )';
  34295. return snippet;
  34296. }
  34297. /**
  34298. * Generates the struct shader string.
  34299. *
  34300. * @param {string} type - The type.
  34301. * @param {Array<Object>} [membersLayout] - The count.
  34302. * @param {?Array<Node>} [values=null] - The default values.
  34303. * @return {string} The generated value as a shader string.
  34304. */
  34305. generateStruct( type, membersLayout, values = null ) {
  34306. const snippets = [];
  34307. for ( const member of membersLayout ) {
  34308. const { name, type } = member;
  34309. if ( values && values[ name ] && values[ name ].isNode ) {
  34310. snippets.push( values[ name ].build( this, type ) );
  34311. } else {
  34312. snippets.push( this.generateConst( type ) );
  34313. }
  34314. }
  34315. return type + '( ' + snippets.join( ', ' ) + ' )';
  34316. }
  34317. /**
  34318. * Generates the shader string for the given type and value.
  34319. *
  34320. * @param {string} type - The type.
  34321. * @param {?any} [value=null] - The value.
  34322. * @return {string} The generated value as a shader string.
  34323. */
  34324. generateConst( type, value = null ) {
  34325. if ( value === null ) {
  34326. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  34327. else if ( type === 'bool' ) value = false;
  34328. else if ( type === 'color' ) value = new Color();
  34329. else if ( type === 'vec2' ) value = new Vector2();
  34330. else if ( type === 'vec3' ) value = new Vector3();
  34331. else if ( type === 'vec4' ) value = new Vector4();
  34332. }
  34333. if ( type === 'float' ) return toFloat( value );
  34334. if ( type === 'int' ) return `${ Math.round( value ) }`;
  34335. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  34336. if ( type === 'bool' ) return value ? 'true' : 'false';
  34337. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  34338. const typeLength = this.getTypeLength( type );
  34339. const componentType = this.getComponentType( type );
  34340. const generateConst = value => this.generateConst( componentType, value );
  34341. if ( typeLength === 2 ) {
  34342. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  34343. } else if ( typeLength === 3 ) {
  34344. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  34345. } else if ( typeLength === 4 && type !== 'mat2' ) {
  34346. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  34347. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  34348. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  34349. } else if ( typeLength > 4 ) {
  34350. return `${ this.getType( type ) }()`;
  34351. }
  34352. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  34353. }
  34354. /**
  34355. * It might be necessary to convert certain data types to different ones
  34356. * so this method can be used to hide the conversion.
  34357. *
  34358. * @param {string} type - The type.
  34359. * @return {string} The updated type.
  34360. */
  34361. getType( type ) {
  34362. if ( type === 'color' ) return 'vec3';
  34363. return type;
  34364. }
  34365. /**
  34366. * Whether the given attribute name is defined in the geometry or not.
  34367. *
  34368. * @param {string} name - The attribute name.
  34369. * @return {boolean} Whether the given attribute name is defined in the geometry.
  34370. */
  34371. hasGeometryAttribute( name ) {
  34372. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  34373. }
  34374. /**
  34375. * Returns a node attribute for the given name and type.
  34376. *
  34377. * @param {string} name - The attribute's name.
  34378. * @param {string} type - The attribute's type.
  34379. * @return {NodeAttribute} The node attribute.
  34380. */
  34381. getAttribute( name, type ) {
  34382. const attributes = this.attributes;
  34383. // find attribute
  34384. for ( const attribute of attributes ) {
  34385. if ( attribute.name === name ) {
  34386. return attribute;
  34387. }
  34388. }
  34389. // create a new if no exist
  34390. const attribute = new NodeAttribute( name, type );
  34391. this.registerDeclaration( attribute );
  34392. attributes.push( attribute );
  34393. return attribute;
  34394. }
  34395. /**
  34396. * Returns for the given node and shader stage the property name for the shader.
  34397. *
  34398. * @param {Node} node - The node.
  34399. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34400. * @return {string} The property name.
  34401. */
  34402. getPropertyName( node/*, shaderStage*/ ) {
  34403. return node.name;
  34404. }
  34405. /**
  34406. * Whether the given type is a vector type or not.
  34407. *
  34408. * @param {string} type - The type to check.
  34409. * @return {boolean} Whether the given type is a vector type or not.
  34410. */
  34411. isVector( type ) {
  34412. return /vec\d/.test( type );
  34413. }
  34414. /**
  34415. * Whether the given type is a matrix type or not.
  34416. *
  34417. * @param {string} type - The type to check.
  34418. * @return {boolean} Whether the given type is a matrix type or not.
  34419. */
  34420. isMatrix( type ) {
  34421. return /mat\d/.test( type );
  34422. }
  34423. /**
  34424. * Whether the given type is a reference type or not.
  34425. *
  34426. * @param {string} type - The type to check.
  34427. * @return {boolean} Whether the given type is a reference type or not.
  34428. */
  34429. isReference( type ) {
  34430. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  34431. }
  34432. /**
  34433. * Checks if the given texture requires a manual conversion to the working color space.
  34434. *
  34435. * @abstract
  34436. * @param {Texture} texture - The texture to check.
  34437. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  34438. */
  34439. needsToWorkingColorSpace( /*texture*/ ) {
  34440. return false;
  34441. }
  34442. /**
  34443. * Returns the component type of a given texture.
  34444. *
  34445. * @param {Texture} texture - The texture.
  34446. * @return {string} The component type.
  34447. */
  34448. getComponentTypeFromTexture( texture ) {
  34449. const type = texture.type;
  34450. if ( texture.isDataTexture ) {
  34451. if ( type === IntType ) return 'int';
  34452. if ( type === UnsignedIntType ) return 'uint';
  34453. }
  34454. return 'float';
  34455. }
  34456. /**
  34457. * Returns the element type for a given type.
  34458. *
  34459. * @param {string} type - The type.
  34460. * @return {string} The element type.
  34461. */
  34462. getElementType( type ) {
  34463. if ( type === 'mat2' ) return 'vec2';
  34464. if ( type === 'mat3' ) return 'vec3';
  34465. if ( type === 'mat4' ) return 'vec4';
  34466. return this.getComponentType( type );
  34467. }
  34468. /**
  34469. * Returns the component type for a given type.
  34470. *
  34471. * @param {string} type - The type.
  34472. * @return {string} The component type.
  34473. */
  34474. getComponentType( type ) {
  34475. type = this.getVectorType( type );
  34476. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  34477. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  34478. if ( componentType === null ) return null;
  34479. if ( componentType[ 1 ] === 'b' ) return 'bool';
  34480. if ( componentType[ 1 ] === 'i' ) return 'int';
  34481. if ( componentType[ 1 ] === 'u' ) return 'uint';
  34482. return 'float';
  34483. }
  34484. /**
  34485. * Returns the vector type for a given type.
  34486. *
  34487. * @param {string} type - The type.
  34488. * @return {string} The vector type.
  34489. */
  34490. getVectorType( type ) {
  34491. if ( type === 'color' ) return 'vec3';
  34492. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  34493. return type;
  34494. }
  34495. /**
  34496. * Returns the data type for the given the length and component type.
  34497. *
  34498. * @param {number} length - The length.
  34499. * @param {string} [componentType='float'] - The component type.
  34500. * @return {string} The type.
  34501. */
  34502. getTypeFromLength( length, componentType = 'float' ) {
  34503. if ( length === 1 ) return componentType;
  34504. let baseType = getTypeFromLength( length );
  34505. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  34506. // fix edge case for mat2x2 being same size as vec4
  34507. if ( /mat2/.test( componentType ) === true ) {
  34508. baseType = baseType.replace( 'vec', 'mat' );
  34509. }
  34510. return prefix + baseType;
  34511. }
  34512. /**
  34513. * Returns the type for a given typed array.
  34514. *
  34515. * @param {TypedArray} array - The typed array.
  34516. * @return {string} The type.
  34517. */
  34518. getTypeFromArray( array ) {
  34519. return typeFromArray.get( array.constructor );
  34520. }
  34521. /**
  34522. * Returns the type is an integer type.
  34523. *
  34524. * @param {string} type - The type.
  34525. * @return {boolean} Whether the type is an integer type or not.
  34526. */
  34527. isInteger( type ) {
  34528. return /int|uint|(i|u)vec/.test( type );
  34529. }
  34530. /**
  34531. * Returns the type for a given buffer attribute.
  34532. *
  34533. * @param {BufferAttribute} attribute - The buffer attribute.
  34534. * @return {string} The type.
  34535. */
  34536. getTypeFromAttribute( attribute ) {
  34537. let dataAttribute = attribute;
  34538. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  34539. const array = dataAttribute.array;
  34540. const itemSize = attribute.itemSize;
  34541. const normalized = attribute.normalized;
  34542. let arrayType;
  34543. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  34544. arrayType = this.getTypeFromArray( array );
  34545. }
  34546. return this.getTypeFromLength( itemSize, arrayType );
  34547. }
  34548. /**
  34549. * Returns the length for the given data type.
  34550. *
  34551. * @param {string} type - The data type.
  34552. * @return {number} The length.
  34553. */
  34554. getTypeLength( type ) {
  34555. const vecType = this.getVectorType( type );
  34556. const vecNum = /vec([2-4])/.exec( vecType );
  34557. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  34558. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  34559. if ( /mat2/.test( type ) === true ) return 4;
  34560. if ( /mat3/.test( type ) === true ) return 9;
  34561. if ( /mat4/.test( type ) === true ) return 16;
  34562. return 0;
  34563. }
  34564. /**
  34565. * Returns the vector type for a given matrix type.
  34566. *
  34567. * @param {string} type - The matrix type.
  34568. * @return {string} The vector type.
  34569. */
  34570. getVectorFromMatrix( type ) {
  34571. return type.replace( 'mat', 'vec' );
  34572. }
  34573. /**
  34574. * For a given type this method changes the component type to the
  34575. * given value. E.g. `vec4` should be changed to the new component type
  34576. * `uint` which results in `uvec4`.
  34577. *
  34578. * @param {string} type - The type.
  34579. * @param {string} newComponentType - The new component type.
  34580. * @return {string} The new type.
  34581. */
  34582. changeComponentType( type, newComponentType ) {
  34583. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  34584. }
  34585. /**
  34586. * Returns the integer type pendant for the given type.
  34587. *
  34588. * @param {string} type - The type.
  34589. * @return {string} The integer type.
  34590. */
  34591. getIntegerType( type ) {
  34592. const componentType = this.getComponentType( type );
  34593. if ( componentType === 'int' || componentType === 'uint' ) return type;
  34594. return this.changeComponentType( type, 'int' );
  34595. }
  34596. /**
  34597. * Adds a stack node to the internal stack.
  34598. *
  34599. * @return {StackNode} The added stack node.
  34600. */
  34601. addStack() {
  34602. this.stack = stack( this.stack );
  34603. const previousStack = getCurrentStack();
  34604. this.stacks.push( previousStack );
  34605. setCurrentStack( this.stack );
  34606. return this.stack;
  34607. }
  34608. /**
  34609. * Removes the last stack node from the internal stack.
  34610. *
  34611. * @return {StackNode} The removed stack node.
  34612. */
  34613. removeStack() {
  34614. const lastStack = this.stack;
  34615. this.stack = lastStack.parent;
  34616. setCurrentStack( this.stacks.pop() );
  34617. return lastStack;
  34618. }
  34619. /**
  34620. * The builder maintains (cached) data for each node during the building process. This method
  34621. * can be used to get these data for a specific shader stage and cache.
  34622. *
  34623. * @param {Node} node - The node to get the data for.
  34624. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34625. * @param {?NodeCache} cache - An optional cache.
  34626. * @return {Object} The node data.
  34627. */
  34628. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  34629. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  34630. let nodeData = cache.getData( node );
  34631. if ( nodeData === undefined ) {
  34632. nodeData = {};
  34633. cache.setData( node, nodeData );
  34634. }
  34635. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  34636. //
  34637. let data = nodeData[ shaderStage ];
  34638. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  34639. const subBuild = this.getClosestSubBuild( subBuilds );
  34640. if ( subBuild ) {
  34641. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  34642. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  34643. data.subBuilds = subBuilds;
  34644. }
  34645. return data;
  34646. }
  34647. /**
  34648. * Returns the properties for the given node and shader stage.
  34649. *
  34650. * @param {Node} node - The node to get the properties for.
  34651. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  34652. * @return {Object} The node properties.
  34653. */
  34654. getNodeProperties( node, shaderStage = 'any' ) {
  34655. const nodeData = this.getDataFromNode( node, shaderStage );
  34656. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  34657. }
  34658. /**
  34659. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  34660. *
  34661. * @param {BufferAttributeNode} node - The buffer attribute node.
  34662. * @param {string} type - The node type.
  34663. * @return {NodeAttribute} The node attribute.
  34664. */
  34665. getBufferAttributeFromNode( node, type ) {
  34666. const nodeData = this.getDataFromNode( node );
  34667. let bufferAttribute = nodeData.bufferAttribute;
  34668. if ( bufferAttribute === undefined ) {
  34669. const index = this.uniforms.index ++;
  34670. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  34671. this.bufferAttributes.push( bufferAttribute );
  34672. nodeData.bufferAttribute = bufferAttribute;
  34673. }
  34674. return bufferAttribute;
  34675. }
  34676. /**
  34677. * Returns an instance of {@link StructType} for the given struct name and shader stage
  34678. * or null if not found.
  34679. *
  34680. * @param {string} name - The name of the struct.
  34681. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34682. * @return {?StructType} The struct type or null if not found.
  34683. */
  34684. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  34685. return this.types[ shaderStage ][ name ] || null;
  34686. }
  34687. /**
  34688. * Returns an instance of {@link StructType} for the given output struct node.
  34689. *
  34690. * @param {OutputStructNode} node - The output struct node.
  34691. * @param {Array<Object>} membersLayout - The output struct types.
  34692. * @param {?string} [name=null] - The name of the struct.
  34693. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34694. * @return {StructType} The struct type attribute.
  34695. */
  34696. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  34697. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34698. let structType = nodeData.structType;
  34699. if ( structType === undefined ) {
  34700. const index = this.structs.index ++;
  34701. if ( name === null ) name = 'StructType' + index;
  34702. structType = new StructType( name, membersLayout );
  34703. this.structs[ shaderStage ].push( structType );
  34704. this.types[ shaderStage ][ name ] = node;
  34705. nodeData.structType = structType;
  34706. }
  34707. return structType;
  34708. }
  34709. /**
  34710. * Returns an instance of {@link StructType} for the given output struct node.
  34711. *
  34712. * @param {OutputStructNode} node - The output struct node.
  34713. * @param {Array<Object>} membersLayout - The output struct types.
  34714. * @return {StructType} The struct type attribute.
  34715. */
  34716. getOutputStructTypeFromNode( node, membersLayout ) {
  34717. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  34718. structType.output = true;
  34719. return structType;
  34720. }
  34721. /**
  34722. * Returns an instance of {@link NodeUniform} for the given uniform node.
  34723. *
  34724. * @param {UniformNode} node - The uniform node.
  34725. * @param {string} type - The uniform type.
  34726. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34727. * @param {?string} name - The name of the uniform.
  34728. * @return {NodeUniform} The node uniform.
  34729. */
  34730. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  34731. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34732. let nodeUniform = nodeData.uniform;
  34733. if ( nodeUniform === undefined ) {
  34734. const index = this.uniforms.index ++;
  34735. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  34736. this.uniforms[ shaderStage ].push( nodeUniform );
  34737. this.registerDeclaration( nodeUniform );
  34738. nodeData.uniform = nodeUniform;
  34739. }
  34740. return nodeUniform;
  34741. }
  34742. /**
  34743. * Returns an instance of {@link NodeVar} for the given variable node.
  34744. *
  34745. * @param {VarNode} node - The variable node.
  34746. * @param {?string} name - The variable's name.
  34747. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  34748. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34749. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  34750. *
  34751. * @return {NodeVar} The node variable.
  34752. */
  34753. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  34754. const nodeData = this.getDataFromNode( node, shaderStage );
  34755. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  34756. let nodeVar = nodeData[ subBuildVariable ];
  34757. if ( nodeVar === undefined ) {
  34758. const idNS = readOnly ? '_const' : '_var';
  34759. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  34760. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  34761. if ( name === null ) {
  34762. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  34763. this.vars[ idNS ] ++;
  34764. }
  34765. //
  34766. if ( subBuildVariable !== 'variable' ) {
  34767. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  34768. }
  34769. //
  34770. const count = node.getArrayCount( this );
  34771. nodeVar = new NodeVar( name, type, readOnly, count );
  34772. if ( ! readOnly ) {
  34773. vars.push( nodeVar );
  34774. }
  34775. this.registerDeclaration( nodeVar );
  34776. nodeData[ subBuildVariable ] = nodeVar;
  34777. }
  34778. return nodeVar;
  34779. }
  34780. /**
  34781. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  34782. *
  34783. * @param {Node} node - The varying node.
  34784. * @return {boolean} Returns true if deterministic.
  34785. */
  34786. isDeterministic( node ) {
  34787. if ( node.isMathNode ) {
  34788. return this.isDeterministic( node.aNode ) &&
  34789. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  34790. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  34791. } else if ( node.isOperatorNode ) {
  34792. return this.isDeterministic( node.aNode ) &&
  34793. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  34794. } else if ( node.isArrayNode ) {
  34795. if ( node.values !== null ) {
  34796. for ( const n of node.values ) {
  34797. if ( ! this.isDeterministic( n ) ) {
  34798. return false;
  34799. }
  34800. }
  34801. }
  34802. return true;
  34803. } else if ( node.isConstNode ) {
  34804. return true;
  34805. }
  34806. return false;
  34807. }
  34808. /**
  34809. * Returns an instance of {@link NodeVarying} for the given varying node.
  34810. *
  34811. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  34812. * @param {?string} name - The varying's name.
  34813. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  34814. * @param {?string} interpolationType - The interpolation type of the varying.
  34815. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34816. * @return {NodeVar} The node varying.
  34817. */
  34818. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  34819. const nodeData = this.getDataFromNode( node, 'any' );
  34820. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  34821. let nodeVarying = nodeData[ subBuildVarying ];
  34822. if ( nodeVarying === undefined ) {
  34823. const varyings = this.varyings;
  34824. const index = varyings.length;
  34825. if ( name === null ) name = 'nodeVarying' + index;
  34826. //
  34827. if ( subBuildVarying !== 'varying' ) {
  34828. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  34829. }
  34830. //
  34831. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  34832. varyings.push( nodeVarying );
  34833. this.registerDeclaration( nodeVarying );
  34834. nodeData[ subBuildVarying ] = nodeVarying;
  34835. }
  34836. return nodeVarying;
  34837. }
  34838. /**
  34839. * Registers a node declaration in the current shader stage.
  34840. *
  34841. * @param {Object} node - The node to be registered.
  34842. */
  34843. registerDeclaration( node ) {
  34844. const shaderStage = this.shaderStage;
  34845. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  34846. const property = this.getPropertyName( node );
  34847. let index = 1;
  34848. let name = property;
  34849. // Automatically renames the property if the name is already in use.
  34850. while ( declarations[ name ] !== undefined ) {
  34851. name = property + '_' + index ++;
  34852. }
  34853. if ( index > 1 ) {
  34854. node.name = name;
  34855. warn( `TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  34856. }
  34857. declarations[ name ] = node;
  34858. }
  34859. /**
  34860. * Returns an instance of {@link NodeCode} for the given code node.
  34861. *
  34862. * @param {CodeNode} node - The code node.
  34863. * @param {string} type - The node type.
  34864. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34865. * @return {NodeCode} The node code.
  34866. */
  34867. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  34868. const nodeData = this.getDataFromNode( node );
  34869. let nodeCode = nodeData.code;
  34870. if ( nodeCode === undefined ) {
  34871. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  34872. const index = codes.length;
  34873. nodeCode = new NodeCode( 'nodeCode' + index, type );
  34874. codes.push( nodeCode );
  34875. nodeData.code = nodeCode;
  34876. }
  34877. return nodeCode;
  34878. }
  34879. /**
  34880. * Adds a code flow based on the code-block hierarchy.
  34881. * This is used so that code-blocks like If,Else create their variables locally if the Node
  34882. * is only used inside one of these conditionals in the current shader stage.
  34883. *
  34884. * @param {Node} node - The node to add.
  34885. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  34886. */
  34887. addFlowCodeHierarchy( node, nodeBlock ) {
  34888. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  34889. let needsFlowCode = true;
  34890. let nodeBlockHierarchy = nodeBlock;
  34891. while ( nodeBlockHierarchy ) {
  34892. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  34893. needsFlowCode = false;
  34894. break;
  34895. }
  34896. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  34897. }
  34898. if ( needsFlowCode ) {
  34899. for ( const flowCode of flowCodes ) {
  34900. this.addLineFlowCode( flowCode );
  34901. }
  34902. }
  34903. }
  34904. /**
  34905. * Add a inline-code to the current flow code-block.
  34906. *
  34907. * @param {Node} node - The node to add.
  34908. * @param {string} code - The code to add.
  34909. * @param {Node} nodeBlock - Current ConditionalNode
  34910. */
  34911. addLineFlowCodeBlock( node, code, nodeBlock ) {
  34912. const nodeData = this.getDataFromNode( node );
  34913. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  34914. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  34915. flowCodes.push( code );
  34916. codeBlock.set( nodeBlock, true );
  34917. }
  34918. /**
  34919. * Add a inline-code to the current flow.
  34920. *
  34921. * @param {string} code - The code to add.
  34922. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  34923. * @return {NodeBuilder} A reference to this node builder.
  34924. */
  34925. addLineFlowCode( code, node = null ) {
  34926. if ( code === '' ) return this;
  34927. if ( node !== null && this.context.nodeBlock ) {
  34928. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  34929. }
  34930. code = this.tab + code;
  34931. if ( ! /;\s*$/.test( code ) ) {
  34932. code = code + ';\n';
  34933. }
  34934. this.flow.code += code;
  34935. return this;
  34936. }
  34937. /**
  34938. * Adds a code to the current code flow.
  34939. *
  34940. * @param {string} code - Shader code.
  34941. * @return {NodeBuilder} A reference to this node builder.
  34942. */
  34943. addFlowCode( code ) {
  34944. this.flow.code += code;
  34945. return this;
  34946. }
  34947. /**
  34948. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  34949. * Typically used in codes with If,Else.
  34950. *
  34951. * @return {NodeBuilder} A reference to this node builder.
  34952. */
  34953. addFlowTab() {
  34954. this.tab += '\t';
  34955. return this;
  34956. }
  34957. /**
  34958. * Removes a tab.
  34959. *
  34960. * @return {NodeBuilder} A reference to this node builder.
  34961. */
  34962. removeFlowTab() {
  34963. this.tab = this.tab.slice( 0, -1 );
  34964. return this;
  34965. }
  34966. /**
  34967. * Gets the current flow data based on a Node.
  34968. *
  34969. * @param {Node} node - Node that the flow was started.
  34970. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34971. * @return {Object} The flow data.
  34972. */
  34973. getFlowData( node/*, shaderStage*/ ) {
  34974. return this.flowsData.get( node );
  34975. }
  34976. /**
  34977. * Executes the node flow based on a root node to generate the final shader code.
  34978. *
  34979. * @param {Node} node - The node to execute.
  34980. * @return {Object} The code flow.
  34981. */
  34982. flowNode( node ) {
  34983. const output = node.getNodeType( this );
  34984. const flowData = this.flowChildNode( node, output );
  34985. this.flowsData.set( node, flowData );
  34986. return flowData;
  34987. }
  34988. /**
  34989. * Includes a node in the current function node.
  34990. *
  34991. * @param {Node} node - The node to include.
  34992. * @returns {void}
  34993. */
  34994. addInclude( node ) {
  34995. if ( this.currentFunctionNode !== null ) {
  34996. this.currentFunctionNode.includes.push( node );
  34997. }
  34998. }
  34999. /**
  35000. * Returns the native shader operator name for a given generic name.
  35001. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35002. *
  35003. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  35004. * @return {FunctionNode} The build function node.
  35005. */
  35006. buildFunctionNode( shaderNode ) {
  35007. const fn = new FunctionNode();
  35008. const previous = this.currentFunctionNode;
  35009. this.currentFunctionNode = fn;
  35010. fn.code = this.buildFunctionCode( shaderNode );
  35011. this.currentFunctionNode = previous;
  35012. return fn;
  35013. }
  35014. /**
  35015. * Generates a code flow based on a TSL function: Fn().
  35016. *
  35017. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  35018. * @return {Object}
  35019. */
  35020. flowShaderNode( shaderNode ) {
  35021. const layout = shaderNode.layout;
  35022. const inputs = {
  35023. [ Symbol.iterator ]() {
  35024. let index = 0;
  35025. const values = Object.values( this );
  35026. return {
  35027. next: () => ( {
  35028. value: values[ index ],
  35029. done: index ++ >= values.length
  35030. } )
  35031. };
  35032. }
  35033. };
  35034. for ( const input of layout.inputs ) {
  35035. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  35036. }
  35037. //
  35038. shaderNode.layout = null;
  35039. const callNode = shaderNode.call( inputs );
  35040. const flowData = this.flowStagesNode( callNode, layout.type );
  35041. shaderNode.layout = layout;
  35042. return flowData;
  35043. }
  35044. /**
  35045. * Executes the node in a specific build stage.
  35046. *
  35047. * @param {Node} node - The node to execute.
  35048. * @param {string} buildStage - The build stage to execute the node in.
  35049. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  35050. * @return {?(Node|string)} The result of the node build.
  35051. */
  35052. flowBuildStage( node, buildStage, output = null ) {
  35053. const previousBuildStage = this.getBuildStage();
  35054. this.setBuildStage( buildStage );
  35055. const result = node.build( this, output );
  35056. this.setBuildStage( previousBuildStage );
  35057. return result;
  35058. }
  35059. /**
  35060. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  35061. *
  35062. * @param {Node} node - The node to execute.
  35063. * @param {?string} output - Expected output type. For example 'vec3'.
  35064. * @return {Object}
  35065. */
  35066. flowStagesNode( node, output = null ) {
  35067. const previousFlow = this.flow;
  35068. const previousVars = this.vars;
  35069. const previousDeclarations = this.declarations;
  35070. const previousCache = this.cache;
  35071. const previousBuildStage = this.buildStage;
  35072. const previousStack = this.stack;
  35073. const flow = {
  35074. code: ''
  35075. };
  35076. this.flow = flow;
  35077. this.vars = {};
  35078. this.declarations = {};
  35079. this.cache = new NodeCache();
  35080. this.stack = stack();
  35081. for ( const buildStage of defaultBuildStages ) {
  35082. this.setBuildStage( buildStage );
  35083. flow.result = node.build( this, output );
  35084. }
  35085. flow.vars = this.getVars( this.shaderStage );
  35086. this.flow = previousFlow;
  35087. this.vars = previousVars;
  35088. this.declarations = previousDeclarations;
  35089. this.cache = previousCache;
  35090. this.stack = previousStack;
  35091. this.setBuildStage( previousBuildStage );
  35092. return flow;
  35093. }
  35094. /**
  35095. * Returns the native shader operator name for a given generic name.
  35096. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35097. *
  35098. * @abstract
  35099. * @param {string} op - The operator name to resolve.
  35100. * @return {?string} The resolved operator name.
  35101. */
  35102. getFunctionOperator( /* op */ ) {
  35103. return null;
  35104. }
  35105. /**
  35106. * Builds the given shader node.
  35107. *
  35108. * @abstract
  35109. * @param {ShaderNodeInternal} shaderNode - The shader node.
  35110. * @return {string} The function code.
  35111. */
  35112. buildFunctionCode( /* shaderNode */ ) {
  35113. warn( 'Abstract function.' );
  35114. }
  35115. /**
  35116. * Generates a code flow based on a child Node.
  35117. *
  35118. * @param {Node} node - The node to execute.
  35119. * @param {?string} output - Expected output type. For example 'vec3'.
  35120. * @return {Object} The code flow.
  35121. */
  35122. flowChildNode( node, output = null ) {
  35123. const previousFlow = this.flow;
  35124. const flow = {
  35125. code: ''
  35126. };
  35127. this.flow = flow;
  35128. flow.result = node.build( this, output );
  35129. this.flow = previousFlow;
  35130. return flow;
  35131. }
  35132. /**
  35133. * Executes a flow of code in a different stage.
  35134. *
  35135. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  35136. * return the value in fragment-stage even if it is being executed in an input fragment.
  35137. *
  35138. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35139. * @param {Node} node - The node to execute.
  35140. * @param {?string} output - Expected output type. For example 'vec3'.
  35141. * @param {?string} propertyName - The property name to assign the result.
  35142. * @return {?(Object|Node)} The code flow or node.build() result.
  35143. */
  35144. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  35145. const previousTab = this.tab;
  35146. const previousCache = this.cache;
  35147. const previousShaderStage = this.shaderStage;
  35148. const previousContext = this.context;
  35149. this.setShaderStage( shaderStage );
  35150. const context = { ...this.context };
  35151. delete context.nodeBlock;
  35152. this.cache = this.globalCache;
  35153. this.tab = '\t';
  35154. this.context = context;
  35155. let result = null;
  35156. if ( this.buildStage === 'generate' ) {
  35157. const flowData = this.flowChildNode( node, output );
  35158. if ( propertyName !== null ) {
  35159. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  35160. }
  35161. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  35162. result = flowData;
  35163. } else {
  35164. result = node.build( this );
  35165. }
  35166. this.setShaderStage( previousShaderStage );
  35167. this.cache = previousCache;
  35168. this.tab = previousTab;
  35169. this.context = previousContext;
  35170. return result;
  35171. }
  35172. /**
  35173. * Returns an array holding all node attributes of this node builder.
  35174. *
  35175. * @return {Array<NodeAttribute>} The node attributes of this builder.
  35176. */
  35177. getAttributesArray() {
  35178. return this.attributes.concat( this.bufferAttributes );
  35179. }
  35180. /**
  35181. * Returns the attribute definitions as a shader string for the given shader stage.
  35182. *
  35183. * @abstract
  35184. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35185. * @return {string} The attribute code section.
  35186. */
  35187. getAttributes( /*shaderStage*/ ) {
  35188. warn( 'Abstract function.' );
  35189. }
  35190. /**
  35191. * Returns the varying definitions as a shader string for the given shader stage.
  35192. *
  35193. * @abstract
  35194. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35195. * @return {string} The varying code section.
  35196. */
  35197. getVaryings( /*shaderStage*/ ) {
  35198. warn( 'Abstract function.' );
  35199. }
  35200. /**
  35201. * Returns a single variable definition as a shader string for the given variable type and name.
  35202. *
  35203. * @param {string} type - The variable's type.
  35204. * @param {string} name - The variable's name.
  35205. * @param {?number} [count=null] - The array length.
  35206. * @return {string} The shader string.
  35207. */
  35208. getVar( type, name, count = null ) {
  35209. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  35210. }
  35211. /**
  35212. * Returns the variable definitions as a shader string for the given shader stage.
  35213. *
  35214. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35215. * @return {string} The variable code section.
  35216. */
  35217. getVars( shaderStage ) {
  35218. let snippet = '';
  35219. const vars = this.vars[ shaderStage ];
  35220. if ( vars !== undefined ) {
  35221. for ( const variable of vars ) {
  35222. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  35223. }
  35224. }
  35225. return snippet;
  35226. }
  35227. /**
  35228. * Returns the uniform definitions as a shader string for the given shader stage.
  35229. *
  35230. * @abstract
  35231. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35232. * @return {string} The uniform code section.
  35233. */
  35234. getUniforms( /*shaderStage*/ ) {
  35235. warn( 'Abstract function.' );
  35236. }
  35237. /**
  35238. * Returns the native code definitions as a shader string for the given shader stage.
  35239. *
  35240. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35241. * @return {string} The native code section.
  35242. */
  35243. getCodes( shaderStage ) {
  35244. const codes = this.codes[ shaderStage ];
  35245. let code = '';
  35246. if ( codes !== undefined ) {
  35247. for ( const nodeCode of codes ) {
  35248. code += nodeCode.code + '\n';
  35249. }
  35250. }
  35251. return code;
  35252. }
  35253. /**
  35254. * Returns the hash of this node builder.
  35255. *
  35256. * @return {string} The hash.
  35257. */
  35258. getHash() {
  35259. return this.vertexShader + this.fragmentShader + this.computeShader;
  35260. }
  35261. /**
  35262. * Sets the current shader stage.
  35263. *
  35264. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  35265. */
  35266. setShaderStage( shaderStage ) {
  35267. this.shaderStage = shaderStage;
  35268. }
  35269. /**
  35270. * Returns the current shader stage.
  35271. *
  35272. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  35273. */
  35274. getShaderStage() {
  35275. return this.shaderStage;
  35276. }
  35277. /**
  35278. * Sets the current build stage.
  35279. *
  35280. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  35281. */
  35282. setBuildStage( buildStage ) {
  35283. this.buildStage = buildStage;
  35284. }
  35285. /**
  35286. * Returns the current build stage.
  35287. *
  35288. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  35289. */
  35290. getBuildStage() {
  35291. return this.buildStage;
  35292. }
  35293. /**
  35294. * Controls the code build of the shader stages.
  35295. *
  35296. * @abstract
  35297. */
  35298. buildCode() {
  35299. warn( 'Abstract function.' );
  35300. }
  35301. /**
  35302. * Returns the current sub-build layer.
  35303. *
  35304. * @return {SubBuildNode} The current sub-build layers.
  35305. */
  35306. get subBuild() {
  35307. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  35308. }
  35309. /**
  35310. * Adds a sub-build layer to the node builder.
  35311. *
  35312. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  35313. */
  35314. addSubBuild( subBuild ) {
  35315. this.subBuildLayers.push( subBuild );
  35316. }
  35317. /**
  35318. * Removes the last sub-build layer from the node builder.
  35319. *
  35320. * @return {SubBuildNode} The removed sub-build layer.
  35321. */
  35322. removeSubBuild() {
  35323. return this.subBuildLayers.pop();
  35324. }
  35325. /**
  35326. * Returns the closest sub-build layer for the given data.
  35327. *
  35328. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  35329. * @return {?string} The closest sub-build name or null if none found.
  35330. */
  35331. getClosestSubBuild( data ) {
  35332. let subBuilds;
  35333. if ( data && data.isNode ) {
  35334. if ( data.isShaderCallNodeInternal ) {
  35335. subBuilds = data.shaderNode.subBuilds;
  35336. } else if ( data.isStackNode ) {
  35337. subBuilds = [ data.subBuild ];
  35338. } else {
  35339. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  35340. }
  35341. } else if ( data instanceof Set ) {
  35342. subBuilds = [ ...data ];
  35343. } else {
  35344. subBuilds = data;
  35345. }
  35346. if ( ! subBuilds ) return null;
  35347. const subBuildLayers = this.subBuildLayers;
  35348. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  35349. const subBuild = subBuilds[ i ];
  35350. if ( subBuildLayers.includes( subBuild ) ) {
  35351. return subBuild;
  35352. }
  35353. }
  35354. return null;
  35355. }
  35356. /**
  35357. * Returns the output node of a sub-build layer.
  35358. *
  35359. * @param {Node} node - The node to get the output from.
  35360. * @return {string} The output node name.
  35361. */
  35362. getSubBuildOutput( node ) {
  35363. return this.getSubBuildProperty( 'outputNode', node );
  35364. }
  35365. /**
  35366. * Returns the sub-build property name for the given property and node.
  35367. *
  35368. * @param {string} [property=''] - The property name.
  35369. * @param {?Node} [node=null] - The node to get the sub-build from.
  35370. * @return {string} The sub-build property name.
  35371. */
  35372. getSubBuildProperty( property = '', node = null ) {
  35373. let subBuild;
  35374. if ( node !== null ) {
  35375. subBuild = this.getClosestSubBuild( node );
  35376. } else {
  35377. subBuild = this.subBuildFn;
  35378. }
  35379. let result;
  35380. if ( subBuild ) {
  35381. result = property ? ( subBuild + '_' + property ) : subBuild;
  35382. } else {
  35383. result = property;
  35384. }
  35385. return result;
  35386. }
  35387. /**
  35388. * Central build method which controls the build for the given object.
  35389. *
  35390. * @return {NodeBuilder} A reference to this node builder.
  35391. */
  35392. build() {
  35393. const { object, material, renderer } = this;
  35394. if ( material !== null ) {
  35395. let nodeMaterial = renderer.library.fromMaterial( material );
  35396. if ( nodeMaterial === null ) {
  35397. error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  35398. nodeMaterial = new NodeMaterial();
  35399. }
  35400. nodeMaterial.build( this );
  35401. } else {
  35402. this.addFlow( 'compute', object );
  35403. }
  35404. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  35405. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  35406. // generate() -> stage 3: generate shader
  35407. for ( const buildStage of defaultBuildStages ) {
  35408. this.setBuildStage( buildStage );
  35409. if ( this.context.vertex && this.context.vertex.isNode ) {
  35410. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  35411. }
  35412. for ( const shaderStage of shaderStages ) {
  35413. this.setShaderStage( shaderStage );
  35414. const flowNodes = this.flowNodes[ shaderStage ];
  35415. for ( const node of flowNodes ) {
  35416. if ( buildStage === 'generate' ) {
  35417. this.flowNode( node );
  35418. } else {
  35419. node.build( this );
  35420. }
  35421. }
  35422. }
  35423. }
  35424. this.setBuildStage( null );
  35425. this.setShaderStage( null );
  35426. // stage 4: build code for a specific output
  35427. this.buildCode();
  35428. this.buildUpdateNodes();
  35429. return this;
  35430. }
  35431. /**
  35432. * Returns a uniform representation which is later used for UBO generation and rendering.
  35433. *
  35434. * @param {NodeUniform} uniformNode - The uniform node.
  35435. * @param {string} type - The requested type.
  35436. * @return {Uniform} The uniform.
  35437. */
  35438. getNodeUniform( uniformNode, type ) {
  35439. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  35440. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  35441. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  35442. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  35443. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  35444. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  35445. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  35446. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  35447. throw new Error( `Uniform "${type}" not declared.` );
  35448. }
  35449. /**
  35450. * Formats the given shader snippet from a given type into another one. E.g.
  35451. * this method might be used to convert a simple float string `"1.0"` into a
  35452. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  35453. *
  35454. * @param {string} snippet - The shader snippet.
  35455. * @param {string} fromType - The source type.
  35456. * @param {string} toType - The target type.
  35457. * @return {string} The updated shader string.
  35458. */
  35459. format( snippet, fromType, toType ) {
  35460. fromType = this.getVectorType( fromType );
  35461. toType = this.getVectorType( toType );
  35462. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  35463. return snippet;
  35464. }
  35465. const fromTypeLength = this.getTypeLength( fromType );
  35466. const toTypeLength = this.getTypeLength( toType );
  35467. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  35468. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  35469. }
  35470. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  35471. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  35472. }
  35473. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  35474. // @TODO: ignore for now
  35475. return snippet;
  35476. }
  35477. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  35478. // @TODO: ignore for now
  35479. return snippet;
  35480. }
  35481. if ( fromTypeLength === toTypeLength ) {
  35482. return `${ this.getType( toType ) }( ${ snippet } )`;
  35483. }
  35484. if ( fromTypeLength > toTypeLength ) {
  35485. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  35486. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  35487. }
  35488. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  35489. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  35490. }
  35491. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  35492. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  35493. }
  35494. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  35495. // convert a number value to vector type, e.g:
  35496. // vec3( 1u ) -> vec3( float( 1u ) )
  35497. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  35498. }
  35499. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  35500. }
  35501. /**
  35502. * Returns a signature with the engine's current revision.
  35503. *
  35504. * @return {string} The signature.
  35505. */
  35506. getSignature() {
  35507. return `// Three.js r${ REVISION } - Node System\n`;
  35508. }
  35509. }
  35510. /**
  35511. * Management class for updating nodes. The module tracks metrics like
  35512. * the elapsed time, delta time, the render and frame ID to correctly
  35513. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  35514. * and {@link Node#updateAfter} depending on the node's configuration.
  35515. */
  35516. class NodeFrame {
  35517. /**
  35518. * Constructs a new node fame.
  35519. */
  35520. constructor() {
  35521. /**
  35522. * The elapsed time in seconds.
  35523. *
  35524. * @type {number}
  35525. * @default 0
  35526. */
  35527. this.time = 0;
  35528. /**
  35529. * The delta time in seconds.
  35530. *
  35531. * @type {number}
  35532. * @default 0
  35533. */
  35534. this.deltaTime = 0;
  35535. /**
  35536. * The frame ID.
  35537. *
  35538. * @type {number}
  35539. * @default 0
  35540. */
  35541. this.frameId = 0;
  35542. /**
  35543. * The render ID.
  35544. *
  35545. * @type {number}
  35546. * @default 0
  35547. */
  35548. this.renderId = 0;
  35549. /**
  35550. * Used to control the {@link Node#update} call.
  35551. *
  35552. * @type {WeakMap<Node, Object>}
  35553. */
  35554. this.updateMap = new WeakMap();
  35555. /**
  35556. * Used to control the {@link Node#updateBefore} call.
  35557. *
  35558. * @type {WeakMap<Node, Object>}
  35559. */
  35560. this.updateBeforeMap = new WeakMap();
  35561. /**
  35562. * Used to control the {@link Node#updateAfter} call.
  35563. *
  35564. * @type {WeakMap<Node, Object>}
  35565. */
  35566. this.updateAfterMap = new WeakMap();
  35567. /**
  35568. * A reference to the current renderer.
  35569. *
  35570. * @type {?Renderer}
  35571. * @default null
  35572. */
  35573. this.renderer = null;
  35574. /**
  35575. * A reference to the current material.
  35576. *
  35577. * @type {?Material}
  35578. * @default null
  35579. */
  35580. this.material = null;
  35581. /**
  35582. * A reference to the current camera.
  35583. *
  35584. * @type {?Camera}
  35585. * @default null
  35586. */
  35587. this.camera = null;
  35588. /**
  35589. * A reference to the current 3D object.
  35590. *
  35591. * @type {?Object3D}
  35592. * @default null
  35593. */
  35594. this.object = null;
  35595. /**
  35596. * A reference to the current scene.
  35597. *
  35598. * @type {?Scene}
  35599. * @default null
  35600. */
  35601. this.scene = null;
  35602. }
  35603. /**
  35604. * Returns a dictionary for a given node and update map which
  35605. * is used to correctly call node update methods per frame or render.
  35606. *
  35607. * @private
  35608. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  35609. * @param {Node} nodeRef - The reference to the current node.
  35610. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  35611. */
  35612. _getMaps( referenceMap, nodeRef ) {
  35613. let maps = referenceMap.get( nodeRef );
  35614. if ( maps === undefined ) {
  35615. maps = {
  35616. renderMap: new WeakMap(),
  35617. frameMap: new WeakMap()
  35618. };
  35619. referenceMap.set( nodeRef, maps );
  35620. }
  35621. return maps;
  35622. }
  35623. /**
  35624. * This method executes the {@link Node#updateBefore} for the given node.
  35625. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  35626. * is only executed once per frame, render or object depending on the update
  35627. * type.
  35628. *
  35629. * @param {Node} node - The node that should be updated.
  35630. */
  35631. updateBeforeNode( node ) {
  35632. const updateType = node.getUpdateBeforeType();
  35633. const reference = node.updateReference( this );
  35634. if ( updateType === NodeUpdateType.FRAME ) {
  35635. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  35636. if ( frameMap.get( reference ) !== this.frameId ) {
  35637. if ( node.updateBefore( this ) !== false ) {
  35638. frameMap.set( reference, this.frameId );
  35639. }
  35640. }
  35641. } else if ( updateType === NodeUpdateType.RENDER ) {
  35642. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  35643. if ( renderMap.get( reference ) !== this.renderId ) {
  35644. if ( node.updateBefore( this ) !== false ) {
  35645. renderMap.set( reference, this.renderId );
  35646. }
  35647. }
  35648. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35649. node.updateBefore( this );
  35650. }
  35651. }
  35652. /**
  35653. * This method executes the {@link Node#updateAfter} for the given node.
  35654. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  35655. * is only executed once per frame, render or object depending on the update
  35656. * type.
  35657. *
  35658. * @param {Node} node - The node that should be updated.
  35659. */
  35660. updateAfterNode( node ) {
  35661. const updateType = node.getUpdateAfterType();
  35662. const reference = node.updateReference( this );
  35663. if ( updateType === NodeUpdateType.FRAME ) {
  35664. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  35665. if ( frameMap.get( reference ) !== this.frameId ) {
  35666. if ( node.updateAfter( this ) !== false ) {
  35667. frameMap.set( reference, this.frameId );
  35668. }
  35669. }
  35670. } else if ( updateType === NodeUpdateType.RENDER ) {
  35671. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  35672. if ( renderMap.get( reference ) !== this.renderId ) {
  35673. if ( node.updateAfter( this ) !== false ) {
  35674. renderMap.set( reference, this.renderId );
  35675. }
  35676. }
  35677. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35678. node.updateAfter( this );
  35679. }
  35680. }
  35681. /**
  35682. * This method executes the {@link Node#update} for the given node.
  35683. * It makes sure {@link Node#updateType} is honored meaning the update
  35684. * is only executed once per frame, render or object depending on the update
  35685. * type.
  35686. *
  35687. * @param {Node} node - The node that should be updated.
  35688. */
  35689. updateNode( node ) {
  35690. const updateType = node.getUpdateType();
  35691. const reference = node.updateReference( this );
  35692. if ( updateType === NodeUpdateType.FRAME ) {
  35693. const { frameMap } = this._getMaps( this.updateMap, reference );
  35694. if ( frameMap.get( reference ) !== this.frameId ) {
  35695. if ( node.update( this ) !== false ) {
  35696. frameMap.set( reference, this.frameId );
  35697. }
  35698. }
  35699. } else if ( updateType === NodeUpdateType.RENDER ) {
  35700. const { renderMap } = this._getMaps( this.updateMap, reference );
  35701. if ( renderMap.get( reference ) !== this.renderId ) {
  35702. if ( node.update( this ) !== false ) {
  35703. renderMap.set( reference, this.renderId );
  35704. }
  35705. }
  35706. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35707. node.update( this );
  35708. }
  35709. }
  35710. /**
  35711. * Updates the internal state of the node frame. This method is
  35712. * called by the renderer in its internal animation loop.
  35713. */
  35714. update() {
  35715. this.frameId ++;
  35716. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  35717. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  35718. this.lastTime = performance.now();
  35719. this.time += this.deltaTime;
  35720. }
  35721. }
  35722. /**
  35723. * Describes the input of a {@link NodeFunction}.
  35724. */
  35725. class NodeFunctionInput {
  35726. /**
  35727. * Constructs a new node function input.
  35728. *
  35729. * @param {string} type - The input type.
  35730. * @param {string} name - The input name.
  35731. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  35732. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  35733. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  35734. */
  35735. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  35736. /**
  35737. * The input type.
  35738. *
  35739. * @type {string}
  35740. */
  35741. this.type = type;
  35742. /**
  35743. * The input name.
  35744. *
  35745. * @type {string}
  35746. */
  35747. this.name = name;
  35748. /**
  35749. * If the input is an Array, count will be the length.
  35750. *
  35751. * @type {?number}
  35752. * @default null
  35753. */
  35754. this.count = count;
  35755. /**
  35756. *The parameter qualifier (only relevant for GLSL).
  35757. *
  35758. * @type {('in'|'out'|'inout')}
  35759. * @default ''
  35760. */
  35761. this.qualifier = qualifier;
  35762. /**
  35763. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  35764. *
  35765. * @type {boolean}
  35766. * @default false
  35767. */
  35768. this.isConst = isConst;
  35769. }
  35770. }
  35771. NodeFunctionInput.isNodeFunctionInput = true;
  35772. /**
  35773. * Module for representing directional lights as nodes.
  35774. *
  35775. * @augments AnalyticLightNode
  35776. */
  35777. class DirectionalLightNode extends AnalyticLightNode {
  35778. static get type() {
  35779. return 'DirectionalLightNode';
  35780. }
  35781. /**
  35782. * Constructs a new directional light node.
  35783. *
  35784. * @param {?DirectionalLight} [light=null] - The directional light source.
  35785. */
  35786. constructor( light = null ) {
  35787. super( light );
  35788. }
  35789. setupDirect() {
  35790. const lightColor = this.colorNode;
  35791. const lightDirection = lightTargetDirection( this.light );
  35792. return { lightDirection, lightColor };
  35793. }
  35794. }
  35795. const _matrix41 = /*@__PURE__*/ new Matrix4();
  35796. const _matrix42 = /*@__PURE__*/ new Matrix4();
  35797. let _ltcLib = null;
  35798. /**
  35799. * Module for representing rect area lights as nodes.
  35800. *
  35801. * @augments AnalyticLightNode
  35802. */
  35803. class RectAreaLightNode extends AnalyticLightNode {
  35804. static get type() {
  35805. return 'RectAreaLightNode';
  35806. }
  35807. /**
  35808. * Constructs a new rect area light node.
  35809. *
  35810. * @param {?RectAreaLight} [light=null] - The rect area light source.
  35811. */
  35812. constructor( light = null ) {
  35813. super( light );
  35814. /**
  35815. * Uniform node representing the half height of the are light.
  35816. *
  35817. * @type {UniformNode<vec3>}
  35818. */
  35819. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  35820. /**
  35821. * Uniform node representing the half width of the are light.
  35822. *
  35823. * @type {UniformNode<vec3>}
  35824. */
  35825. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  35826. /**
  35827. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  35828. * relies on `viewMatrix` which might vary per render call.
  35829. *
  35830. * @type {string}
  35831. * @default 'render'
  35832. */
  35833. this.updateType = NodeUpdateType.RENDER;
  35834. }
  35835. /**
  35836. * Overwritten to updated rect area light specific uniforms.
  35837. *
  35838. * @param {NodeFrame} frame - A reference to the current node frame.
  35839. */
  35840. update( frame ) {
  35841. super.update( frame );
  35842. const { light } = this;
  35843. const viewMatrix = frame.camera.matrixWorldInverse;
  35844. _matrix42.identity();
  35845. _matrix41.copy( light.matrixWorld );
  35846. _matrix41.premultiply( viewMatrix );
  35847. _matrix42.extractRotation( _matrix41 );
  35848. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  35849. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  35850. this.halfWidth.value.applyMatrix4( _matrix42 );
  35851. this.halfHeight.value.applyMatrix4( _matrix42 );
  35852. }
  35853. setupDirectRectArea( builder ) {
  35854. let ltc_1, ltc_2;
  35855. if ( builder.isAvailable( 'float32Filterable' ) ) {
  35856. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  35857. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  35858. } else {
  35859. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  35860. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  35861. }
  35862. const { colorNode, light } = this;
  35863. const lightPosition = lightViewPosition( light );
  35864. return {
  35865. lightColor: colorNode,
  35866. lightPosition,
  35867. halfWidth: this.halfWidth,
  35868. halfHeight: this.halfHeight,
  35869. ltc_1,
  35870. ltc_2
  35871. };
  35872. }
  35873. /**
  35874. * Used to configure the internal BRDF approximation texture data.
  35875. *
  35876. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  35877. */
  35878. static setLTC( ltc ) {
  35879. _ltcLib = ltc;
  35880. }
  35881. }
  35882. /**
  35883. * Module for representing spot lights as nodes.
  35884. *
  35885. * @augments AnalyticLightNode
  35886. */
  35887. class SpotLightNode extends AnalyticLightNode {
  35888. static get type() {
  35889. return 'SpotLightNode';
  35890. }
  35891. /**
  35892. * Constructs a new spot light node.
  35893. *
  35894. * @param {?SpotLight} [light=null] - The spot light source.
  35895. */
  35896. constructor( light = null ) {
  35897. super( light );
  35898. /**
  35899. * Uniform node representing the cone cosine.
  35900. *
  35901. * @type {UniformNode<float>}
  35902. */
  35903. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  35904. /**
  35905. * Uniform node representing the penumbra cosine.
  35906. *
  35907. * @type {UniformNode<float>}
  35908. */
  35909. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  35910. /**
  35911. * Uniform node representing the cutoff distance.
  35912. *
  35913. * @type {UniformNode<float>}
  35914. */
  35915. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  35916. /**
  35917. * Uniform node representing the decay exponent.
  35918. *
  35919. * @type {UniformNode<float>}
  35920. */
  35921. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  35922. /**
  35923. * Uniform node representing the light color.
  35924. *
  35925. * @type {UniformNode<Color>}
  35926. */
  35927. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  35928. }
  35929. /**
  35930. * Overwritten to updated spot light specific uniforms.
  35931. *
  35932. * @param {NodeFrame} frame - A reference to the current node frame.
  35933. */
  35934. update( frame ) {
  35935. super.update( frame );
  35936. const { light } = this;
  35937. this.coneCosNode.value = Math.cos( light.angle );
  35938. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  35939. this.cutoffDistanceNode.value = light.distance;
  35940. this.decayExponentNode.value = light.decay;
  35941. }
  35942. /**
  35943. * Computes the spot attenuation for the given angle.
  35944. *
  35945. * @param {NodeBuilder} builder - The node builder.
  35946. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  35947. * @return {Node<float>} The spot attenuation.
  35948. */
  35949. getSpotAttenuation( builder, angleCosine ) {
  35950. const { coneCosNode, penumbraCosNode } = this;
  35951. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  35952. }
  35953. getLightCoord( builder ) {
  35954. const properties = builder.getNodeProperties( this );
  35955. let projectionUV = properties.projectionUV;
  35956. if ( projectionUV === undefined ) {
  35957. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  35958. properties.projectionUV = projectionUV;
  35959. }
  35960. return projectionUV;
  35961. }
  35962. setupDirect( builder ) {
  35963. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  35964. const lightVector = this.getLightVector( builder );
  35965. const lightDirection = lightVector.normalize();
  35966. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  35967. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  35968. const lightDistance = lightVector.length();
  35969. const lightAttenuation = getDistanceAttenuation( {
  35970. lightDistance,
  35971. cutoffDistance: cutoffDistanceNode,
  35972. decayExponent: decayExponentNode
  35973. } );
  35974. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  35975. let projected, lightCoord;
  35976. if ( light.colorNode ) {
  35977. lightCoord = this.getLightCoord( builder );
  35978. projected = light.colorNode( lightCoord );
  35979. } else if ( light.map ) {
  35980. lightCoord = this.getLightCoord( builder );
  35981. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  35982. }
  35983. if ( projected ) {
  35984. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  35985. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  35986. }
  35987. return { lightColor, lightDirection };
  35988. }
  35989. }
  35990. /**
  35991. * An IES version of the default spot light node.
  35992. *
  35993. * @augments SpotLightNode
  35994. */
  35995. class IESSpotLightNode extends SpotLightNode {
  35996. static get type() {
  35997. return 'IESSpotLightNode';
  35998. }
  35999. /**
  36000. * Overwrites the default implementation to compute an IES conform spot attenuation.
  36001. *
  36002. * @param {NodeBuilder} builder - The node builder.
  36003. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  36004. * @return {Node<float>} The spot attenuation.
  36005. */
  36006. getSpotAttenuation( builder, angleCosine ) {
  36007. const iesMap = this.light.iesMap;
  36008. let spotAttenuation = null;
  36009. if ( iesMap && iesMap.isTexture === true ) {
  36010. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36011. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36012. } else {
  36013. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36014. }
  36015. return spotAttenuation;
  36016. }
  36017. }
  36018. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  36019. const d = p.abs().sub( b );
  36020. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  36021. } );
  36022. /**
  36023. * An implementation of a projector light node.
  36024. *
  36025. * @augments SpotLightNode
  36026. */
  36027. class ProjectorLightNode extends SpotLightNode {
  36028. static get type() {
  36029. return 'ProjectorLightNode';
  36030. }
  36031. update( frame ) {
  36032. super.update( frame );
  36033. const light = this.light;
  36034. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  36035. if ( light.aspect === null ) {
  36036. let aspect = 1;
  36037. if ( light.map !== null ) {
  36038. aspect = light.map.width / light.map.height;
  36039. }
  36040. light.shadow.aspect = aspect;
  36041. } else {
  36042. light.shadow.aspect = light.aspect;
  36043. }
  36044. }
  36045. /**
  36046. * Overwrites the default implementation to compute projection attenuation.
  36047. *
  36048. * @param {NodeBuilder} builder - The node builder.
  36049. * @return {Node<float>} The spot attenuation.
  36050. */
  36051. getSpotAttenuation( builder ) {
  36052. const attenuation = float( 0 );
  36053. const penumbraCos = this.penumbraCosNode;
  36054. // compute the fragment's position in the light's clip space
  36055. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  36056. // the sign of w determines whether the current fragment is in front or behind the light.
  36057. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  36058. If( spotLightCoord.w.greaterThan( 0 ), () => {
  36059. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  36060. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  36061. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  36062. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  36063. } );
  36064. return attenuation;
  36065. }
  36066. }
  36067. /**
  36068. * Module for representing ambient lights as nodes.
  36069. *
  36070. * @augments AnalyticLightNode
  36071. */
  36072. class AmbientLightNode extends AnalyticLightNode {
  36073. static get type() {
  36074. return 'AmbientLightNode';
  36075. }
  36076. /**
  36077. * Constructs a new ambient light node.
  36078. *
  36079. * @param {?AmbientLight} [light=null] - The ambient light source.
  36080. */
  36081. constructor( light = null ) {
  36082. super( light );
  36083. }
  36084. setup( { context } ) {
  36085. context.irradiance.addAssign( this.colorNode );
  36086. }
  36087. }
  36088. /**
  36089. * Module for representing hemisphere lights as nodes.
  36090. *
  36091. * @augments AnalyticLightNode
  36092. */
  36093. class HemisphereLightNode extends AnalyticLightNode {
  36094. static get type() {
  36095. return 'HemisphereLightNode';
  36096. }
  36097. /**
  36098. * Constructs a new hemisphere light node.
  36099. *
  36100. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  36101. */
  36102. constructor( light = null ) {
  36103. super( light );
  36104. /**
  36105. * Uniform node representing the light's position.
  36106. *
  36107. * @type {UniformNode<vec3>}
  36108. */
  36109. this.lightPositionNode = lightPosition( light );
  36110. /**
  36111. * A node representing the light's direction.
  36112. *
  36113. * @type {Node<vec3>}
  36114. */
  36115. this.lightDirectionNode = this.lightPositionNode.normalize();
  36116. /**
  36117. * Uniform node representing the light's ground color.
  36118. *
  36119. * @type {UniformNode<vec3>}
  36120. */
  36121. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36122. }
  36123. /**
  36124. * Overwritten to updated hemisphere light specific uniforms.
  36125. *
  36126. * @param {NodeFrame} frame - A reference to the current node frame.
  36127. */
  36128. update( frame ) {
  36129. const { light } = this;
  36130. super.update( frame );
  36131. this.lightPositionNode.object3d = light;
  36132. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36133. }
  36134. setup( builder ) {
  36135. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36136. const dotNL = normalWorld.dot( lightDirectionNode );
  36137. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36138. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36139. builder.context.irradiance.addAssign( irradiance );
  36140. }
  36141. }
  36142. /**
  36143. * Module for representing light probes as nodes.
  36144. *
  36145. * @augments AnalyticLightNode
  36146. */
  36147. class LightProbeNode extends AnalyticLightNode {
  36148. static get type() {
  36149. return 'LightProbeNode';
  36150. }
  36151. /**
  36152. * Constructs a new light probe node.
  36153. *
  36154. * @param {?LightProbe} [light=null] - The light probe.
  36155. */
  36156. constructor( light = null ) {
  36157. super( light );
  36158. const array = [];
  36159. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36160. /**
  36161. * Light probe represented as a uniform of spherical harmonics.
  36162. *
  36163. * @type {UniformArrayNode}
  36164. */
  36165. this.lightProbe = uniformArray( array );
  36166. }
  36167. /**
  36168. * Overwritten to updated light probe specific uniforms.
  36169. *
  36170. * @param {NodeFrame} frame - A reference to the current node frame.
  36171. */
  36172. update( frame ) {
  36173. const { light } = this;
  36174. super.update( frame );
  36175. //
  36176. for ( let i = 0; i < 9; i ++ ) {
  36177. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36178. }
  36179. }
  36180. setup( builder ) {
  36181. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36182. builder.context.irradiance.addAssign( irradiance );
  36183. }
  36184. }
  36185. /**
  36186. * Base class for node parsers. A derived parser must be implemented
  36187. * for each supported native shader language.
  36188. */
  36189. class NodeParser {
  36190. /**
  36191. * The method parses the given native code an returns a node function.
  36192. *
  36193. * @abstract
  36194. * @param {string} source - The native shader code.
  36195. * @return {NodeFunction} A node function.
  36196. */
  36197. parseFunction( /*source*/ ) {
  36198. warn( 'Abstract function.' );
  36199. }
  36200. }
  36201. /**
  36202. * Base class for node functions. A derived module must be implemented
  36203. * for each supported native shader language. Similar to other `Node*` modules,
  36204. * this class is only relevant during the building process and not used
  36205. * in user-level code.
  36206. */
  36207. class NodeFunction {
  36208. /**
  36209. * Constructs a new node function.
  36210. *
  36211. * @param {string} type - The node type. This type is the return type of the node function.
  36212. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  36213. * @param {string} [name=''] - The function's name.
  36214. * @param {string} [precision=''] - The precision qualifier.
  36215. */
  36216. constructor( type, inputs, name = '', precision = '' ) {
  36217. /**
  36218. * The node type. This type is the return type of the node function.
  36219. *
  36220. * @type {string}
  36221. */
  36222. this.type = type;
  36223. /**
  36224. * The function's inputs.
  36225. *
  36226. * @type {Array<NodeFunctionInput>}
  36227. */
  36228. this.inputs = inputs;
  36229. /**
  36230. * The name of the uniform.
  36231. *
  36232. * @type {string}
  36233. * @default ''
  36234. */
  36235. this.name = name;
  36236. /**
  36237. * The precision qualifier.
  36238. *
  36239. * @type {string}
  36240. * @default ''
  36241. */
  36242. this.precision = precision;
  36243. }
  36244. /**
  36245. * This method returns the native code of the node function.
  36246. *
  36247. * @abstract
  36248. * @param {string} name - The function's name.
  36249. * @return {string} A shader code.
  36250. */
  36251. getCode( /*name = this.name*/ ) {
  36252. warn( 'Abstract function.' );
  36253. }
  36254. }
  36255. NodeFunction.isNodeFunction = true;
  36256. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36257. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36258. const pragmaMain = '#pragma main';
  36259. const parse$1 = ( source ) => {
  36260. source = source.trim();
  36261. const pragmaMainIndex = source.indexOf( pragmaMain );
  36262. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36263. const declaration = mainCode.match( declarationRegexp$1 );
  36264. if ( declaration !== null && declaration.length === 5 ) {
  36265. // tokenizer
  36266. const inputsCode = declaration[ 4 ];
  36267. const propsMatches = [];
  36268. let nameMatch = null;
  36269. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36270. propsMatches.push( nameMatch );
  36271. }
  36272. // parser
  36273. const inputs = [];
  36274. let i = 0;
  36275. while ( i < propsMatches.length ) {
  36276. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36277. if ( isConst === true ) {
  36278. i ++;
  36279. }
  36280. let qualifier = propsMatches[ i ][ 0 ];
  36281. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36282. i ++;
  36283. } else {
  36284. qualifier = '';
  36285. }
  36286. const type = propsMatches[ i ++ ][ 0 ];
  36287. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36288. if ( Number.isNaN( count ) === false ) i ++;
  36289. else count = null;
  36290. const name = propsMatches[ i ++ ][ 0 ];
  36291. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36292. }
  36293. //
  36294. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36295. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36296. const type = declaration[ 2 ];
  36297. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36298. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  36299. return {
  36300. type,
  36301. inputs,
  36302. name,
  36303. precision,
  36304. inputsCode,
  36305. blockCode,
  36306. headerCode
  36307. };
  36308. } else {
  36309. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36310. }
  36311. };
  36312. /**
  36313. * This class represents a GLSL node function.
  36314. *
  36315. * @augments NodeFunction
  36316. */
  36317. class GLSLNodeFunction extends NodeFunction {
  36318. /**
  36319. * Constructs a new GLSL node function.
  36320. *
  36321. * @param {string} source - The GLSL source.
  36322. */
  36323. constructor( source ) {
  36324. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36325. super( type, inputs, name, precision );
  36326. this.inputsCode = inputsCode;
  36327. this.blockCode = blockCode;
  36328. this.headerCode = headerCode;
  36329. }
  36330. /**
  36331. * This method returns the GLSL code of the node function.
  36332. *
  36333. * @param {string} [name=this.name] - The function's name.
  36334. * @return {string} The shader code.
  36335. */
  36336. getCode( name = this.name ) {
  36337. let code;
  36338. const blockCode = this.blockCode;
  36339. if ( blockCode !== '' ) {
  36340. const { type, inputsCode, headerCode, precision } = this;
  36341. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36342. if ( precision !== '' ) {
  36343. declarationCode = `${ precision } ${ declarationCode }`;
  36344. }
  36345. code = headerCode + declarationCode + blockCode;
  36346. } else {
  36347. // interface function
  36348. code = '';
  36349. }
  36350. return code;
  36351. }
  36352. }
  36353. /**
  36354. * A GLSL node parser.
  36355. *
  36356. * @augments NodeParser
  36357. */
  36358. class GLSLNodeParser extends NodeParser {
  36359. /**
  36360. * The method parses the given GLSL code an returns a node function.
  36361. *
  36362. * @param {string} source - The GLSL code.
  36363. * @return {GLSLNodeFunction} A node function.
  36364. */
  36365. parseFunction( source ) {
  36366. return new GLSLNodeFunction( source );
  36367. }
  36368. }
  36369. const _outputNodeMap = new WeakMap();
  36370. const _chainKeys$2 = [];
  36371. const _cacheKeyValues = [];
  36372. /**
  36373. * This renderer module manages node-related objects and is the
  36374. * primary interface between the renderer and the node system.
  36375. *
  36376. * @private
  36377. * @augments DataMap
  36378. */
  36379. class Nodes extends DataMap {
  36380. /**
  36381. * Constructs a new nodes management component.
  36382. *
  36383. * @param {Renderer} renderer - The renderer.
  36384. * @param {Backend} backend - The renderer's backend.
  36385. */
  36386. constructor( renderer, backend ) {
  36387. super();
  36388. /**
  36389. * The renderer.
  36390. *
  36391. * @type {Renderer}
  36392. */
  36393. this.renderer = renderer;
  36394. /**
  36395. * The renderer's backend.
  36396. *
  36397. * @type {Backend}
  36398. */
  36399. this.backend = backend;
  36400. /**
  36401. * The node frame.
  36402. *
  36403. * @type {Renderer}
  36404. */
  36405. this.nodeFrame = new NodeFrame();
  36406. /**
  36407. * A cache for managing node builder states.
  36408. *
  36409. * @type {Map<number,NodeBuilderState>}
  36410. */
  36411. this.nodeBuilderCache = new Map();
  36412. /**
  36413. * A cache for managing data cache key data.
  36414. *
  36415. * @type {ChainMap}
  36416. */
  36417. this.callHashCache = new ChainMap();
  36418. /**
  36419. * A cache for managing node uniforms group data.
  36420. *
  36421. * @type {ChainMap}
  36422. */
  36423. this.groupsData = new ChainMap();
  36424. /**
  36425. * A cache for managing node objects of
  36426. * scene properties like fog or environments.
  36427. *
  36428. * @type {Object<string,WeakMap>}
  36429. */
  36430. this.cacheLib = {};
  36431. }
  36432. /**
  36433. * Returns `true` if the given node uniforms group must be updated or not.
  36434. *
  36435. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  36436. * @return {boolean} Whether the node uniforms group requires an update or not.
  36437. */
  36438. updateGroup( nodeUniformsGroup ) {
  36439. const groupNode = nodeUniformsGroup.groupNode;
  36440. const name = groupNode.name;
  36441. // objectGroup is always updated
  36442. if ( name === objectGroup.name ) return true;
  36443. // renderGroup is updated once per render/compute call
  36444. if ( name === renderGroup.name ) {
  36445. const uniformsGroupData = this.get( nodeUniformsGroup );
  36446. const renderId = this.nodeFrame.renderId;
  36447. if ( uniformsGroupData.renderId !== renderId ) {
  36448. uniformsGroupData.renderId = renderId;
  36449. return true;
  36450. }
  36451. return false;
  36452. }
  36453. // frameGroup is updated once per frame
  36454. if ( name === frameGroup.name ) {
  36455. const uniformsGroupData = this.get( nodeUniformsGroup );
  36456. const frameId = this.nodeFrame.frameId;
  36457. if ( uniformsGroupData.frameId !== frameId ) {
  36458. uniformsGroupData.frameId = frameId;
  36459. return true;
  36460. }
  36461. return false;
  36462. }
  36463. // other groups are updated just when groupNode.needsUpdate is true
  36464. _chainKeys$2[ 0 ] = groupNode;
  36465. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  36466. let groupData = this.groupsData.get( _chainKeys$2 );
  36467. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  36468. _chainKeys$2.length = 0;
  36469. if ( groupData.version !== groupNode.version ) {
  36470. groupData.version = groupNode.version;
  36471. return true;
  36472. }
  36473. return false;
  36474. }
  36475. /**
  36476. * Returns the cache key for the given render object.
  36477. *
  36478. * @param {RenderObject} renderObject - The render object.
  36479. * @return {number} The cache key.
  36480. */
  36481. getForRenderCacheKey( renderObject ) {
  36482. return renderObject.initialCacheKey;
  36483. }
  36484. /**
  36485. * Returns a node builder state for the given render object.
  36486. *
  36487. * @param {RenderObject} renderObject - The render object.
  36488. * @return {NodeBuilderState} The node builder state.
  36489. */
  36490. getForRender( renderObject ) {
  36491. const renderObjectData = this.get( renderObject );
  36492. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36493. if ( nodeBuilderState === undefined ) {
  36494. const { nodeBuilderCache } = this;
  36495. const cacheKey = this.getForRenderCacheKey( renderObject );
  36496. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36497. if ( nodeBuilderState === undefined ) {
  36498. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36499. nodeBuilder.scene = renderObject.scene;
  36500. nodeBuilder.material = renderObject.material;
  36501. nodeBuilder.camera = renderObject.camera;
  36502. nodeBuilder.context.material = renderObject.material;
  36503. nodeBuilder.lightsNode = renderObject.lightsNode;
  36504. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36505. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36506. nodeBuilder.clippingContext = renderObject.clippingContext;
  36507. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  36508. nodeBuilder.enableMultiview();
  36509. }
  36510. nodeBuilder.build();
  36511. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36512. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  36513. }
  36514. nodeBuilderState.usedTimes ++;
  36515. renderObjectData.nodeBuilderState = nodeBuilderState;
  36516. }
  36517. return nodeBuilderState;
  36518. }
  36519. /**
  36520. * Deletes the given object from the internal data map
  36521. *
  36522. * @param {any} object - The object to delete.
  36523. * @return {?Object} The deleted dictionary.
  36524. */
  36525. delete( object ) {
  36526. if ( object.isRenderObject ) {
  36527. const nodeBuilderState = this.get( object ).nodeBuilderState;
  36528. nodeBuilderState.usedTimes --;
  36529. if ( nodeBuilderState.usedTimes === 0 ) {
  36530. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  36531. }
  36532. }
  36533. return super.delete( object );
  36534. }
  36535. /**
  36536. * Returns a node builder state for the given compute node.
  36537. *
  36538. * @param {Node} computeNode - The compute node.
  36539. * @return {NodeBuilderState} The node builder state.
  36540. */
  36541. getForCompute( computeNode ) {
  36542. const computeData = this.get( computeNode );
  36543. let nodeBuilderState = computeData.nodeBuilderState;
  36544. if ( nodeBuilderState === undefined ) {
  36545. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  36546. nodeBuilder.build();
  36547. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36548. computeData.nodeBuilderState = nodeBuilderState;
  36549. }
  36550. return nodeBuilderState;
  36551. }
  36552. /**
  36553. * Creates a node builder state for the given node builder.
  36554. *
  36555. * @private
  36556. * @param {NodeBuilder} nodeBuilder - The node builder.
  36557. * @return {NodeBuilderState} The node builder state.
  36558. */
  36559. _createNodeBuilderState( nodeBuilder ) {
  36560. return new NodeBuilderState(
  36561. nodeBuilder.vertexShader,
  36562. nodeBuilder.fragmentShader,
  36563. nodeBuilder.computeShader,
  36564. nodeBuilder.getAttributesArray(),
  36565. nodeBuilder.getBindings(),
  36566. nodeBuilder.updateNodes,
  36567. nodeBuilder.updateBeforeNodes,
  36568. nodeBuilder.updateAfterNodes,
  36569. nodeBuilder.observer,
  36570. nodeBuilder.transforms
  36571. );
  36572. }
  36573. /**
  36574. * Returns an environment node for the current configured
  36575. * scene environment.
  36576. *
  36577. * @param {Scene} scene - The scene.
  36578. * @return {Node} A node representing the current scene environment.
  36579. */
  36580. getEnvironmentNode( scene ) {
  36581. this.updateEnvironment( scene );
  36582. let environmentNode = null;
  36583. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  36584. environmentNode = scene.environmentNode;
  36585. } else {
  36586. const sceneData = this.get( scene );
  36587. if ( sceneData.environmentNode ) {
  36588. environmentNode = sceneData.environmentNode;
  36589. }
  36590. }
  36591. return environmentNode;
  36592. }
  36593. /**
  36594. * Returns a background node for the current configured
  36595. * scene background.
  36596. *
  36597. * @param {Scene} scene - The scene.
  36598. * @return {Node} A node representing the current scene background.
  36599. */
  36600. getBackgroundNode( scene ) {
  36601. this.updateBackground( scene );
  36602. let backgroundNode = null;
  36603. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  36604. backgroundNode = scene.backgroundNode;
  36605. } else {
  36606. const sceneData = this.get( scene );
  36607. if ( sceneData.backgroundNode ) {
  36608. backgroundNode = sceneData.backgroundNode;
  36609. }
  36610. }
  36611. return backgroundNode;
  36612. }
  36613. /**
  36614. * Returns a fog node for the current configured scene fog.
  36615. *
  36616. * @param {Scene} scene - The scene.
  36617. * @return {Node} A node representing the current scene fog.
  36618. */
  36619. getFogNode( scene ) {
  36620. this.updateFog( scene );
  36621. return scene.fogNode || this.get( scene ).fogNode || null;
  36622. }
  36623. /**
  36624. * Returns a cache key for the given scene and lights node.
  36625. * This key is used by `RenderObject` as a part of the dynamic
  36626. * cache key (a key that must be checked every time the render
  36627. * objects is drawn).
  36628. *
  36629. * @param {Scene} scene - The scene.
  36630. * @param {LightsNode} lightsNode - The lights node.
  36631. * @return {number} The cache key.
  36632. */
  36633. getCacheKey( scene, lightsNode ) {
  36634. _chainKeys$2[ 0 ] = scene;
  36635. _chainKeys$2[ 1 ] = lightsNode;
  36636. const callId = this.renderer.info.calls;
  36637. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  36638. if ( cacheKeyData.callId !== callId ) {
  36639. const environmentNode = this.getEnvironmentNode( scene );
  36640. const fogNode = this.getFogNode( scene );
  36641. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  36642. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  36643. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  36644. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  36645. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  36646. cacheKeyData.callId = callId;
  36647. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  36648. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  36649. _cacheKeyValues.length = 0;
  36650. }
  36651. _chainKeys$2.length = 0;
  36652. return cacheKeyData.cacheKey;
  36653. }
  36654. /**
  36655. * A boolean that indicates whether tone mapping should be enabled
  36656. * or not.
  36657. *
  36658. * @type {boolean}
  36659. */
  36660. get isToneMappingState() {
  36661. return this.renderer.getRenderTarget() ? false : true;
  36662. }
  36663. /**
  36664. * If a scene background is configured, this method makes sure to
  36665. * represent the background with a corresponding node-based implementation.
  36666. *
  36667. * @param {Scene} scene - The scene.
  36668. */
  36669. updateBackground( scene ) {
  36670. const sceneData = this.get( scene );
  36671. const background = scene.background;
  36672. if ( background ) {
  36673. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  36674. if ( sceneData.background !== background || forceUpdate ) {
  36675. const backgroundNode = this.getCacheNode( 'background', background, () => {
  36676. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  36677. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  36678. return pmremTexture( background );
  36679. } else {
  36680. let envMap;
  36681. if ( background.isCubeTexture === true ) {
  36682. envMap = cubeTexture( background );
  36683. } else {
  36684. envMap = texture( background );
  36685. }
  36686. return cubeMapNode( envMap );
  36687. }
  36688. } else if ( background.isTexture === true ) {
  36689. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  36690. } else if ( background.isColor !== true ) {
  36691. error( 'WebGPUNodes: Unsupported background configuration.', background );
  36692. }
  36693. }, forceUpdate );
  36694. sceneData.backgroundNode = backgroundNode;
  36695. sceneData.background = background;
  36696. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  36697. }
  36698. } else if ( sceneData.backgroundNode ) {
  36699. delete sceneData.backgroundNode;
  36700. delete sceneData.background;
  36701. }
  36702. }
  36703. /**
  36704. * This method is part of the caching of nodes which are used to represents the
  36705. * scene's background, fog or environment.
  36706. *
  36707. * @param {string} type - The type of object to cache.
  36708. * @param {Object} object - The object.
  36709. * @param {Function} callback - A callback that produces a node representation for the given object.
  36710. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  36711. * @return {Node} The node representation.
  36712. */
  36713. getCacheNode( type, object, callback, forceUpdate = false ) {
  36714. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  36715. let node = nodeCache.get( object );
  36716. if ( node === undefined || forceUpdate ) {
  36717. node = callback();
  36718. nodeCache.set( object, node );
  36719. }
  36720. return node;
  36721. }
  36722. /**
  36723. * If a scene fog is configured, this method makes sure to
  36724. * represent the fog with a corresponding node-based implementation.
  36725. *
  36726. * @param {Scene} scene - The scene.
  36727. */
  36728. updateFog( scene ) {
  36729. const sceneData = this.get( scene );
  36730. const sceneFog = scene.fog;
  36731. if ( sceneFog ) {
  36732. if ( sceneData.fog !== sceneFog ) {
  36733. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  36734. if ( sceneFog.isFogExp2 ) {
  36735. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36736. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  36737. return fog( color, densityFogFactor( density ) );
  36738. } else if ( sceneFog.isFog ) {
  36739. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36740. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  36741. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  36742. return fog( color, rangeFogFactor( near, far ) );
  36743. } else {
  36744. error( 'Renderer: Unsupported fog configuration.', sceneFog );
  36745. }
  36746. } );
  36747. sceneData.fogNode = fogNode;
  36748. sceneData.fog = sceneFog;
  36749. }
  36750. } else {
  36751. delete sceneData.fogNode;
  36752. delete sceneData.fog;
  36753. }
  36754. }
  36755. /**
  36756. * If a scene environment is configured, this method makes sure to
  36757. * represent the environment with a corresponding node-based implementation.
  36758. *
  36759. * @param {Scene} scene - The scene.
  36760. */
  36761. updateEnvironment( scene ) {
  36762. const sceneData = this.get( scene );
  36763. const environment = scene.environment;
  36764. if ( environment ) {
  36765. if ( sceneData.environment !== environment ) {
  36766. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  36767. if ( environment.isCubeTexture === true ) {
  36768. return cubeTexture( environment );
  36769. } else if ( environment.isTexture === true ) {
  36770. return texture( environment );
  36771. } else {
  36772. error( 'Nodes: Unsupported environment configuration.', environment );
  36773. }
  36774. } );
  36775. sceneData.environmentNode = environmentNode;
  36776. sceneData.environment = environment;
  36777. }
  36778. } else if ( sceneData.environmentNode ) {
  36779. delete sceneData.environmentNode;
  36780. delete sceneData.environment;
  36781. }
  36782. }
  36783. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  36784. const nodeFrame = this.nodeFrame;
  36785. nodeFrame.renderer = renderer;
  36786. nodeFrame.scene = scene;
  36787. nodeFrame.object = object;
  36788. nodeFrame.camera = camera;
  36789. nodeFrame.material = material;
  36790. return nodeFrame;
  36791. }
  36792. getNodeFrameForRender( renderObject ) {
  36793. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  36794. }
  36795. /**
  36796. * Returns the current output cache key.
  36797. *
  36798. * @return {string} The output cache key.
  36799. */
  36800. getOutputCacheKey() {
  36801. const renderer = this.renderer;
  36802. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  36803. }
  36804. /**
  36805. * Checks if the output configuration (tone mapping and color space) for
  36806. * the given target has changed.
  36807. *
  36808. * @param {Texture} outputTarget - The output target.
  36809. * @return {boolean} Whether the output configuration has changed or not.
  36810. */
  36811. hasOutputChange( outputTarget ) {
  36812. const cacheKey = _outputNodeMap.get( outputTarget );
  36813. return cacheKey !== this.getOutputCacheKey();
  36814. }
  36815. /**
  36816. * Returns a node that represents the output configuration (tone mapping and
  36817. * color space) for the current target.
  36818. *
  36819. * @param {Texture} outputTarget - The output target.
  36820. * @return {Node} The output node.
  36821. */
  36822. getOutputNode( outputTarget ) {
  36823. const renderer = this.renderer;
  36824. const cacheKey = this.getOutputCacheKey();
  36825. const output = outputTarget.isArrayTexture ?
  36826. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  36827. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  36828. _outputNodeMap.set( outputTarget, cacheKey );
  36829. return output;
  36830. }
  36831. /**
  36832. * Triggers the call of `updateBefore()` methods
  36833. * for all nodes of the given render object.
  36834. *
  36835. * @param {RenderObject} renderObject - The render object.
  36836. */
  36837. updateBefore( renderObject ) {
  36838. const nodeBuilder = renderObject.getNodeBuilderState();
  36839. for ( const node of nodeBuilder.updateBeforeNodes ) {
  36840. // update frame state for each node
  36841. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  36842. }
  36843. }
  36844. /**
  36845. * Triggers the call of `updateAfter()` methods
  36846. * for all nodes of the given render object.
  36847. *
  36848. * @param {RenderObject} renderObject - The render object.
  36849. */
  36850. updateAfter( renderObject ) {
  36851. const nodeBuilder = renderObject.getNodeBuilderState();
  36852. for ( const node of nodeBuilder.updateAfterNodes ) {
  36853. // update frame state for each node
  36854. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  36855. }
  36856. }
  36857. /**
  36858. * Triggers the call of `update()` methods
  36859. * for all nodes of the given compute node.
  36860. *
  36861. * @param {Node} computeNode - The compute node.
  36862. */
  36863. updateForCompute( computeNode ) {
  36864. const nodeFrame = this.getNodeFrame();
  36865. const nodeBuilder = this.getForCompute( computeNode );
  36866. for ( const node of nodeBuilder.updateNodes ) {
  36867. nodeFrame.updateNode( node );
  36868. }
  36869. }
  36870. /**
  36871. * Triggers the call of `update()` methods
  36872. * for all nodes of the given compute node.
  36873. *
  36874. * @param {RenderObject} renderObject - The render object.
  36875. */
  36876. updateForRender( renderObject ) {
  36877. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36878. const nodeBuilder = renderObject.getNodeBuilderState();
  36879. for ( const node of nodeBuilder.updateNodes ) {
  36880. nodeFrame.updateNode( node );
  36881. }
  36882. }
  36883. /**
  36884. * Returns `true` if the given render object requires a refresh.
  36885. *
  36886. * @param {RenderObject} renderObject - The render object.
  36887. * @return {boolean} Whether the given render object requires a refresh or not.
  36888. */
  36889. needsRefresh( renderObject ) {
  36890. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36891. const monitor = renderObject.getMonitor();
  36892. return monitor.needsRefresh( renderObject, nodeFrame );
  36893. }
  36894. /**
  36895. * Frees the internal resources.
  36896. */
  36897. dispose() {
  36898. super.dispose();
  36899. this.nodeFrame = new NodeFrame();
  36900. this.nodeBuilderCache = new Map();
  36901. this.cacheLib = {};
  36902. }
  36903. }
  36904. const _plane = /*@__PURE__*/ new Plane();
  36905. /**
  36906. * Represents the state that is used to perform clipping via clipping planes.
  36907. * There is a default clipping context for each render context. When the
  36908. * scene holds instances of `ClippingGroup`, there will be a context for each
  36909. * group.
  36910. *
  36911. * @private
  36912. */
  36913. class ClippingContext {
  36914. /**
  36915. * Constructs a new clipping context.
  36916. *
  36917. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  36918. */
  36919. constructor( parentContext = null ) {
  36920. /**
  36921. * The clipping context's version.
  36922. *
  36923. * @type {number}
  36924. * @readonly
  36925. */
  36926. this.version = 0;
  36927. /**
  36928. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  36929. *
  36930. * @type {?boolean}
  36931. * @default null
  36932. */
  36933. this.clipIntersection = null;
  36934. /**
  36935. * The clipping context's cache key.
  36936. *
  36937. * @type {string}
  36938. */
  36939. this.cacheKey = '';
  36940. /**
  36941. * Whether the shadow pass is active or not.
  36942. *
  36943. * @type {boolean}
  36944. * @default false
  36945. */
  36946. this.shadowPass = false;
  36947. /**
  36948. * The view normal matrix.
  36949. *
  36950. * @type {Matrix3}
  36951. */
  36952. this.viewNormalMatrix = new Matrix3();
  36953. /**
  36954. * Internal cache for maintaining clipping contexts.
  36955. *
  36956. * @type {WeakMap<ClippingGroup,ClippingContext>}
  36957. */
  36958. this.clippingGroupContexts = new WeakMap();
  36959. /**
  36960. * The intersection planes.
  36961. *
  36962. * @type {Array<Vector4>}
  36963. */
  36964. this.intersectionPlanes = [];
  36965. /**
  36966. * The intersection planes.
  36967. *
  36968. * @type {Array<Vector4>}
  36969. */
  36970. this.unionPlanes = [];
  36971. /**
  36972. * The version of the clipping context's parent context.
  36973. *
  36974. * @type {?number}
  36975. * @readonly
  36976. */
  36977. this.parentVersion = null;
  36978. if ( parentContext !== null ) {
  36979. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  36980. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  36981. this.shadowPass = parentContext.shadowPass;
  36982. this.viewMatrix = parentContext.viewMatrix;
  36983. }
  36984. }
  36985. /**
  36986. * Projects the given source clipping planes and writes the result into the
  36987. * destination array.
  36988. *
  36989. * @param {Array<Plane>} source - The source clipping planes.
  36990. * @param {Array<Vector4>} destination - The destination.
  36991. * @param {number} offset - The offset.
  36992. */
  36993. projectPlanes( source, destination, offset ) {
  36994. const l = source.length;
  36995. for ( let i = 0; i < l; i ++ ) {
  36996. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  36997. const v = destination[ offset + i ];
  36998. const normal = _plane.normal;
  36999. v.x = - normal.x;
  37000. v.y = - normal.y;
  37001. v.z = - normal.z;
  37002. v.w = _plane.constant;
  37003. }
  37004. }
  37005. /**
  37006. * Updates the root clipping context of a scene.
  37007. *
  37008. * @param {Scene} scene - The scene.
  37009. * @param {Camera} camera - The camera that is used to render the scene.
  37010. */
  37011. updateGlobal( scene, camera ) {
  37012. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  37013. this.viewMatrix = camera.matrixWorldInverse;
  37014. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  37015. }
  37016. /**
  37017. * Updates the clipping context.
  37018. *
  37019. * @param {ClippingContext} parentContext - The parent context.
  37020. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  37021. */
  37022. update( parentContext, clippingGroup ) {
  37023. let update = false;
  37024. if ( parentContext.version !== this.parentVersion ) {
  37025. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  37026. this.unionPlanes = Array.from( parentContext.unionPlanes );
  37027. this.parentVersion = parentContext.version;
  37028. }
  37029. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  37030. this.clipIntersection = clippingGroup.clipIntersection;
  37031. if ( this.clipIntersection ) {
  37032. this.unionPlanes.length = parentContext.unionPlanes.length;
  37033. } else {
  37034. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  37035. }
  37036. }
  37037. const srcClippingPlanes = clippingGroup.clippingPlanes;
  37038. const l = srcClippingPlanes.length;
  37039. let dstClippingPlanes;
  37040. let offset;
  37041. if ( this.clipIntersection ) {
  37042. dstClippingPlanes = this.intersectionPlanes;
  37043. offset = parentContext.intersectionPlanes.length;
  37044. } else {
  37045. dstClippingPlanes = this.unionPlanes;
  37046. offset = parentContext.unionPlanes.length;
  37047. }
  37048. if ( dstClippingPlanes.length !== offset + l ) {
  37049. dstClippingPlanes.length = offset + l;
  37050. for ( let i = 0; i < l; i ++ ) {
  37051. dstClippingPlanes[ offset + i ] = new Vector4();
  37052. }
  37053. update = true;
  37054. }
  37055. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  37056. if ( update ) {
  37057. this.version ++;
  37058. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  37059. }
  37060. }
  37061. /**
  37062. * Returns a clipping context for the given clipping group.
  37063. *
  37064. * @param {ClippingGroup} clippingGroup - The clipping group.
  37065. * @return {ClippingContext} The clipping context.
  37066. */
  37067. getGroupContext( clippingGroup ) {
  37068. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  37069. let context = this.clippingGroupContexts.get( clippingGroup );
  37070. if ( context === undefined ) {
  37071. context = new ClippingContext( this );
  37072. this.clippingGroupContexts.set( clippingGroup, context );
  37073. }
  37074. context.update( this, clippingGroup );
  37075. return context;
  37076. }
  37077. /**
  37078. * The count of union clipping planes.
  37079. *
  37080. * @type {number}
  37081. * @readonly
  37082. */
  37083. get unionClippingCount() {
  37084. return this.unionPlanes.length;
  37085. }
  37086. }
  37087. /**
  37088. * This module is used to represent render bundles inside the renderer
  37089. * for further processing.
  37090. *
  37091. * @private
  37092. */
  37093. class RenderBundle {
  37094. /**
  37095. * Constructs a new bundle group.
  37096. *
  37097. * @param {BundleGroup} bundleGroup - The bundle group.
  37098. * @param {Camera} camera - The camera the bundle group is rendered with.
  37099. */
  37100. constructor( bundleGroup, camera ) {
  37101. this.bundleGroup = bundleGroup;
  37102. this.camera = camera;
  37103. }
  37104. }
  37105. const _chainKeys$1 = [];
  37106. /**
  37107. * This renderer module manages render bundles.
  37108. *
  37109. * @private
  37110. */
  37111. class RenderBundles {
  37112. /**
  37113. * Constructs a new render bundle management component.
  37114. */
  37115. constructor() {
  37116. /**
  37117. * A chain map for maintaining the render bundles.
  37118. *
  37119. * @type {ChainMap}
  37120. */
  37121. this.bundles = new ChainMap();
  37122. }
  37123. /**
  37124. * Returns a render bundle for the given bundle group and camera.
  37125. *
  37126. * @param {BundleGroup} bundleGroup - The bundle group.
  37127. * @param {Camera} camera - The camera the bundle group is rendered with.
  37128. * @return {RenderBundle} The render bundle.
  37129. */
  37130. get( bundleGroup, camera ) {
  37131. const bundles = this.bundles;
  37132. _chainKeys$1[ 0 ] = bundleGroup;
  37133. _chainKeys$1[ 1 ] = camera;
  37134. let bundle = bundles.get( _chainKeys$1 );
  37135. if ( bundle === undefined ) {
  37136. bundle = new RenderBundle( bundleGroup, camera );
  37137. bundles.set( _chainKeys$1, bundle );
  37138. }
  37139. _chainKeys$1.length = 0;
  37140. return bundle;
  37141. }
  37142. /**
  37143. * Frees all internal resources.
  37144. */
  37145. dispose() {
  37146. this.bundles = new ChainMap();
  37147. }
  37148. }
  37149. /**
  37150. * The purpose of a node library is to assign node implementations
  37151. * to existing library features. In `WebGPURenderer` lights, materials
  37152. * which are not based on `NodeMaterial` as well as tone mapping techniques
  37153. * are implemented with node-based modules.
  37154. *
  37155. * @private
  37156. */
  37157. class NodeLibrary {
  37158. /**
  37159. * Constructs a new node library.
  37160. */
  37161. constructor() {
  37162. /**
  37163. * A weak map that maps lights to light nodes.
  37164. *
  37165. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  37166. */
  37167. this.lightNodes = new WeakMap();
  37168. /**
  37169. * A map that maps materials to node materials.
  37170. *
  37171. * @type {Map<string,NodeMaterial.constructor>}
  37172. */
  37173. this.materialNodes = new Map();
  37174. /**
  37175. * A map that maps tone mapping techniques (constants)
  37176. * to tone mapping node functions.
  37177. *
  37178. * @type {Map<number,Function>}
  37179. */
  37180. this.toneMappingNodes = new Map();
  37181. }
  37182. /**
  37183. * Returns a matching node material instance for the given material object.
  37184. *
  37185. * This method also assigns/copies the properties of the given material object
  37186. * to the node material. This is done to make sure the current material
  37187. * configuration carries over to the node version.
  37188. *
  37189. * @param {Material} material - A material.
  37190. * @return {NodeMaterial} The corresponding node material.
  37191. */
  37192. fromMaterial( material ) {
  37193. if ( material.isNodeMaterial ) return material;
  37194. let nodeMaterial = null;
  37195. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37196. if ( nodeMaterialClass !== null ) {
  37197. nodeMaterial = new nodeMaterialClass();
  37198. for ( const key in material ) {
  37199. nodeMaterial[ key ] = material[ key ];
  37200. }
  37201. }
  37202. return nodeMaterial;
  37203. }
  37204. /**
  37205. * Adds a tone mapping node function for a tone mapping technique (constant).
  37206. *
  37207. * @param {Function} toneMappingNode - The tone mapping node function.
  37208. * @param {number} toneMapping - The tone mapping.
  37209. */
  37210. addToneMapping( toneMappingNode, toneMapping ) {
  37211. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37212. }
  37213. /**
  37214. * Returns a tone mapping node function for a tone mapping technique (constant).
  37215. *
  37216. * @param {number} toneMapping - The tone mapping.
  37217. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  37218. */
  37219. getToneMappingFunction( toneMapping ) {
  37220. return this.toneMappingNodes.get( toneMapping ) || null;
  37221. }
  37222. /**
  37223. * Returns a node material class definition for a material type.
  37224. *
  37225. * @param {string} materialType - The material type.
  37226. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  37227. */
  37228. getMaterialNodeClass( materialType ) {
  37229. return this.materialNodes.get( materialType ) || null;
  37230. }
  37231. /**
  37232. * Adds a node material class definition for a given material type.
  37233. *
  37234. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  37235. * @param {string} materialClassType - The material type.
  37236. */
  37237. addMaterial( materialNodeClass, materialClassType ) {
  37238. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  37239. }
  37240. /**
  37241. * Returns a light node class definition for a light class definition.
  37242. *
  37243. * @param {Light.constructor} light - The light class definition.
  37244. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  37245. */
  37246. getLightNodeClass( light ) {
  37247. return this.lightNodes.get( light ) || null;
  37248. }
  37249. /**
  37250. * Adds a light node class definition for a given light class definition.
  37251. *
  37252. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  37253. * @param {Light.constructor} lightClass - The light class definition.
  37254. */
  37255. addLight( lightNodeClass, lightClass ) {
  37256. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37257. }
  37258. /**
  37259. * Adds a node class definition for the given type to the provided type library.
  37260. *
  37261. * @param {Node.constructor} nodeClass - The node class definition.
  37262. * @param {number|string} type - The object type.
  37263. * @param {Map<number|string,Node.constructor>} library - The type library.
  37264. */
  37265. addType( nodeClass, type, library ) {
  37266. if ( library.has( type ) ) {
  37267. warn( `Redefinition of node ${ type }` );
  37268. return;
  37269. }
  37270. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37271. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37272. library.set( type, nodeClass );
  37273. }
  37274. /**
  37275. * Adds a node class definition for the given class definition to the provided type library.
  37276. *
  37277. * @param {Node.constructor} nodeClass - The node class definition.
  37278. * @param {Node.constructor} baseClass - The class definition.
  37279. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  37280. */
  37281. addClass( nodeClass, baseClass, library ) {
  37282. if ( library.has( baseClass ) ) {
  37283. warn( `Redefinition of node ${ baseClass.name }` );
  37284. return;
  37285. }
  37286. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37287. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37288. library.set( baseClass, nodeClass );
  37289. }
  37290. }
  37291. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37292. const _chainKeys = [];
  37293. /**
  37294. * This renderer module manages the lights nodes which are unique
  37295. * per scene and camera combination.
  37296. *
  37297. * The lights node itself is later configured in the render list
  37298. * with the actual lights from the scene.
  37299. *
  37300. * @private
  37301. * @augments ChainMap
  37302. */
  37303. class Lighting extends ChainMap {
  37304. /**
  37305. * Constructs a lighting management component.
  37306. */
  37307. constructor() {
  37308. super();
  37309. }
  37310. /**
  37311. * Creates a new lights node for the given array of lights.
  37312. *
  37313. * @param {Array<Light>} lights - The render object.
  37314. * @return {LightsNode} The lights node.
  37315. */
  37316. createNode( lights = [] ) {
  37317. return new LightsNode().setLights( lights );
  37318. }
  37319. /**
  37320. * Returns a lights node for the given scene and camera.
  37321. *
  37322. * @param {Scene} scene - The scene.
  37323. * @param {Camera} camera - The camera.
  37324. * @return {LightsNode} The lights node.
  37325. */
  37326. getNode( scene, camera ) {
  37327. // ignore post-processing
  37328. if ( scene.isQuadMesh ) return _defaultLights;
  37329. _chainKeys[ 0 ] = scene;
  37330. _chainKeys[ 1 ] = camera;
  37331. let node = this.get( _chainKeys );
  37332. if ( node === undefined ) {
  37333. node = this.createNode();
  37334. this.set( _chainKeys, node );
  37335. }
  37336. _chainKeys.length = 0;
  37337. return node;
  37338. }
  37339. }
  37340. /**
  37341. * A special type of render target that is used when rendering
  37342. * with the WebXR Device API.
  37343. *
  37344. * @private
  37345. * @augments RenderTarget
  37346. */
  37347. class XRRenderTarget extends RenderTarget {
  37348. /**
  37349. * Constructs a new XR render target.
  37350. *
  37351. * @param {number} [width=1] - The width of the render target.
  37352. * @param {number} [height=1] - The height of the render target.
  37353. * @param {Object} [options={}] - The configuration options.
  37354. */
  37355. constructor( width = 1, height = 1, options = {} ) {
  37356. super( width, height, options );
  37357. /**
  37358. * This flag can be used for type testing.
  37359. *
  37360. * @type {boolean}
  37361. * @readonly
  37362. * @default true
  37363. */
  37364. this.isXRRenderTarget = true;
  37365. /**
  37366. * Whether the attachments of the render target
  37367. * are defined by external textures. This flag is
  37368. * set to `true` when using the WebXR Layers API.
  37369. *
  37370. * @private
  37371. * @type {boolean}
  37372. * @default false
  37373. */
  37374. this._hasExternalTextures = false;
  37375. /**
  37376. * Whether a depth buffer should automatically be allocated
  37377. * for this XR render target or not.
  37378. *
  37379. * Allocating a depth buffer is the default behavior of XR render
  37380. * targets. However, when using the WebXR Layers API, this flag
  37381. * must be set to `false` when the `ignoreDepthValues` property of
  37382. * the projection layers evaluates to `false`.
  37383. *
  37384. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  37385. *
  37386. * @private
  37387. * @type {boolean}
  37388. * @default true
  37389. */
  37390. this._autoAllocateDepthBuffer = true;
  37391. /**
  37392. * Whether this render target is associated with a XRWebGLLayer.
  37393. *
  37394. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  37395. * this means that you don't have access to its bound color,
  37396. * stencil and depth buffers. We need to handle this framebuffer
  37397. * differently since its textures are always bound.
  37398. *
  37399. * @private
  37400. * @type {boolean}
  37401. * @default false
  37402. * */
  37403. this._isOpaqueFramebuffer = false;
  37404. }
  37405. copy( source ) {
  37406. super.copy( source );
  37407. this._hasExternalTextures = source._hasExternalTextures;
  37408. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  37409. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  37410. return this;
  37411. }
  37412. }
  37413. const _cameraLPos = /*@__PURE__*/ new Vector3();
  37414. const _cameraRPos = /*@__PURE__*/ new Vector3();
  37415. /**
  37416. * The XR manager is built on top of the WebXR Device API to
  37417. * manage XR sessions with `WebGPURenderer`.
  37418. *
  37419. * XR is currently only supported with a WebGL 2 backend.
  37420. *
  37421. * @augments EventDispatcher
  37422. */
  37423. class XRManager extends EventDispatcher {
  37424. /**
  37425. * Constructs a new XR manager.
  37426. *
  37427. * @param {Renderer} renderer - The renderer.
  37428. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  37429. */
  37430. constructor( renderer, multiview = false ) {
  37431. super();
  37432. /**
  37433. * This flag globally enables XR rendering.
  37434. *
  37435. * @type {boolean}
  37436. * @default false
  37437. */
  37438. this.enabled = false;
  37439. /**
  37440. * Whether the XR device is currently presenting or not.
  37441. *
  37442. * @type {boolean}
  37443. * @default false
  37444. * @readonly
  37445. */
  37446. this.isPresenting = false;
  37447. /**
  37448. * Whether the XR camera should automatically be updated or not.
  37449. *
  37450. * @type {boolean}
  37451. * @default true
  37452. */
  37453. this.cameraAutoUpdate = true;
  37454. /**
  37455. * The renderer.
  37456. *
  37457. * @private
  37458. * @type {Renderer}
  37459. */
  37460. this._renderer = renderer;
  37461. // camera
  37462. /**
  37463. * Represents the camera for the left eye.
  37464. *
  37465. * @private
  37466. * @type {PerspectiveCamera}
  37467. */
  37468. this._cameraL = new PerspectiveCamera();
  37469. this._cameraL.viewport = new Vector4();
  37470. /**
  37471. * Represents the camera for the right eye.
  37472. *
  37473. * @private
  37474. * @type {PerspectiveCamera}
  37475. */
  37476. this._cameraR = new PerspectiveCamera();
  37477. this._cameraR.viewport = new Vector4();
  37478. /**
  37479. * A list of cameras used for rendering the XR views.
  37480. *
  37481. * @private
  37482. * @type {Array<Camera>}
  37483. */
  37484. this._cameras = [ this._cameraL, this._cameraR ];
  37485. /**
  37486. * The main XR camera.
  37487. *
  37488. * @private
  37489. * @type {ArrayCamera}
  37490. */
  37491. this._cameraXR = new ArrayCamera();
  37492. /**
  37493. * The current near value of the XR camera.
  37494. *
  37495. * @private
  37496. * @type {?number}
  37497. * @default null
  37498. */
  37499. this._currentDepthNear = null;
  37500. /**
  37501. * The current far value of the XR camera.
  37502. *
  37503. * @private
  37504. * @type {?number}
  37505. * @default null
  37506. */
  37507. this._currentDepthFar = null;
  37508. /**
  37509. * A list of WebXR controllers requested by the application.
  37510. *
  37511. * @private
  37512. * @type {Array<WebXRController>}
  37513. */
  37514. this._controllers = [];
  37515. /**
  37516. * A list of XR input source. Each input source belongs to
  37517. * an instance of WebXRController.
  37518. *
  37519. * @private
  37520. * @type {Array<XRInputSource?>}
  37521. */
  37522. this._controllerInputSources = [];
  37523. /**
  37524. * The XR render target that represents the rendering destination
  37525. * during an active XR session.
  37526. *
  37527. * @private
  37528. * @type {?RenderTarget}
  37529. * @default null
  37530. */
  37531. this._xrRenderTarget = null;
  37532. /**
  37533. * An array holding all the non-projection layers
  37534. *
  37535. * @private
  37536. * @type {Array<Object>}
  37537. * @default []
  37538. */
  37539. this._layers = [];
  37540. /**
  37541. * Whether the XR session uses layers.
  37542. *
  37543. * @type {boolean}
  37544. * @default false
  37545. */
  37546. this._sessionUsesLayers = false;
  37547. /**
  37548. * Whether the device supports binding gl objects.
  37549. *
  37550. * @private
  37551. * @type {boolean}
  37552. * @readonly
  37553. */
  37554. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  37555. this._frameBufferTargets = null;
  37556. /**
  37557. * Helper function to create native WebXR Layer.
  37558. *
  37559. * @private
  37560. * @type {Function}
  37561. */
  37562. this._createXRLayer = createXRLayer.bind( this );
  37563. /**
  37564. * The current WebGL context.
  37565. *
  37566. * @private
  37567. * @type {?WebGL2RenderingContext}
  37568. * @default null
  37569. */
  37570. this._gl = null;
  37571. /**
  37572. * The current animation context.
  37573. *
  37574. * @private
  37575. * @type {?Window}
  37576. * @default null
  37577. */
  37578. this._currentAnimationContext = null;
  37579. /**
  37580. * The current animation loop.
  37581. *
  37582. * @private
  37583. * @type {?Function}
  37584. * @default null
  37585. */
  37586. this._currentAnimationLoop = null;
  37587. /**
  37588. * The current pixel ratio.
  37589. *
  37590. * @private
  37591. * @type {?number}
  37592. * @default null
  37593. */
  37594. this._currentPixelRatio = null;
  37595. /**
  37596. * The current size of the renderer's canvas
  37597. * in logical pixel unit.
  37598. *
  37599. * @private
  37600. * @type {Vector2}
  37601. */
  37602. this._currentSize = new Vector2();
  37603. /**
  37604. * The default event listener for handling events inside a XR session.
  37605. *
  37606. * @private
  37607. * @type {Function}
  37608. */
  37609. this._onSessionEvent = onSessionEvent.bind( this );
  37610. /**
  37611. * The event listener for handling the end of a XR session.
  37612. *
  37613. * @private
  37614. * @type {Function}
  37615. */
  37616. this._onSessionEnd = onSessionEnd.bind( this );
  37617. /**
  37618. * The event listener for handling the `inputsourceschange` event.
  37619. *
  37620. * @private
  37621. * @type {Function}
  37622. */
  37623. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  37624. /**
  37625. * The animation loop which is used as a replacement for the default
  37626. * animation loop of the application. It is only used when a XR session
  37627. * is active.
  37628. *
  37629. * @private
  37630. * @type {Function}
  37631. */
  37632. this._onAnimationFrame = onAnimationFrame.bind( this );
  37633. /**
  37634. * The current XR reference space.
  37635. *
  37636. * @private
  37637. * @type {?XRReferenceSpace}
  37638. * @default null
  37639. */
  37640. this._referenceSpace = null;
  37641. /**
  37642. * The current XR reference space type.
  37643. *
  37644. * @private
  37645. * @type {XRReferenceSpaceType}
  37646. * @default 'local-floor'
  37647. */
  37648. this._referenceSpaceType = 'local-floor';
  37649. /**
  37650. * A custom reference space defined by the application.
  37651. *
  37652. * @private
  37653. * @type {?XRReferenceSpace}
  37654. * @default null
  37655. */
  37656. this._customReferenceSpace = null;
  37657. /**
  37658. * The framebuffer scale factor.
  37659. *
  37660. * @private
  37661. * @type {number}
  37662. * @default 1
  37663. */
  37664. this._framebufferScaleFactor = 1;
  37665. /**
  37666. * The foveation factor.
  37667. *
  37668. * @private
  37669. * @type {number}
  37670. * @default 1
  37671. */
  37672. this._foveation = 1.0;
  37673. /**
  37674. * A reference to the current XR session.
  37675. *
  37676. * @private
  37677. * @type {?XRSession}
  37678. * @default null
  37679. */
  37680. this._session = null;
  37681. /**
  37682. * A reference to the current XR base layer.
  37683. *
  37684. * @private
  37685. * @type {?XRWebGLLayer}
  37686. * @default null
  37687. */
  37688. this._glBaseLayer = null;
  37689. /**
  37690. * A reference to the current XR binding.
  37691. *
  37692. * @private
  37693. * @type {?XRWebGLBinding}
  37694. * @default null
  37695. */
  37696. this._glBinding = null;
  37697. /**
  37698. * A reference to the current XR projection layer.
  37699. *
  37700. * @private
  37701. * @type {?XRProjectionLayer}
  37702. * @default null
  37703. */
  37704. this._glProjLayer = null;
  37705. /**
  37706. * A reference to the current XR frame.
  37707. *
  37708. * @private
  37709. * @type {?XRFrame}
  37710. * @default null
  37711. */
  37712. this._xrFrame = null;
  37713. /**
  37714. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  37715. *
  37716. * Note: this does not represent XRSession explicitly requesting
  37717. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  37718. *
  37719. * @private
  37720. * @type {boolean}
  37721. * @readonly
  37722. */
  37723. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  37724. /**
  37725. * Whether the usage of multiview has been requested by the application or not.
  37726. *
  37727. * @private
  37728. * @type {boolean}
  37729. * @default false
  37730. * @readonly
  37731. */
  37732. this._useMultiviewIfPossible = multiview;
  37733. /**
  37734. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  37735. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  37736. *
  37737. * @private
  37738. * @type {boolean}
  37739. * @readonly
  37740. */
  37741. this._useMultiview = false;
  37742. }
  37743. /**
  37744. * Returns an instance of `THREE.Group` that represents the transformation
  37745. * of a XR controller in target ray space. The requested controller is defined
  37746. * by the given index.
  37747. *
  37748. * @param {number} index - The index of the XR controller.
  37749. * @return {Group} A group that represents the controller's transformation.
  37750. */
  37751. getController( index ) {
  37752. const controller = this._getController( index );
  37753. return controller.getTargetRaySpace();
  37754. }
  37755. /**
  37756. * Returns an instance of `THREE.Group` that represents the transformation
  37757. * of a XR controller in grip space. The requested controller is defined
  37758. * by the given index.
  37759. *
  37760. * @param {number} index - The index of the XR controller.
  37761. * @return {Group} A group that represents the controller's transformation.
  37762. */
  37763. getControllerGrip( index ) {
  37764. const controller = this._getController( index );
  37765. return controller.getGripSpace();
  37766. }
  37767. /**
  37768. * Returns an instance of `THREE.Group` that represents the transformation
  37769. * of a XR controller in hand space. The requested controller is defined
  37770. * by the given index.
  37771. *
  37772. * @param {number} index - The index of the XR controller.
  37773. * @return {Group} A group that represents the controller's transformation.
  37774. */
  37775. getHand( index ) {
  37776. const controller = this._getController( index );
  37777. return controller.getHandSpace();
  37778. }
  37779. /**
  37780. * Returns the foveation value.
  37781. *
  37782. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  37783. */
  37784. getFoveation() {
  37785. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  37786. return undefined;
  37787. }
  37788. return this._foveation;
  37789. }
  37790. /**
  37791. * Sets the foveation value.
  37792. *
  37793. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  37794. * and `1` means maximum foveation (the edges render at lower resolution).
  37795. */
  37796. setFoveation( foveation ) {
  37797. this._foveation = foveation;
  37798. if ( this._glProjLayer !== null ) {
  37799. this._glProjLayer.fixedFoveation = foveation;
  37800. }
  37801. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  37802. this._glBaseLayer.fixedFoveation = foveation;
  37803. }
  37804. }
  37805. /**
  37806. * Returns the framebuffer scale factor.
  37807. *
  37808. * @return {number} The framebuffer scale factor.
  37809. */
  37810. getFramebufferScaleFactor() {
  37811. return this._framebufferScaleFactor;
  37812. }
  37813. /**
  37814. * Sets the framebuffer scale factor.
  37815. *
  37816. * This method can not be used during a XR session.
  37817. *
  37818. * @param {number} factor - The framebuffer scale factor.
  37819. */
  37820. setFramebufferScaleFactor( factor ) {
  37821. this._framebufferScaleFactor = factor;
  37822. if ( this.isPresenting === true ) {
  37823. warn( 'XRManager: Cannot change framebuffer scale while presenting.' );
  37824. }
  37825. }
  37826. /**
  37827. * Returns the reference space type.
  37828. *
  37829. * @return {XRReferenceSpaceType} The reference space type.
  37830. */
  37831. getReferenceSpaceType() {
  37832. return this._referenceSpaceType;
  37833. }
  37834. /**
  37835. * Sets the reference space type.
  37836. *
  37837. * This method can not be used during a XR session.
  37838. *
  37839. * @param {XRReferenceSpaceType} type - The reference space type.
  37840. */
  37841. setReferenceSpaceType( type ) {
  37842. this._referenceSpaceType = type;
  37843. if ( this.isPresenting === true ) {
  37844. warn( 'XRManager: Cannot change reference space type while presenting.' );
  37845. }
  37846. }
  37847. /**
  37848. * Returns the XR reference space.
  37849. *
  37850. * @return {XRReferenceSpace} The XR reference space.
  37851. */
  37852. getReferenceSpace() {
  37853. return this._customReferenceSpace || this._referenceSpace;
  37854. }
  37855. /**
  37856. * Sets a custom XR reference space.
  37857. *
  37858. * @param {XRReferenceSpace} space - The XR reference space.
  37859. */
  37860. setReferenceSpace( space ) {
  37861. this._customReferenceSpace = space;
  37862. }
  37863. /**
  37864. * Returns the XR camera.
  37865. *
  37866. * @return {ArrayCamera} The XR camera.
  37867. */
  37868. getCamera() {
  37869. return this._cameraXR;
  37870. }
  37871. /**
  37872. * Returns the environment blend mode from the current XR session.
  37873. *
  37874. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  37875. */
  37876. getEnvironmentBlendMode() {
  37877. if ( this._session !== null ) {
  37878. return this._session.environmentBlendMode;
  37879. }
  37880. }
  37881. /**
  37882. * Returns the current XR binding.
  37883. *
  37884. * Creates a new binding if needed and the browser is
  37885. * capable of doing so.
  37886. *
  37887. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  37888. */
  37889. getBinding() {
  37890. if ( this._glBinding === null && this._supportsGlBinding ) {
  37891. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  37892. }
  37893. return this._glBinding;
  37894. }
  37895. /**
  37896. * Returns the current XR frame.
  37897. *
  37898. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  37899. */
  37900. getFrame() {
  37901. return this._xrFrame;
  37902. }
  37903. /**
  37904. * Returns `true` if the engine renders to a multiview target.
  37905. *
  37906. * @return {boolean} Whether the engine renders to a multiview render target or not.
  37907. */
  37908. useMultiview() {
  37909. return this._useMultiview;
  37910. }
  37911. /**
  37912. * This method can be used in XR applications to create a quadratic layer that presents a separate
  37913. * rendered scene.
  37914. *
  37915. * @param {number} width - The width of the layer plane in world units.
  37916. * @param {number} height - The height of the layer plane in world units.
  37917. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  37918. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  37919. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  37920. * @param {number} pixelheight - The height of the layer's render target in pixels.
  37921. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  37922. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  37923. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  37924. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  37925. */
  37926. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  37927. const geometry = new PlaneGeometry( width, height );
  37928. const renderTarget = new XRRenderTarget(
  37929. pixelwidth,
  37930. pixelheight,
  37931. {
  37932. format: RGBAFormat,
  37933. type: UnsignedByteType,
  37934. depthTexture: new DepthTexture(
  37935. pixelwidth,
  37936. pixelheight,
  37937. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  37938. undefined,
  37939. undefined,
  37940. undefined,
  37941. undefined,
  37942. undefined,
  37943. undefined,
  37944. attributes.stencil ? DepthStencilFormat : DepthFormat
  37945. ),
  37946. stencilBuffer: attributes.stencil,
  37947. resolveDepthBuffer: false,
  37948. resolveStencilBuffer: false
  37949. } );
  37950. renderTarget._autoAllocateDepthBuffer = true;
  37951. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  37952. material.map = renderTarget.texture;
  37953. material.map.offset.y = 1;
  37954. material.map.repeat.y = -1;
  37955. const plane = new Mesh( geometry, material );
  37956. plane.position.copy( translation );
  37957. plane.quaternion.copy( quaternion );
  37958. const layer = {
  37959. type: 'quad',
  37960. width: width,
  37961. height: height,
  37962. translation: translation,
  37963. quaternion: quaternion,
  37964. pixelwidth: pixelwidth,
  37965. pixelheight: pixelheight,
  37966. plane: plane,
  37967. material: material,
  37968. rendercall: rendercall,
  37969. renderTarget: renderTarget };
  37970. this._layers.push( layer );
  37971. if ( this._session !== null ) {
  37972. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  37973. layer.plane.material.blending = CustomBlending;
  37974. layer.plane.material.blendEquation = AddEquation;
  37975. layer.plane.material.blendSrc = ZeroFactor;
  37976. layer.plane.material.blendDst = ZeroFactor;
  37977. layer.xrlayer = this._createXRLayer( layer );
  37978. const xrlayers = this._session.renderState.layers;
  37979. xrlayers.unshift( layer.xrlayer );
  37980. this._session.updateRenderState( { layers: xrlayers } );
  37981. } else {
  37982. renderTarget.isXRRenderTarget = false;
  37983. }
  37984. return plane;
  37985. }
  37986. /**
  37987. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  37988. * rendered scene.
  37989. *
  37990. * @param {number} radius - The radius of the cylinder in world units.
  37991. * @param {number} centralAngle - The central angle of the cylinder in radians.
  37992. * @param {number} aspectratio - The aspect ratio.
  37993. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  37994. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  37995. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  37996. * @param {number} pixelheight - The height of the layer's render target in pixels.
  37997. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  37998. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  37999. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  38000. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  38001. */
  38002. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  38003. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  38004. const renderTarget = new XRRenderTarget(
  38005. pixelwidth,
  38006. pixelheight,
  38007. {
  38008. format: RGBAFormat,
  38009. type: UnsignedByteType,
  38010. depthTexture: new DepthTexture(
  38011. pixelwidth,
  38012. pixelheight,
  38013. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  38014. undefined,
  38015. undefined,
  38016. undefined,
  38017. undefined,
  38018. undefined,
  38019. undefined,
  38020. attributes.stencil ? DepthStencilFormat : DepthFormat
  38021. ),
  38022. stencilBuffer: attributes.stencil,
  38023. resolveDepthBuffer: false,
  38024. resolveStencilBuffer: false
  38025. } );
  38026. renderTarget._autoAllocateDepthBuffer = true;
  38027. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38028. material.map = renderTarget.texture;
  38029. material.map.offset.y = 1;
  38030. material.map.repeat.y = -1;
  38031. const plane = new Mesh( geometry, material );
  38032. plane.position.copy( translation );
  38033. plane.quaternion.copy( quaternion );
  38034. const layer = {
  38035. type: 'cylinder',
  38036. radius: radius,
  38037. centralAngle: centralAngle,
  38038. aspectratio: aspectratio,
  38039. translation: translation,
  38040. quaternion: quaternion,
  38041. pixelwidth: pixelwidth,
  38042. pixelheight: pixelheight,
  38043. plane: plane,
  38044. material: material,
  38045. rendercall: rendercall,
  38046. renderTarget: renderTarget };
  38047. this._layers.push( layer );
  38048. if ( this._session !== null ) {
  38049. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  38050. layer.plane.material.blending = CustomBlending;
  38051. layer.plane.material.blendEquation = AddEquation;
  38052. layer.plane.material.blendSrc = ZeroFactor;
  38053. layer.plane.material.blendDst = ZeroFactor;
  38054. layer.xrlayer = this._createXRLayer( layer );
  38055. const xrlayers = this._session.renderState.layers;
  38056. xrlayers.unshift( layer.xrlayer );
  38057. this._session.updateRenderState( { layers: xrlayers } );
  38058. } else {
  38059. renderTarget.isXRRenderTarget = false;
  38060. }
  38061. return plane;
  38062. }
  38063. /**
  38064. * Renders the XR layers that have been previously added to the scene.
  38065. *
  38066. * This method is usually called in your animation loop before rendering
  38067. * the actual scene via `renderer.render( scene, camera );`.
  38068. */
  38069. renderLayers( ) {
  38070. const translationObject = new Vector3();
  38071. const quaternionObject = new Quaternion();
  38072. const renderer = this._renderer;
  38073. const wasPresenting = this.isPresenting;
  38074. const rendererOutputTarget = renderer.getOutputRenderTarget();
  38075. const rendererFramebufferTarget = renderer._frameBufferTarget;
  38076. this.isPresenting = false;
  38077. const rendererSize = new Vector2();
  38078. renderer.getSize( rendererSize );
  38079. const rendererQuad = renderer._quad;
  38080. for ( const layer of this._layers ) {
  38081. layer.renderTarget.isXRRenderTarget = this._session !== null;
  38082. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  38083. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  38084. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  38085. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  38086. renderer.backend.setXRRenderTargetTextures(
  38087. layer.renderTarget,
  38088. glSubImage.colorTexture,
  38089. undefined );
  38090. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  38091. renderer.setOutputRenderTarget( layer.renderTarget );
  38092. renderer.setRenderTarget( null );
  38093. renderer._frameBufferTarget = null;
  38094. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  38095. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  38096. if ( ! frameBufferTarget ) {
  38097. renderer._quad = new QuadMesh( new NodeMaterial() );
  38098. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  38099. } else {
  38100. renderer._frameBufferTarget = frameBufferTarget;
  38101. renderer._quad = quad;
  38102. }
  38103. layer.rendercall();
  38104. renderer._frameBufferTarget = null;
  38105. } else {
  38106. renderer.setRenderTarget( layer.renderTarget );
  38107. layer.rendercall();
  38108. }
  38109. }
  38110. renderer.setRenderTarget( null );
  38111. renderer.setOutputRenderTarget( rendererOutputTarget );
  38112. renderer._frameBufferTarget = rendererFramebufferTarget;
  38113. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  38114. renderer._quad = rendererQuad;
  38115. this.isPresenting = wasPresenting;
  38116. }
  38117. /**
  38118. * Returns the current XR session.
  38119. *
  38120. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  38121. */
  38122. getSession() {
  38123. return this._session;
  38124. }
  38125. /**
  38126. * After a XR session has been requested usually with one of the `*Button` modules, it
  38127. * is injected into the renderer with this method. This method triggers the start of
  38128. * the actual XR rendering.
  38129. *
  38130. * @async
  38131. * @param {XRSession} session - The XR session to set.
  38132. * @return {Promise} A Promise that resolves when the session has been set.
  38133. */
  38134. async setSession( session ) {
  38135. const renderer = this._renderer;
  38136. const backend = renderer.backend;
  38137. this._gl = renderer.getContext();
  38138. const gl = this._gl;
  38139. const attributes = gl.getContextAttributes();
  38140. this._session = session;
  38141. if ( session !== null ) {
  38142. 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.' );
  38143. session.addEventListener( 'select', this._onSessionEvent );
  38144. session.addEventListener( 'selectstart', this._onSessionEvent );
  38145. session.addEventListener( 'selectend', this._onSessionEvent );
  38146. session.addEventListener( 'squeeze', this._onSessionEvent );
  38147. session.addEventListener( 'squeezestart', this._onSessionEvent );
  38148. session.addEventListener( 'squeezeend', this._onSessionEvent );
  38149. session.addEventListener( 'end', this._onSessionEnd );
  38150. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38151. await backend.makeXRCompatible();
  38152. this._currentPixelRatio = renderer.getPixelRatio();
  38153. renderer.getSize( this._currentSize );
  38154. this._currentAnimationContext = renderer._animation.getContext();
  38155. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  38156. renderer._animation.stop();
  38157. //
  38158. if ( this._supportsLayers === true ) {
  38159. // default path using XRProjectionLayer
  38160. let depthFormat = null;
  38161. let depthType = null;
  38162. let glDepthFormat = null;
  38163. if ( renderer.depth ) {
  38164. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  38165. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  38166. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  38167. }
  38168. const projectionlayerInit = {
  38169. colorFormat: gl.RGBA8,
  38170. depthFormat: glDepthFormat,
  38171. scaleFactor: this._framebufferScaleFactor,
  38172. clearOnAccess: false
  38173. };
  38174. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  38175. projectionlayerInit.textureType = 'texture-array';
  38176. this._useMultiview = true;
  38177. }
  38178. this._glBinding = this.getBinding();
  38179. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  38180. const layersArray = [ glProjLayer ];
  38181. this._glProjLayer = glProjLayer;
  38182. renderer.setPixelRatio( 1 );
  38183. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  38184. const depth = this._useMultiview ? 2 : 1;
  38185. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  38186. this._xrRenderTarget = new XRRenderTarget(
  38187. glProjLayer.textureWidth,
  38188. glProjLayer.textureHeight,
  38189. {
  38190. format: RGBAFormat,
  38191. type: UnsignedByteType,
  38192. colorSpace: renderer.outputColorSpace,
  38193. depthTexture: depthTexture,
  38194. stencilBuffer: renderer.stencil,
  38195. samples: attributes.antialias ? 4 : 0,
  38196. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38197. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38198. depth: this._useMultiview ? 2 : 1,
  38199. multiview: this._useMultiview
  38200. } );
  38201. this._xrRenderTarget._hasExternalTextures = true;
  38202. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  38203. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  38204. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38205. if ( this._sessionUsesLayers ) {
  38206. // switch layers to native
  38207. for ( const layer of this._layers ) {
  38208. // change material so it "punches" out a hole to show the XR Layer.
  38209. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  38210. layer.plane.material.blending = CustomBlending;
  38211. layer.plane.material.blendEquation = AddEquation;
  38212. layer.plane.material.blendSrc = ZeroFactor;
  38213. layer.plane.material.blendDst = ZeroFactor;
  38214. layer.xrlayer = this._createXRLayer( layer );
  38215. layersArray.unshift( layer.xrlayer );
  38216. }
  38217. }
  38218. session.updateRenderState( { layers: layersArray } );
  38219. } else {
  38220. // fallback to XRWebGLLayer
  38221. const layerInit = {
  38222. antialias: renderer.samples > 0,
  38223. alpha: true,
  38224. depth: renderer.depth,
  38225. stencil: renderer.stencil,
  38226. framebufferScaleFactor: this.getFramebufferScaleFactor()
  38227. };
  38228. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  38229. this._glBaseLayer = glBaseLayer;
  38230. session.updateRenderState( { baseLayer: glBaseLayer } );
  38231. renderer.setPixelRatio( 1 );
  38232. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  38233. this._xrRenderTarget = new XRRenderTarget(
  38234. glBaseLayer.framebufferWidth,
  38235. glBaseLayer.framebufferHeight,
  38236. {
  38237. format: RGBAFormat,
  38238. type: UnsignedByteType,
  38239. colorSpace: renderer.outputColorSpace,
  38240. stencilBuffer: renderer.stencil,
  38241. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38242. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38243. }
  38244. );
  38245. this._xrRenderTarget._isOpaqueFramebuffer = true;
  38246. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38247. }
  38248. //
  38249. this.setFoveation( this.getFoveation() );
  38250. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  38251. renderer._animation.setContext( session );
  38252. renderer._animation.start();
  38253. this.isPresenting = true;
  38254. this.dispatchEvent( { type: 'sessionstart' } );
  38255. }
  38256. }
  38257. /**
  38258. * This method is called by the renderer per frame and updates the XR camera
  38259. * and it sub cameras based on the given camera. The given camera is the "user"
  38260. * camera created on application level and used for non-XR rendering.
  38261. *
  38262. * @param {PerspectiveCamera} camera - The camera.
  38263. */
  38264. updateCamera( camera ) {
  38265. const session = this._session;
  38266. if ( session === null ) return;
  38267. const depthNear = camera.near;
  38268. const depthFar = camera.far;
  38269. const cameraXR = this._cameraXR;
  38270. const cameraL = this._cameraL;
  38271. const cameraR = this._cameraR;
  38272. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  38273. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  38274. cameraXR.isMultiViewCamera = this._useMultiview;
  38275. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  38276. // Note that the new renderState won't apply until the next frame. See #18320
  38277. session.updateRenderState( {
  38278. depthNear: cameraXR.near,
  38279. depthFar: cameraXR.far
  38280. } );
  38281. this._currentDepthNear = cameraXR.near;
  38282. this._currentDepthFar = cameraXR.far;
  38283. }
  38284. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  38285. cameraXR.layers.mask = camera.layers.mask | 0b110;
  38286. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  38287. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  38288. const parent = camera.parent;
  38289. const cameras = cameraXR.cameras;
  38290. updateCamera( cameraXR, parent );
  38291. for ( let i = 0; i < cameras.length; i ++ ) {
  38292. updateCamera( cameras[ i ], parent );
  38293. }
  38294. // update projection matrix for proper view frustum culling
  38295. if ( cameras.length === 2 ) {
  38296. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  38297. } else {
  38298. // assume single camera setup (AR)
  38299. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  38300. }
  38301. // update user camera and its children
  38302. updateUserCamera( camera, cameraXR, parent );
  38303. }
  38304. /**
  38305. * Returns a WebXR controller for the given controller index.
  38306. *
  38307. * @private
  38308. * @param {number} index - The controller index.
  38309. * @return {WebXRController} The XR controller.
  38310. */
  38311. _getController( index ) {
  38312. let controller = this._controllers[ index ];
  38313. if ( controller === undefined ) {
  38314. controller = new WebXRController();
  38315. this._controllers[ index ] = controller;
  38316. }
  38317. return controller;
  38318. }
  38319. }
  38320. /**
  38321. * Assumes 2 cameras that are parallel and share an X-axis, and that
  38322. * the cameras' projection and world matrices have already been set.
  38323. * And that near and far planes are identical for both cameras.
  38324. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  38325. *
  38326. * @param {ArrayCamera} camera - The camera to update.
  38327. * @param {PerspectiveCamera} cameraL - The left camera.
  38328. * @param {PerspectiveCamera} cameraR - The right camera.
  38329. */
  38330. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  38331. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  38332. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  38333. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  38334. const projL = cameraL.projectionMatrix.elements;
  38335. const projR = cameraR.projectionMatrix.elements;
  38336. // VR systems will have identical far and near planes, and
  38337. // most likely identical top and bottom frustum extents.
  38338. // Use the left camera for these values.
  38339. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  38340. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  38341. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  38342. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  38343. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  38344. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  38345. const left = near * leftFov;
  38346. const right = near * rightFov;
  38347. // Calculate the new camera's position offset from the
  38348. // left camera. xOffset should be roughly half `ipd`.
  38349. const zOffset = ipd / ( - leftFov + rightFov );
  38350. const xOffset = zOffset * - leftFov;
  38351. // TODO: Better way to apply this offset?
  38352. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  38353. camera.translateX( xOffset );
  38354. camera.translateZ( zOffset );
  38355. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  38356. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38357. // Check if the projection uses an infinite far plane.
  38358. if ( projL[ 10 ] === -1 ) {
  38359. // Use the projection matrix from the left eye.
  38360. // The camera offset is sufficient to include the view volumes
  38361. // of both eyes (assuming symmetric projections).
  38362. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  38363. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  38364. } else {
  38365. // Find the union of the frustum values of the cameras and scale
  38366. // the values so that the near plane's position does not change in world space,
  38367. // although must now be relative to the new union camera.
  38368. const near2 = near + zOffset;
  38369. const far2 = far + zOffset;
  38370. const left2 = left - xOffset;
  38371. const right2 = right + ( ipd - xOffset );
  38372. const top2 = topFov * far / far2 * near2;
  38373. const bottom2 = bottomFov * far / far2 * near2;
  38374. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  38375. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38376. }
  38377. }
  38378. /**
  38379. * Updates the world matrices for the given camera based on the parent 3D object.
  38380. *
  38381. * @inner
  38382. * @param {Camera} camera - The camera to update.
  38383. * @param {Object3D} parent - The parent 3D object.
  38384. */
  38385. function updateCamera( camera, parent ) {
  38386. if ( parent === null ) {
  38387. camera.matrixWorld.copy( camera.matrix );
  38388. } else {
  38389. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  38390. }
  38391. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38392. }
  38393. /**
  38394. * Updates the given camera with the transformation of the XR camera and parent object.
  38395. *
  38396. * @inner
  38397. * @param {Camera} camera - The camera to update.
  38398. * @param {ArrayCamera} cameraXR - The XR camera.
  38399. * @param {Object3D} parent - The parent 3D object.
  38400. */
  38401. function updateUserCamera( camera, cameraXR, parent ) {
  38402. if ( parent === null ) {
  38403. camera.matrix.copy( cameraXR.matrixWorld );
  38404. } else {
  38405. camera.matrix.copy( parent.matrixWorld );
  38406. camera.matrix.invert();
  38407. camera.matrix.multiply( cameraXR.matrixWorld );
  38408. }
  38409. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38410. camera.updateMatrixWorld( true );
  38411. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  38412. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  38413. if ( camera.isPerspectiveCamera ) {
  38414. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  38415. camera.zoom = 1;
  38416. }
  38417. }
  38418. function onSessionEvent( event ) {
  38419. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  38420. if ( controllerIndex === -1 ) {
  38421. return;
  38422. }
  38423. const controller = this._controllers[ controllerIndex ];
  38424. if ( controller !== undefined ) {
  38425. const referenceSpace = this.getReferenceSpace();
  38426. controller.update( event.inputSource, event.frame, referenceSpace );
  38427. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  38428. }
  38429. }
  38430. function onSessionEnd() {
  38431. const session = this._session;
  38432. const renderer = this._renderer;
  38433. session.removeEventListener( 'select', this._onSessionEvent );
  38434. session.removeEventListener( 'selectstart', this._onSessionEvent );
  38435. session.removeEventListener( 'selectend', this._onSessionEvent );
  38436. session.removeEventListener( 'squeeze', this._onSessionEvent );
  38437. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  38438. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  38439. session.removeEventListener( 'end', this._onSessionEnd );
  38440. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38441. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38442. const inputSource = this._controllerInputSources[ i ];
  38443. if ( inputSource === null ) continue;
  38444. this._controllerInputSources[ i ] = null;
  38445. this._controllers[ i ].disconnect( inputSource );
  38446. }
  38447. this._currentDepthNear = null;
  38448. this._currentDepthFar = null;
  38449. // restore framebuffer/rendering state
  38450. renderer._resetXRState();
  38451. this._session = null;
  38452. this._xrRenderTarget = null;
  38453. this._glBinding = null;
  38454. this._glBaseLayer = null;
  38455. this._glProjLayer = null;
  38456. // switch layers back to emulated
  38457. if ( this._sessionUsesLayers === true ) {
  38458. for ( const layer of this._layers ) {
  38459. // Recreate layer render target to reset state
  38460. layer.renderTarget = new XRRenderTarget(
  38461. layer.pixelwidth,
  38462. layer.pixelheight,
  38463. {
  38464. format: RGBAFormat,
  38465. type: UnsignedByteType,
  38466. depthTexture: new DepthTexture(
  38467. layer.pixelwidth,
  38468. layer.pixelheight,
  38469. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  38470. undefined,
  38471. undefined,
  38472. undefined,
  38473. undefined,
  38474. undefined,
  38475. undefined,
  38476. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  38477. ),
  38478. stencilBuffer: layer.stencilBuffer,
  38479. resolveDepthBuffer: false,
  38480. resolveStencilBuffer: false
  38481. } );
  38482. layer.renderTarget.isXRRenderTarget = false;
  38483. layer.plane.material = layer.material;
  38484. layer.material.map = layer.renderTarget.texture;
  38485. layer.material.map.offset.y = 1;
  38486. layer.material.map.repeat.y = -1;
  38487. delete layer.xrlayer;
  38488. }
  38489. }
  38490. //
  38491. this.isPresenting = false;
  38492. this._useMultiview = false;
  38493. renderer._animation.stop();
  38494. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  38495. renderer._animation.setContext( this._currentAnimationContext );
  38496. renderer._animation.start();
  38497. renderer.setPixelRatio( this._currentPixelRatio );
  38498. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  38499. this.dispatchEvent( { type: 'sessionend' } );
  38500. }
  38501. function onInputSourcesChange( event ) {
  38502. const controllers = this._controllers;
  38503. const controllerInputSources = this._controllerInputSources;
  38504. // Notify disconnected
  38505. for ( let i = 0; i < event.removed.length; i ++ ) {
  38506. const inputSource = event.removed[ i ];
  38507. const index = controllerInputSources.indexOf( inputSource );
  38508. if ( index >= 0 ) {
  38509. controllerInputSources[ index ] = null;
  38510. controllers[ index ].disconnect( inputSource );
  38511. }
  38512. }
  38513. // Notify connected
  38514. for ( let i = 0; i < event.added.length; i ++ ) {
  38515. const inputSource = event.added[ i ];
  38516. let controllerIndex = controllerInputSources.indexOf( inputSource );
  38517. if ( controllerIndex === -1 ) {
  38518. // Assign input source a controller that currently has no input source
  38519. for ( let i = 0; i < controllers.length; i ++ ) {
  38520. if ( i >= controllerInputSources.length ) {
  38521. controllerInputSources.push( inputSource );
  38522. controllerIndex = i;
  38523. break;
  38524. } else if ( controllerInputSources[ i ] === null ) {
  38525. controllerInputSources[ i ] = inputSource;
  38526. controllerIndex = i;
  38527. break;
  38528. }
  38529. }
  38530. // If all controllers do currently receive input we ignore new ones
  38531. if ( controllerIndex === -1 ) break;
  38532. }
  38533. const controller = controllers[ controllerIndex ];
  38534. if ( controller ) {
  38535. controller.connect( inputSource );
  38536. }
  38537. }
  38538. }
  38539. // Creation method for native WebXR layers
  38540. function createXRLayer( layer ) {
  38541. if ( layer.type === 'quad' ) {
  38542. return this._glBinding.createQuadLayer( {
  38543. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38544. width: layer.width / 2,
  38545. height: layer.height / 2,
  38546. space: this._referenceSpace,
  38547. viewPixelWidth: layer.pixelwidth,
  38548. viewPixelHeight: layer.pixelheight,
  38549. clearOnAccess: false
  38550. } );
  38551. } else {
  38552. return this._glBinding.createCylinderLayer( {
  38553. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38554. radius: layer.radius,
  38555. centralAngle: layer.centralAngle,
  38556. aspectRatio: layer.aspectRatio,
  38557. space: this._referenceSpace,
  38558. viewPixelWidth: layer.pixelwidth,
  38559. viewPixelHeight: layer.pixelheight,
  38560. clearOnAccess: false
  38561. } );
  38562. }
  38563. }
  38564. // Animation Loop
  38565. function onAnimationFrame( time, frame ) {
  38566. if ( frame === undefined ) return;
  38567. const cameraXR = this._cameraXR;
  38568. const renderer = this._renderer;
  38569. const backend = renderer.backend;
  38570. const glBaseLayer = this._glBaseLayer;
  38571. const referenceSpace = this.getReferenceSpace();
  38572. const pose = frame.getViewerPose( referenceSpace );
  38573. this._xrFrame = frame;
  38574. if ( pose !== null ) {
  38575. const views = pose.views;
  38576. if ( this._glBaseLayer !== null ) {
  38577. backend.setXRTarget( glBaseLayer.framebuffer );
  38578. }
  38579. let cameraXRNeedsUpdate = false;
  38580. // check if it's necessary to rebuild cameraXR's camera list
  38581. if ( views.length !== cameraXR.cameras.length ) {
  38582. cameraXR.cameras.length = 0;
  38583. cameraXRNeedsUpdate = true;
  38584. }
  38585. for ( let i = 0; i < views.length; i ++ ) {
  38586. const view = views[ i ];
  38587. let viewport;
  38588. if ( this._supportsLayers === true ) {
  38589. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  38590. viewport = glSubImage.viewport;
  38591. // For side-by-side projection, we only produce a single texture for both eyes.
  38592. if ( i === 0 ) {
  38593. backend.setXRRenderTargetTextures(
  38594. this._xrRenderTarget,
  38595. glSubImage.colorTexture,
  38596. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  38597. );
  38598. }
  38599. } else {
  38600. viewport = glBaseLayer.getViewport( view );
  38601. }
  38602. let camera = this._cameras[ i ];
  38603. if ( camera === undefined ) {
  38604. camera = new PerspectiveCamera();
  38605. camera.layers.enable( i );
  38606. camera.viewport = new Vector4();
  38607. this._cameras[ i ] = camera;
  38608. }
  38609. camera.matrix.fromArray( view.transform.matrix );
  38610. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38611. camera.projectionMatrix.fromArray( view.projectionMatrix );
  38612. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38613. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  38614. if ( i === 0 ) {
  38615. cameraXR.matrix.copy( camera.matrix );
  38616. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  38617. }
  38618. if ( cameraXRNeedsUpdate === true ) {
  38619. cameraXR.cameras.push( camera );
  38620. }
  38621. }
  38622. renderer.setOutputRenderTarget( this._xrRenderTarget );
  38623. }
  38624. //
  38625. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38626. const inputSource = this._controllerInputSources[ i ];
  38627. const controller = this._controllers[ i ];
  38628. if ( inputSource !== null && controller !== undefined ) {
  38629. controller.update( inputSource, frame, referenceSpace );
  38630. }
  38631. }
  38632. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  38633. if ( frame.detectedPlanes ) {
  38634. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  38635. }
  38636. this._xrFrame = null;
  38637. }
  38638. const _scene = /*@__PURE__*/ new Scene();
  38639. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  38640. const _screen = /*@__PURE__*/ new Vector4();
  38641. const _frustum = /*@__PURE__*/ new Frustum();
  38642. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  38643. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  38644. const _vector4 = /*@__PURE__*/ new Vector4();
  38645. /**
  38646. * Base class for renderers.
  38647. */
  38648. class Renderer {
  38649. /**
  38650. * Renderer options.
  38651. *
  38652. * @typedef {Object} Renderer~Options
  38653. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  38654. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  38655. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  38656. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  38657. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  38658. * @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
  38659. * to overwrite the default.
  38660. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  38661. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  38662. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  38663. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  38664. */
  38665. /**
  38666. * Constructs a new renderer.
  38667. *
  38668. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  38669. * @param {Renderer~Options} [parameters] - The configuration parameter.
  38670. */
  38671. constructor( backend, parameters = {} ) {
  38672. /**
  38673. * This flag can be used for type testing.
  38674. *
  38675. * @type {boolean}
  38676. * @readonly
  38677. * @default true
  38678. */
  38679. this.isRenderer = true;
  38680. //
  38681. const {
  38682. logarithmicDepthBuffer = false,
  38683. alpha = true,
  38684. depth = true,
  38685. stencil = false,
  38686. antialias = false,
  38687. samples = 0,
  38688. getFallback = null,
  38689. colorBufferType = HalfFloatType,
  38690. multiview = false
  38691. } = parameters;
  38692. /**
  38693. * A reference to the canvas element the renderer is drawing to.
  38694. * This value of this property will automatically be created by
  38695. * the renderer.
  38696. *
  38697. * @type {HTMLCanvasElement|OffscreenCanvas}
  38698. */
  38699. this.domElement = backend.getDomElement();
  38700. /**
  38701. * A reference to the current backend.
  38702. *
  38703. * @type {Backend}
  38704. */
  38705. this.backend = backend;
  38706. /**
  38707. * The number of MSAA samples.
  38708. *
  38709. * @type {number}
  38710. * @default 0
  38711. */
  38712. this.samples = samples || ( antialias === true ) ? 4 : 0;
  38713. /**
  38714. * Whether the renderer should automatically clear the current rendering target
  38715. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  38716. * or the current bound render target (custom framebuffer).
  38717. *
  38718. * @type {boolean}
  38719. * @default true
  38720. */
  38721. this.autoClear = true;
  38722. /**
  38723. * When `autoClear` is set to `true`, this property defines whether the renderer
  38724. * should clear the color buffer.
  38725. *
  38726. * @type {boolean}
  38727. * @default true
  38728. */
  38729. this.autoClearColor = true;
  38730. /**
  38731. * When `autoClear` is set to `true`, this property defines whether the renderer
  38732. * should clear the depth buffer.
  38733. *
  38734. * @type {boolean}
  38735. * @default true
  38736. */
  38737. this.autoClearDepth = true;
  38738. /**
  38739. * When `autoClear` is set to `true`, this property defines whether the renderer
  38740. * should clear the stencil buffer.
  38741. *
  38742. * @type {boolean}
  38743. * @default true
  38744. */
  38745. this.autoClearStencil = true;
  38746. /**
  38747. * Whether the default framebuffer should be transparent or opaque.
  38748. *
  38749. * @type {boolean}
  38750. * @default true
  38751. */
  38752. this.alpha = alpha;
  38753. /**
  38754. * Whether logarithmic depth buffer is enabled or not.
  38755. *
  38756. * @type {boolean}
  38757. * @default false
  38758. */
  38759. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  38760. /**
  38761. * Defines the output color space of the renderer.
  38762. *
  38763. * @type {string}
  38764. * @default SRGBColorSpace
  38765. */
  38766. this.outputColorSpace = SRGBColorSpace;
  38767. /**
  38768. * Defines the tone mapping of the renderer.
  38769. *
  38770. * @type {number}
  38771. * @default NoToneMapping
  38772. */
  38773. this.toneMapping = NoToneMapping;
  38774. /**
  38775. * Defines the tone mapping exposure.
  38776. *
  38777. * @type {number}
  38778. * @default 1
  38779. */
  38780. this.toneMappingExposure = 1.0;
  38781. /**
  38782. * Whether the renderer should sort its render lists or not.
  38783. *
  38784. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  38785. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  38786. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  38787. * e.g. manually determining each object's rendering order.
  38788. *
  38789. * @type {boolean}
  38790. * @default true
  38791. */
  38792. this.sortObjects = true;
  38793. /**
  38794. * Whether the default framebuffer should have a depth buffer or not.
  38795. *
  38796. * @type {boolean}
  38797. * @default true
  38798. */
  38799. this.depth = depth;
  38800. /**
  38801. * Whether the default framebuffer should have a stencil buffer or not.
  38802. *
  38803. * @type {boolean}
  38804. * @default false
  38805. */
  38806. this.stencil = stencil;
  38807. /**
  38808. * Holds a series of statistical information about the GPU memory
  38809. * and the rendering process. Useful for debugging and monitoring.
  38810. *
  38811. * @type {Info}
  38812. */
  38813. this.info = new Info();
  38814. /**
  38815. * Stores override nodes for specific transformations or calculations.
  38816. * These nodes can be used to replace default behavior in the rendering pipeline.
  38817. *
  38818. * @type {Object}
  38819. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  38820. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  38821. */
  38822. this.overrideNodes = {
  38823. modelViewMatrix: null,
  38824. modelNormalViewMatrix: null
  38825. };
  38826. /**
  38827. * The node library defines how certain library objects like materials, lights
  38828. * or tone mapping functions are mapped to node types. This is required since
  38829. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  38830. * be part of the scene graph, they are internally represented as nodes for
  38831. * further processing.
  38832. *
  38833. * @type {NodeLibrary}
  38834. */
  38835. this.library = new NodeLibrary();
  38836. /**
  38837. * A map-like data structure for managing lights.
  38838. *
  38839. * @type {Lighting}
  38840. */
  38841. this.lighting = new Lighting();
  38842. // internals
  38843. /**
  38844. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  38845. *
  38846. * @private
  38847. * @type {?Function}
  38848. */
  38849. this._getFallback = getFallback;
  38850. /**
  38851. * The renderer's pixel ratio.
  38852. *
  38853. * @private
  38854. * @type {number}
  38855. * @default 1
  38856. */
  38857. this._pixelRatio = 1;
  38858. /**
  38859. * The width of the renderer's default framebuffer in logical pixel unit.
  38860. *
  38861. * @private
  38862. * @type {number}
  38863. */
  38864. this._width = this.domElement.width;
  38865. /**
  38866. * The height of the renderer's default framebuffer in logical pixel unit.
  38867. *
  38868. * @private
  38869. * @type {number}
  38870. */
  38871. this._height = this.domElement.height;
  38872. /**
  38873. * The viewport of the renderer in logical pixel unit.
  38874. *
  38875. * @private
  38876. * @type {Vector4}
  38877. */
  38878. this._viewport = new Vector4( 0, 0, this._width, this._height );
  38879. /**
  38880. * The scissor rectangle of the renderer in logical pixel unit.
  38881. *
  38882. * @private
  38883. * @type {Vector4}
  38884. */
  38885. this._scissor = new Vector4( 0, 0, this._width, this._height );
  38886. /**
  38887. * Whether the scissor test should be enabled or not.
  38888. *
  38889. * @private
  38890. * @type {boolean}
  38891. */
  38892. this._scissorTest = false;
  38893. /**
  38894. * A reference to a renderer module for managing shader attributes.
  38895. *
  38896. * @private
  38897. * @type {?Attributes}
  38898. * @default null
  38899. */
  38900. this._attributes = null;
  38901. /**
  38902. * A reference to a renderer module for managing geometries.
  38903. *
  38904. * @private
  38905. * @type {?Geometries}
  38906. * @default null
  38907. */
  38908. this._geometries = null;
  38909. /**
  38910. * A reference to a renderer module for managing node related logic.
  38911. *
  38912. * @private
  38913. * @type {?Nodes}
  38914. * @default null
  38915. */
  38916. this._nodes = null;
  38917. /**
  38918. * A reference to a renderer module for managing the internal animation loop.
  38919. *
  38920. * @private
  38921. * @type {?Animation}
  38922. * @default null
  38923. */
  38924. this._animation = null;
  38925. /**
  38926. * A reference to a renderer module for managing shader program bindings.
  38927. *
  38928. * @private
  38929. * @type {?Bindings}
  38930. * @default null
  38931. */
  38932. this._bindings = null;
  38933. /**
  38934. * A reference to a renderer module for managing render objects.
  38935. *
  38936. * @private
  38937. * @type {?RenderObjects}
  38938. * @default null
  38939. */
  38940. this._objects = null;
  38941. /**
  38942. * A reference to a renderer module for managing render and compute pipelines.
  38943. *
  38944. * @private
  38945. * @type {?Pipelines}
  38946. * @default null
  38947. */
  38948. this._pipelines = null;
  38949. /**
  38950. * A reference to a renderer module for managing render bundles.
  38951. *
  38952. * @private
  38953. * @type {?RenderBundles}
  38954. * @default null
  38955. */
  38956. this._bundles = null;
  38957. /**
  38958. * A reference to a renderer module for managing render lists.
  38959. *
  38960. * @private
  38961. * @type {?RenderLists}
  38962. * @default null
  38963. */
  38964. this._renderLists = null;
  38965. /**
  38966. * A reference to a renderer module for managing render contexts.
  38967. *
  38968. * @private
  38969. * @type {?RenderContexts}
  38970. * @default null
  38971. */
  38972. this._renderContexts = null;
  38973. /**
  38974. * A reference to a renderer module for managing textures.
  38975. *
  38976. * @private
  38977. * @type {?Textures}
  38978. * @default null
  38979. */
  38980. this._textures = null;
  38981. /**
  38982. * A reference to a renderer module for backgrounds.
  38983. *
  38984. * @private
  38985. * @type {?Background}
  38986. * @default null
  38987. */
  38988. this._background = null;
  38989. /**
  38990. * This fullscreen quad is used for internal render passes
  38991. * like the tone mapping and color space output pass.
  38992. *
  38993. * @private
  38994. * @type {QuadMesh}
  38995. */
  38996. this._quad = new QuadMesh( new NodeMaterial() );
  38997. this._quad.material.name = 'Renderer_output';
  38998. /**
  38999. * A reference to the current render context.
  39000. *
  39001. * @private
  39002. * @type {?RenderContext}
  39003. * @default null
  39004. */
  39005. this._currentRenderContext = null;
  39006. /**
  39007. * A custom sort function for the opaque render list.
  39008. *
  39009. * @private
  39010. * @type {?Function}
  39011. * @default null
  39012. */
  39013. this._opaqueSort = null;
  39014. /**
  39015. * A custom sort function for the transparent render list.
  39016. *
  39017. * @private
  39018. * @type {?Function}
  39019. * @default null
  39020. */
  39021. this._transparentSort = null;
  39022. /**
  39023. * The framebuffer target.
  39024. *
  39025. * @private
  39026. * @type {?RenderTarget}
  39027. * @default null
  39028. */
  39029. this._frameBufferTarget = null;
  39030. const alphaClear = this.alpha === true ? 0 : 1;
  39031. /**
  39032. * The clear color value.
  39033. *
  39034. * @private
  39035. * @type {Color4}
  39036. */
  39037. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  39038. /**
  39039. * The clear depth value.
  39040. *
  39041. * @private
  39042. * @type {number}
  39043. * @default 1
  39044. */
  39045. this._clearDepth = 1;
  39046. /**
  39047. * The clear stencil value.
  39048. *
  39049. * @private
  39050. * @type {number}
  39051. * @default 0
  39052. */
  39053. this._clearStencil = 0;
  39054. /**
  39055. * The current render target.
  39056. *
  39057. * @private
  39058. * @type {?RenderTarget}
  39059. * @default null
  39060. */
  39061. this._renderTarget = null;
  39062. /**
  39063. * The active cube face.
  39064. *
  39065. * @private
  39066. * @type {number}
  39067. * @default 0
  39068. */
  39069. this._activeCubeFace = 0;
  39070. /**
  39071. * The active mipmap level.
  39072. *
  39073. * @private
  39074. * @type {number}
  39075. * @default 0
  39076. */
  39077. this._activeMipmapLevel = 0;
  39078. /**
  39079. * The current output render target.
  39080. *
  39081. * @private
  39082. * @type {?RenderTarget}
  39083. * @default null
  39084. */
  39085. this._outputRenderTarget = null;
  39086. /**
  39087. * The MRT setting.
  39088. *
  39089. * @private
  39090. * @type {?MRTNode}
  39091. * @default null
  39092. */
  39093. this._mrt = null;
  39094. /**
  39095. * This function defines how a render object is going
  39096. * to be rendered.
  39097. *
  39098. * @private
  39099. * @type {?Function}
  39100. * @default null
  39101. */
  39102. this._renderObjectFunction = null;
  39103. /**
  39104. * Used to keep track of the current render object function.
  39105. *
  39106. * @private
  39107. * @type {?Function}
  39108. * @default null
  39109. */
  39110. this._currentRenderObjectFunction = null;
  39111. /**
  39112. * Used to keep track of the current render bundle.
  39113. *
  39114. * @private
  39115. * @type {?RenderBundle}
  39116. * @default null
  39117. */
  39118. this._currentRenderBundle = null;
  39119. /**
  39120. * Next to `_renderObjectFunction()`, this function provides another hook
  39121. * for influencing the render process of a render object. It is meant for internal
  39122. * use and only relevant for `compileAsync()` right now. Instead of using
  39123. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  39124. * a different function might be used which performs no draw but just the node
  39125. * and pipeline updates.
  39126. *
  39127. * @private
  39128. * @type {?Function}
  39129. * @default null
  39130. */
  39131. this._handleObjectFunction = this._renderObjectDirect;
  39132. /**
  39133. * Indicates whether the device has been lost or not. In WebGL terms, the device
  39134. * lost is considered as a context lost. When this is set to `true`, rendering
  39135. * isn't possible anymore.
  39136. *
  39137. * @private
  39138. * @type {boolean}
  39139. * @default false
  39140. */
  39141. this._isDeviceLost = false;
  39142. /**
  39143. * A callback function that defines what should happen when a device/context lost occurs.
  39144. *
  39145. * @type {Function}
  39146. */
  39147. this.onDeviceLost = this._onDeviceLost;
  39148. /**
  39149. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  39150. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  39151. * This will reduce rendering quality though.
  39152. *
  39153. * @private
  39154. * @type {number}
  39155. * @default HalfFloatType
  39156. */
  39157. this._colorBufferType = colorBufferType;
  39158. /**
  39159. * Whether the renderer has been initialized or not.
  39160. *
  39161. * @private
  39162. * @type {boolean}
  39163. * @default false
  39164. */
  39165. this._initialized = false;
  39166. /**
  39167. * A reference to the promise which initializes the renderer.
  39168. *
  39169. * @private
  39170. * @type {?Promise<this>}
  39171. * @default null
  39172. */
  39173. this._initPromise = null;
  39174. /**
  39175. * An array of compilation promises which are used in `compileAsync()`.
  39176. *
  39177. * @private
  39178. * @type {?Array<Promise>}
  39179. * @default null
  39180. */
  39181. this._compilationPromises = null;
  39182. /**
  39183. * Whether the renderer should render transparent render objects or not.
  39184. *
  39185. * @type {boolean}
  39186. * @default true
  39187. */
  39188. this.transparent = true;
  39189. /**
  39190. * Whether the renderer should render opaque render objects or not.
  39191. *
  39192. * @type {boolean}
  39193. * @default true
  39194. */
  39195. this.opaque = true;
  39196. /**
  39197. * Shadow map configuration
  39198. * @typedef {Object} ShadowMapConfig
  39199. * @property {boolean} enabled - Whether to globally enable shadows or not.
  39200. * @property {number} type - The shadow map type.
  39201. */
  39202. /**
  39203. * The renderer's shadow configuration.
  39204. *
  39205. * @type {ShadowMapConfig}
  39206. */
  39207. this.shadowMap = {
  39208. enabled: false,
  39209. type: PCFShadowMap
  39210. };
  39211. /**
  39212. * XR configuration.
  39213. * @typedef {Object} XRConfig
  39214. * @property {boolean} enabled - Whether to globally enable XR or not.
  39215. */
  39216. /**
  39217. * The renderer's XR manager.
  39218. *
  39219. * @type {XRManager}
  39220. */
  39221. this.xr = new XRManager( this, multiview );
  39222. /**
  39223. * Debug configuration.
  39224. * @typedef {Object} DebugConfig
  39225. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  39226. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  39227. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  39228. */
  39229. /**
  39230. * The renderer's debug configuration.
  39231. *
  39232. * @type {DebugConfig}
  39233. */
  39234. this.debug = {
  39235. checkShaderErrors: true,
  39236. onShaderError: null,
  39237. getShaderAsync: async ( scene, camera, object ) => {
  39238. await this.compileAsync( scene, camera );
  39239. const renderList = this._renderLists.get( scene, camera );
  39240. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  39241. const material = scene.overrideMaterial || object.material;
  39242. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  39243. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  39244. return { fragmentShader, vertexShader };
  39245. }
  39246. };
  39247. }
  39248. /**
  39249. * Initializes the renderer so it is ready for usage.
  39250. *
  39251. * @async
  39252. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  39253. */
  39254. async init() {
  39255. if ( this._initialized ) {
  39256. throw new Error( 'Renderer: Backend has already been initialized.' );
  39257. }
  39258. if ( this._initPromise !== null ) {
  39259. return this._initPromise;
  39260. }
  39261. this._initPromise = new Promise( async ( resolve, reject ) => {
  39262. let backend = this.backend;
  39263. try {
  39264. await backend.init( this );
  39265. } catch ( error ) {
  39266. if ( this._getFallback !== null ) {
  39267. // try the fallback
  39268. try {
  39269. this.backend = backend = this._getFallback( error );
  39270. await backend.init( this );
  39271. } catch ( error ) {
  39272. reject( error );
  39273. return;
  39274. }
  39275. } else {
  39276. reject( error );
  39277. return;
  39278. }
  39279. }
  39280. this._nodes = new Nodes( this, backend );
  39281. this._animation = new Animation( this._nodes, this.info );
  39282. this._attributes = new Attributes( backend );
  39283. this._background = new Background( this, this._nodes );
  39284. this._geometries = new Geometries( this._attributes, this.info );
  39285. this._textures = new Textures( this, backend, this.info );
  39286. this._pipelines = new Pipelines( backend, this._nodes );
  39287. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  39288. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  39289. this._renderLists = new RenderLists( this.lighting );
  39290. this._bundles = new RenderBundles();
  39291. this._renderContexts = new RenderContexts();
  39292. //
  39293. this._animation.start();
  39294. this._initialized = true;
  39295. resolve( this );
  39296. } );
  39297. return this._initPromise;
  39298. }
  39299. /**
  39300. * The coordinate system of the renderer. The value of this property
  39301. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  39302. * `THREE.WebGPUCoordinateSystem`.
  39303. *
  39304. * @readonly
  39305. * @type {number}
  39306. */
  39307. get coordinateSystem() {
  39308. return this.backend.coordinateSystem;
  39309. }
  39310. /**
  39311. * Compiles all materials in the given scene. This can be useful to avoid a
  39312. * phenomenon which is called "shader compilation stutter", which occurs when
  39313. * rendering an object with a new shader for the first time.
  39314. *
  39315. * If you want to add a 3D object to an existing scene, use the third optional
  39316. * parameter for applying the target scene. Note that the (target) scene's lighting
  39317. * and environment must be configured before calling this method.
  39318. *
  39319. * @async
  39320. * @param {Object3D} scene - The scene or 3D object to precompile.
  39321. * @param {Camera} camera - The camera that is used to render the scene.
  39322. * @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.
  39323. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  39324. */
  39325. async compileAsync( scene, camera, targetScene = null ) {
  39326. if ( this._isDeviceLost === true ) return;
  39327. if ( this._initialized === false ) await this.init();
  39328. // preserve render tree
  39329. const nodeFrame = this._nodes.nodeFrame;
  39330. const previousRenderId = nodeFrame.renderId;
  39331. const previousRenderContext = this._currentRenderContext;
  39332. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  39333. const previousCompilationPromises = this._compilationPromises;
  39334. //
  39335. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  39336. if ( targetScene === null ) targetScene = scene;
  39337. const renderTarget = this._renderTarget;
  39338. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  39339. const activeMipmapLevel = this._activeMipmapLevel;
  39340. const compilationPromises = [];
  39341. this._currentRenderContext = renderContext;
  39342. this._currentRenderObjectFunction = this.renderObject;
  39343. this._handleObjectFunction = this._createObjectPipeline;
  39344. this._compilationPromises = compilationPromises;
  39345. nodeFrame.renderId ++;
  39346. //
  39347. nodeFrame.update();
  39348. //
  39349. renderContext.depth = this.depth;
  39350. renderContext.stencil = this.stencil;
  39351. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  39352. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  39353. //
  39354. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  39355. //
  39356. const renderList = this._renderLists.get( scene, camera );
  39357. renderList.begin();
  39358. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  39359. // include lights from target scene
  39360. if ( targetScene !== scene ) {
  39361. targetScene.traverseVisible( function ( object ) {
  39362. if ( object.isLight && object.layers.test( camera.layers ) ) {
  39363. renderList.pushLight( object );
  39364. }
  39365. } );
  39366. }
  39367. renderList.finish();
  39368. //
  39369. if ( renderTarget !== null ) {
  39370. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  39371. const renderTargetData = this._textures.get( renderTarget );
  39372. renderContext.textures = renderTargetData.textures;
  39373. renderContext.depthTexture = renderTargetData.depthTexture;
  39374. } else {
  39375. renderContext.textures = null;
  39376. renderContext.depthTexture = null;
  39377. }
  39378. //
  39379. this._background.update( sceneRef, renderList, renderContext );
  39380. // process render lists
  39381. const opaqueObjects = renderList.opaque;
  39382. const transparentObjects = renderList.transparent;
  39383. const transparentDoublePassObjects = renderList.transparentDoublePass;
  39384. const lightsNode = renderList.lightsNode;
  39385. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39386. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39387. // restore render tree
  39388. nodeFrame.renderId = previousRenderId;
  39389. this._currentRenderContext = previousRenderContext;
  39390. this._currentRenderObjectFunction = previousRenderObjectFunction;
  39391. this._compilationPromises = previousCompilationPromises;
  39392. this._handleObjectFunction = this._renderObjectDirect;
  39393. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  39394. await Promise.all( compilationPromises );
  39395. }
  39396. /**
  39397. * Renders the scene in an async fashion.
  39398. *
  39399. * @async
  39400. * @param {Object3D} scene - The scene or 3D object to render.
  39401. * @param {Camera} camera - The camera.
  39402. * @return {Promise} A Promise that resolves when the render has been finished.
  39403. */
  39404. async renderAsync( scene, camera ) {
  39405. if ( this._initialized === false ) await this.init();
  39406. this._renderScene( scene, camera );
  39407. }
  39408. /**
  39409. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  39410. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  39411. *
  39412. * @async
  39413. * @return {Promise} A Promise that resolves when synchronization has been finished.
  39414. */
  39415. async waitForGPU() {
  39416. await this.backend.waitForGPU();
  39417. }
  39418. /**
  39419. * Enables or disables high precision for model-view and normal-view matrices.
  39420. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  39421. *
  39422. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  39423. *
  39424. * @param {boolean} value - Whether to enable or disable high precision.
  39425. * @type {boolean}
  39426. */
  39427. set highPrecision( value ) {
  39428. if ( value === true ) {
  39429. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  39430. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  39431. } else if ( this.highPrecision ) {
  39432. this.overrideNodes.modelViewMatrix = null;
  39433. this.overrideNodes.modelNormalViewMatrix = null;
  39434. }
  39435. }
  39436. /**
  39437. * Returns whether high precision is enabled or not.
  39438. *
  39439. * @return {boolean} Whether high precision is enabled or not.
  39440. * @type {boolean}
  39441. */
  39442. get highPrecision() {
  39443. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  39444. }
  39445. /**
  39446. * Sets the given MRT configuration.
  39447. *
  39448. * @param {MRTNode} mrt - The MRT node to set.
  39449. * @return {Renderer} A reference to this renderer.
  39450. */
  39451. setMRT( mrt ) {
  39452. this._mrt = mrt;
  39453. return this;
  39454. }
  39455. /**
  39456. * Returns the MRT configuration.
  39457. *
  39458. * @return {MRTNode} The MRT configuration.
  39459. */
  39460. getMRT() {
  39461. return this._mrt;
  39462. }
  39463. /**
  39464. * Returns the color buffer type.
  39465. *
  39466. * @return {number} The color buffer type.
  39467. */
  39468. getColorBufferType() {
  39469. return this._colorBufferType;
  39470. }
  39471. /**
  39472. * Default implementation of the device lost callback.
  39473. *
  39474. * @private
  39475. * @param {Object} info - Information about the context lost.
  39476. */
  39477. _onDeviceLost( info ) {
  39478. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  39479. if ( info.reason ) {
  39480. errorMessage += `\nReason: ${info.reason}`;
  39481. }
  39482. error( errorMessage );
  39483. this._isDeviceLost = true;
  39484. }
  39485. /**
  39486. * Renders the given render bundle.
  39487. *
  39488. * @private
  39489. * @param {Object} bundle - Render bundle data.
  39490. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  39491. * @param {LightsNode} lightsNode - The lights node.
  39492. */
  39493. _renderBundle( bundle, sceneRef, lightsNode ) {
  39494. const { bundleGroup, camera, renderList } = bundle;
  39495. const renderContext = this._currentRenderContext;
  39496. //
  39497. const renderBundle = this._bundles.get( bundleGroup, camera );
  39498. const renderBundleData = this.backend.get( renderBundle );
  39499. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  39500. //
  39501. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  39502. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  39503. renderBundleData.renderContexts.add( renderContext );
  39504. if ( renderBundleNeedsUpdate ) {
  39505. this.backend.beginBundle( renderContext );
  39506. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  39507. renderBundleData.renderObjects = [];
  39508. }
  39509. this._currentRenderBundle = renderBundle;
  39510. const {
  39511. transparentDoublePass: transparentDoublePassObjects,
  39512. transparent: transparentObjects,
  39513. opaque: opaqueObjects
  39514. } = renderList;
  39515. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39516. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39517. this._currentRenderBundle = null;
  39518. //
  39519. this.backend.finishBundle( renderContext, renderBundle );
  39520. renderBundleData.version = bundleGroup.version;
  39521. } else {
  39522. const { renderObjects } = renderBundleData;
  39523. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  39524. const renderObject = renderObjects[ i ];
  39525. if ( this._nodes.needsRefresh( renderObject ) ) {
  39526. this._nodes.updateBefore( renderObject );
  39527. this._nodes.updateForRender( renderObject );
  39528. this._bindings.updateForRender( renderObject );
  39529. this._nodes.updateAfter( renderObject );
  39530. }
  39531. }
  39532. }
  39533. this.backend.addBundle( renderContext, renderBundle );
  39534. }
  39535. /**
  39536. * Renders the scene or 3D object with the given camera. This method can only be called
  39537. * if the renderer has been initialized.
  39538. *
  39539. * The target of the method is the default framebuffer (meaning the canvas)
  39540. * or alternatively a render target when specified via `setRenderTarget()`.
  39541. *
  39542. * @param {Object3D} scene - The scene or 3D object to render.
  39543. * @param {Camera} camera - The camera to render the scene with.
  39544. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  39545. * Only returned when the renderer has not been initialized.
  39546. */
  39547. render( scene, camera ) {
  39548. if ( this._initialized === false ) {
  39549. warn( 'Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  39550. return this.renderAsync( scene, camera );
  39551. }
  39552. this._renderScene( scene, camera );
  39553. }
  39554. /**
  39555. * Returns an internal render target which is used when computing the output tone mapping
  39556. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  39557. * pass and not inline to achieve more correct results.
  39558. *
  39559. * @private
  39560. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  39561. */
  39562. _getFrameBufferTarget() {
  39563. const { currentToneMapping, currentColorSpace } = this;
  39564. const useToneMapping = currentToneMapping !== NoToneMapping;
  39565. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  39566. if ( useToneMapping === false && useColorSpace === false ) return null;
  39567. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  39568. const { depth, stencil } = this;
  39569. let frameBufferTarget = this._frameBufferTarget;
  39570. if ( frameBufferTarget === null ) {
  39571. frameBufferTarget = new RenderTarget( width, height, {
  39572. depthBuffer: depth,
  39573. stencilBuffer: stencil,
  39574. type: this._colorBufferType,
  39575. format: RGBAFormat,
  39576. colorSpace: ColorManagement.workingColorSpace,
  39577. generateMipmaps: false,
  39578. minFilter: LinearFilter,
  39579. magFilter: LinearFilter,
  39580. samples: this.samples
  39581. } );
  39582. frameBufferTarget.isPostProcessingRenderTarget = true;
  39583. this._frameBufferTarget = frameBufferTarget;
  39584. }
  39585. const outputRenderTarget = this.getOutputRenderTarget();
  39586. frameBufferTarget.depthBuffer = depth;
  39587. frameBufferTarget.stencilBuffer = stencil;
  39588. if ( outputRenderTarget !== null ) {
  39589. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  39590. } else {
  39591. frameBufferTarget.setSize( width, height, 1 );
  39592. }
  39593. frameBufferTarget.viewport.copy( this._viewport );
  39594. frameBufferTarget.scissor.copy( this._scissor );
  39595. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  39596. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  39597. frameBufferTarget.scissorTest = this._scissorTest;
  39598. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  39599. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  39600. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  39601. return frameBufferTarget;
  39602. }
  39603. /**
  39604. * Renders the scene or 3D object with the given camera.
  39605. *
  39606. * @private
  39607. * @param {Object3D} scene - The scene or 3D object to render.
  39608. * @param {Camera} camera - The camera to render the scene with.
  39609. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  39610. * @return {RenderContext} The current render context.
  39611. */
  39612. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  39613. if ( this._isDeviceLost === true ) return;
  39614. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  39615. // preserve render tree
  39616. const nodeFrame = this._nodes.nodeFrame;
  39617. const previousRenderId = nodeFrame.renderId;
  39618. const previousRenderContext = this._currentRenderContext;
  39619. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  39620. //
  39621. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  39622. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  39623. const activeCubeFace = this._activeCubeFace;
  39624. const activeMipmapLevel = this._activeMipmapLevel;
  39625. //
  39626. let renderTarget;
  39627. if ( frameBufferTarget !== null ) {
  39628. renderTarget = frameBufferTarget;
  39629. this.setRenderTarget( renderTarget );
  39630. } else {
  39631. renderTarget = outputRenderTarget;
  39632. }
  39633. //
  39634. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  39635. this._currentRenderContext = renderContext;
  39636. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  39637. //
  39638. this.info.calls ++;
  39639. this.info.render.calls ++;
  39640. this.info.render.frameCalls ++;
  39641. nodeFrame.renderId = this.info.calls;
  39642. //
  39643. const coordinateSystem = this.coordinateSystem;
  39644. const xr = this.xr;
  39645. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  39646. camera.coordinateSystem = coordinateSystem;
  39647. camera.updateProjectionMatrix();
  39648. if ( camera.isArrayCamera ) {
  39649. for ( const subCamera of camera.cameras ) {
  39650. subCamera.coordinateSystem = coordinateSystem;
  39651. subCamera.updateProjectionMatrix();
  39652. }
  39653. }
  39654. }
  39655. //
  39656. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  39657. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  39658. if ( xr.enabled === true && xr.isPresenting === true ) {
  39659. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  39660. camera = xr.getCamera(); // use XR camera for rendering
  39661. }
  39662. //
  39663. let viewport = this._viewport;
  39664. let scissor = this._scissor;
  39665. let pixelRatio = this._pixelRatio;
  39666. if ( renderTarget !== null ) {
  39667. viewport = renderTarget.viewport;
  39668. scissor = renderTarget.scissor;
  39669. pixelRatio = 1;
  39670. }
  39671. this.getDrawingBufferSize( _drawingBufferSize );
  39672. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  39673. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  39674. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  39675. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  39676. renderContext.viewportValue.width >>= activeMipmapLevel;
  39677. renderContext.viewportValue.height >>= activeMipmapLevel;
  39678. renderContext.viewportValue.minDepth = minDepth;
  39679. renderContext.viewportValue.maxDepth = maxDepth;
  39680. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  39681. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  39682. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  39683. renderContext.scissorValue.width >>= activeMipmapLevel;
  39684. renderContext.scissorValue.height >>= activeMipmapLevel;
  39685. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  39686. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  39687. //
  39688. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  39689. //
  39690. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  39691. if ( ! camera.isArrayCamera ) {
  39692. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  39693. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  39694. }
  39695. const renderList = this._renderLists.get( scene, camera );
  39696. renderList.begin();
  39697. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  39698. renderList.finish();
  39699. if ( this.sortObjects === true ) {
  39700. renderList.sort( this._opaqueSort, this._transparentSort );
  39701. }
  39702. //
  39703. if ( renderTarget !== null ) {
  39704. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  39705. const renderTargetData = this._textures.get( renderTarget );
  39706. renderContext.textures = renderTargetData.textures;
  39707. renderContext.depthTexture = renderTargetData.depthTexture;
  39708. renderContext.width = renderTargetData.width;
  39709. renderContext.height = renderTargetData.height;
  39710. renderContext.renderTarget = renderTarget;
  39711. renderContext.depth = renderTarget.depthBuffer;
  39712. renderContext.stencil = renderTarget.stencilBuffer;
  39713. } else {
  39714. renderContext.textures = null;
  39715. renderContext.depthTexture = null;
  39716. renderContext.width = _drawingBufferSize.width;
  39717. renderContext.height = _drawingBufferSize.height;
  39718. renderContext.depth = this.depth;
  39719. renderContext.stencil = this.stencil;
  39720. }
  39721. renderContext.width >>= activeMipmapLevel;
  39722. renderContext.height >>= activeMipmapLevel;
  39723. renderContext.activeCubeFace = activeCubeFace;
  39724. renderContext.activeMipmapLevel = activeMipmapLevel;
  39725. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  39726. //
  39727. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  39728. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  39729. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  39730. }
  39731. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  39732. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  39733. }
  39734. //
  39735. this._background.update( sceneRef, renderList, renderContext );
  39736. //
  39737. renderContext.camera = camera;
  39738. this.backend.beginRender( renderContext );
  39739. // process render lists
  39740. const {
  39741. bundles,
  39742. lightsNode,
  39743. transparentDoublePass: transparentDoublePassObjects,
  39744. transparent: transparentObjects,
  39745. opaque: opaqueObjects
  39746. } = renderList;
  39747. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  39748. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39749. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39750. // finish render pass
  39751. this.backend.finishRender( renderContext );
  39752. // restore render tree
  39753. nodeFrame.renderId = previousRenderId;
  39754. this._currentRenderContext = previousRenderContext;
  39755. this._currentRenderObjectFunction = previousRenderObjectFunction;
  39756. //
  39757. if ( frameBufferTarget !== null ) {
  39758. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  39759. this._renderOutput( renderTarget );
  39760. }
  39761. //
  39762. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  39763. //
  39764. return renderContext;
  39765. }
  39766. _setXRLayerSize( width, height ) {
  39767. this._width = width;
  39768. this._height = height;
  39769. this.setViewport( 0, 0, width, height );
  39770. }
  39771. /**
  39772. * The output pass performs tone mapping and color space conversion.
  39773. *
  39774. * @private
  39775. * @param {RenderTarget} renderTarget - The current render target.
  39776. */
  39777. _renderOutput( renderTarget ) {
  39778. const quad = this._quad;
  39779. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  39780. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  39781. quad.material.needsUpdate = true;
  39782. }
  39783. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  39784. const currentAutoClear = this.autoClear;
  39785. const currentXR = this.xr.enabled;
  39786. this.autoClear = false;
  39787. this.xr.enabled = false;
  39788. this._renderScene( quad, quad.camera, false );
  39789. this.autoClear = currentAutoClear;
  39790. this.xr.enabled = currentXR;
  39791. }
  39792. /**
  39793. * Returns the maximum available anisotropy for texture filtering.
  39794. *
  39795. * @return {number} The maximum available anisotropy.
  39796. */
  39797. getMaxAnisotropy() {
  39798. return this.backend.getMaxAnisotropy();
  39799. }
  39800. /**
  39801. * Returns the active cube face.
  39802. *
  39803. * @return {number} The active cube face.
  39804. */
  39805. getActiveCubeFace() {
  39806. return this._activeCubeFace;
  39807. }
  39808. /**
  39809. * Returns the active mipmap level.
  39810. *
  39811. * @return {number} The active mipmap level.
  39812. */
  39813. getActiveMipmapLevel() {
  39814. return this._activeMipmapLevel;
  39815. }
  39816. /**
  39817. * Applications are advised to always define the animation loop
  39818. * with this method and not manually with `requestAnimationFrame()`
  39819. * for best compatibility.
  39820. *
  39821. * @async
  39822. * @param {?onAnimationCallback} callback - The application's animation loop.
  39823. * @return {Promise} A Promise that resolves when the set has been executed.
  39824. */
  39825. async setAnimationLoop( callback ) {
  39826. if ( this._initialized === false ) await this.init();
  39827. this._animation.setAnimationLoop( callback );
  39828. }
  39829. /**
  39830. * Can be used to transfer buffer data from a storage buffer attribute
  39831. * from the GPU to the CPU in context of compute shaders.
  39832. *
  39833. * @async
  39834. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39835. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39836. */
  39837. async getArrayBufferAsync( attribute ) {
  39838. return await this.backend.getArrayBufferAsync( attribute );
  39839. }
  39840. /**
  39841. * Returns the rendering context.
  39842. *
  39843. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  39844. */
  39845. getContext() {
  39846. return this.backend.getContext();
  39847. }
  39848. /**
  39849. * Returns the pixel ratio.
  39850. *
  39851. * @return {number} The pixel ratio.
  39852. */
  39853. getPixelRatio() {
  39854. return this._pixelRatio;
  39855. }
  39856. /**
  39857. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39858. *
  39859. * @param {Vector2} target - The method writes the result in this target object.
  39860. * @return {Vector2} The drawing buffer size.
  39861. */
  39862. getDrawingBufferSize( target ) {
  39863. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39864. }
  39865. /**
  39866. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39867. *
  39868. * @param {Vector2} target - The method writes the result in this target object.
  39869. * @return {Vector2} The renderer's size in logical pixels.
  39870. */
  39871. getSize( target ) {
  39872. return target.set( this._width, this._height );
  39873. }
  39874. /**
  39875. * Sets the given pixel ratio and resizes the canvas if necessary.
  39876. *
  39877. * @param {number} [value=1] - The pixel ratio.
  39878. */
  39879. setPixelRatio( value = 1 ) {
  39880. if ( this._pixelRatio === value ) return;
  39881. this._pixelRatio = value;
  39882. this.setSize( this._width, this._height, false );
  39883. }
  39884. /**
  39885. * This method allows to define the drawing buffer size by specifying
  39886. * width, height and pixel ratio all at once. The size of the drawing
  39887. * buffer is computed with this formula:
  39888. * ```js
  39889. * size.x = width * pixelRatio;
  39890. * size.y = height * pixelRatio;
  39891. * ```
  39892. *
  39893. * @param {number} width - The width in logical pixels.
  39894. * @param {number} height - The height in logical pixels.
  39895. * @param {number} pixelRatio - The pixel ratio.
  39896. */
  39897. setDrawingBufferSize( width, height, pixelRatio ) {
  39898. // Renderer can't be resized while presenting in XR.
  39899. if ( this.xr && this.xr.isPresenting ) return;
  39900. this._width = width;
  39901. this._height = height;
  39902. this._pixelRatio = pixelRatio;
  39903. this.domElement.width = Math.floor( width * pixelRatio );
  39904. this.domElement.height = Math.floor( height * pixelRatio );
  39905. this.setViewport( 0, 0, width, height );
  39906. if ( this._initialized ) this.backend.updateSize();
  39907. }
  39908. /**
  39909. * Sets the size of the renderer.
  39910. *
  39911. * @param {number} width - The width in logical pixels.
  39912. * @param {number} height - The height in logical pixels.
  39913. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39914. */
  39915. setSize( width, height, updateStyle = true ) {
  39916. // Renderer can't be resized while presenting in XR.
  39917. if ( this.xr && this.xr.isPresenting ) return;
  39918. this._width = width;
  39919. this._height = height;
  39920. this.domElement.width = Math.floor( width * this._pixelRatio );
  39921. this.domElement.height = Math.floor( height * this._pixelRatio );
  39922. if ( updateStyle === true ) {
  39923. this.domElement.style.width = width + 'px';
  39924. this.domElement.style.height = height + 'px';
  39925. }
  39926. this.setViewport( 0, 0, width, height );
  39927. if ( this._initialized ) this.backend.updateSize();
  39928. }
  39929. /**
  39930. * Defines a manual sort function for the opaque render list.
  39931. * Pass `null` to use the default sort.
  39932. *
  39933. * @param {Function} method - The sort function.
  39934. */
  39935. setOpaqueSort( method ) {
  39936. this._opaqueSort = method;
  39937. }
  39938. /**
  39939. * Defines a manual sort function for the transparent render list.
  39940. * Pass `null` to use the default sort.
  39941. *
  39942. * @param {Function} method - The sort function.
  39943. */
  39944. setTransparentSort( method ) {
  39945. this._transparentSort = method;
  39946. }
  39947. /**
  39948. * Returns the scissor rectangle.
  39949. *
  39950. * @param {Vector4} target - The method writes the result in this target object.
  39951. * @return {Vector4} The scissor rectangle.
  39952. */
  39953. getScissor( target ) {
  39954. const scissor = this._scissor;
  39955. target.x = scissor.x;
  39956. target.y = scissor.y;
  39957. target.width = scissor.width;
  39958. target.height = scissor.height;
  39959. return target;
  39960. }
  39961. /**
  39962. * Defines the scissor rectangle.
  39963. *
  39964. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39965. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39966. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39967. * @param {number} width - The width of the scissor box in logical pixel unit.
  39968. * @param {number} height - The height of the scissor box in logical pixel unit.
  39969. */
  39970. setScissor( x, y, width, height ) {
  39971. const scissor = this._scissor;
  39972. if ( x.isVector4 ) {
  39973. scissor.copy( x );
  39974. } else {
  39975. scissor.set( x, y, width, height );
  39976. }
  39977. }
  39978. /**
  39979. * Returns the scissor test value.
  39980. *
  39981. * @return {boolean} Whether the scissor test should be enabled or not.
  39982. */
  39983. getScissorTest() {
  39984. return this._scissorTest;
  39985. }
  39986. /**
  39987. * Defines the scissor test.
  39988. *
  39989. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39990. */
  39991. setScissorTest( boolean ) {
  39992. this._scissorTest = boolean;
  39993. this.backend.setScissorTest( boolean );
  39994. }
  39995. /**
  39996. * Returns the viewport definition.
  39997. *
  39998. * @param {Vector4} target - The method writes the result in this target object.
  39999. * @return {Vector4} The viewport definition.
  40000. */
  40001. getViewport( target ) {
  40002. return target.copy( this._viewport );
  40003. }
  40004. /**
  40005. * Defines the viewport.
  40006. *
  40007. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40008. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  40009. * @param {number} width - The width of the viewport in logical pixel unit.
  40010. * @param {number} height - The height of the viewport in logical pixel unit.
  40011. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  40012. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  40013. */
  40014. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  40015. const viewport = this._viewport;
  40016. if ( x.isVector4 ) {
  40017. viewport.copy( x );
  40018. } else {
  40019. viewport.set( x, y, width, height );
  40020. }
  40021. viewport.minDepth = minDepth;
  40022. viewport.maxDepth = maxDepth;
  40023. }
  40024. /**
  40025. * Returns the clear color.
  40026. *
  40027. * @param {Color} target - The method writes the result in this target object.
  40028. * @return {Color} The clear color.
  40029. */
  40030. getClearColor( target ) {
  40031. return target.copy( this._clearColor );
  40032. }
  40033. /**
  40034. * Defines the clear color and optionally the clear alpha.
  40035. *
  40036. * @param {Color} color - The clear color.
  40037. * @param {number} [alpha=1] - The clear alpha.
  40038. */
  40039. setClearColor( color, alpha = 1 ) {
  40040. this._clearColor.set( color );
  40041. this._clearColor.a = alpha;
  40042. }
  40043. /**
  40044. * Returns the clear alpha.
  40045. *
  40046. * @return {number} The clear alpha.
  40047. */
  40048. getClearAlpha() {
  40049. return this._clearColor.a;
  40050. }
  40051. /**
  40052. * Defines the clear alpha.
  40053. *
  40054. * @param {number} alpha - The clear alpha.
  40055. */
  40056. setClearAlpha( alpha ) {
  40057. this._clearColor.a = alpha;
  40058. }
  40059. /**
  40060. * Returns the clear depth.
  40061. *
  40062. * @return {number} The clear depth.
  40063. */
  40064. getClearDepth() {
  40065. return this._clearDepth;
  40066. }
  40067. /**
  40068. * Defines the clear depth.
  40069. *
  40070. * @param {number} depth - The clear depth.
  40071. */
  40072. setClearDepth( depth ) {
  40073. this._clearDepth = depth;
  40074. }
  40075. /**
  40076. * Returns the clear stencil.
  40077. *
  40078. * @return {number} The clear stencil.
  40079. */
  40080. getClearStencil() {
  40081. return this._clearStencil;
  40082. }
  40083. /**
  40084. * Defines the clear stencil.
  40085. *
  40086. * @param {number} stencil - The clear stencil.
  40087. */
  40088. setClearStencil( stencil ) {
  40089. this._clearStencil = stencil;
  40090. }
  40091. /**
  40092. * This method performs an occlusion query for the given 3D object.
  40093. * It returns `true` if the given 3D object is fully occluded by other
  40094. * 3D objects in the scene.
  40095. *
  40096. * @param {Object3D} object - The 3D object to test.
  40097. * @return {boolean} Whether the 3D object is fully occluded or not.
  40098. */
  40099. isOccluded( object ) {
  40100. const renderContext = this._currentRenderContext;
  40101. return renderContext && this.backend.isOccluded( renderContext, object );
  40102. }
  40103. /**
  40104. * Performs a manual clear operation. This method ignores `autoClear` properties.
  40105. *
  40106. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40107. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40108. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40109. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40110. * Only returned when the renderer has not been initialized.
  40111. */
  40112. clear( color = true, depth = true, stencil = true ) {
  40113. if ( this._initialized === false ) {
  40114. warn( 'Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  40115. return this.clearAsync( color, depth, stencil );
  40116. }
  40117. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40118. let renderContext = null;
  40119. if ( renderTarget !== null ) {
  40120. this._textures.updateRenderTarget( renderTarget );
  40121. const renderTargetData = this._textures.get( renderTarget );
  40122. renderContext = this._renderContexts.getForClear( renderTarget );
  40123. renderContext.textures = renderTargetData.textures;
  40124. renderContext.depthTexture = renderTargetData.depthTexture;
  40125. renderContext.width = renderTargetData.width;
  40126. renderContext.height = renderTargetData.height;
  40127. renderContext.renderTarget = renderTarget;
  40128. renderContext.depth = renderTarget.depthBuffer;
  40129. renderContext.stencil = renderTarget.stencilBuffer;
  40130. // #30329
  40131. renderContext.clearColorValue = this.backend.getClearColor();
  40132. renderContext.activeCubeFace = this.getActiveCubeFace();
  40133. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  40134. }
  40135. this.backend.clear( color, depth, stencil, renderContext );
  40136. if ( renderTarget !== null && this._renderTarget === null ) {
  40137. this._renderOutput( renderTarget );
  40138. }
  40139. }
  40140. /**
  40141. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  40142. *
  40143. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40144. * Only returned when the renderer has not been initialized.
  40145. */
  40146. clearColor() {
  40147. return this.clear( true, false, false );
  40148. }
  40149. /**
  40150. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  40151. *
  40152. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40153. * Only returned when the renderer has not been initialized.
  40154. */
  40155. clearDepth() {
  40156. return this.clear( false, true, false );
  40157. }
  40158. /**
  40159. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  40160. *
  40161. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40162. * Only returned when the renderer has not been initialized.
  40163. */
  40164. clearStencil() {
  40165. return this.clear( false, false, true );
  40166. }
  40167. /**
  40168. * Async version of {@link Renderer#clear}.
  40169. *
  40170. * @async
  40171. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40172. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40173. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40174. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40175. */
  40176. async clearAsync( color = true, depth = true, stencil = true ) {
  40177. if ( this._initialized === false ) await this.init();
  40178. this.clear( color, depth, stencil );
  40179. }
  40180. /**
  40181. * Async version of {@link Renderer#clearColor}.
  40182. *
  40183. * @async
  40184. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40185. */
  40186. async clearColorAsync() {
  40187. this.clearAsync( true, false, false );
  40188. }
  40189. /**
  40190. * Async version of {@link Renderer#clearDepth}.
  40191. *
  40192. * @async
  40193. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40194. */
  40195. async clearDepthAsync() {
  40196. this.clearAsync( false, true, false );
  40197. }
  40198. /**
  40199. * Async version of {@link Renderer#clearStencil}.
  40200. *
  40201. * @async
  40202. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40203. */
  40204. async clearStencilAsync() {
  40205. this.clearAsync( false, false, true );
  40206. }
  40207. /**
  40208. * The current tone mapping of the renderer. When not producing screen output,
  40209. * the tone mapping is always `NoToneMapping`.
  40210. *
  40211. * @type {number}
  40212. */
  40213. get currentToneMapping() {
  40214. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  40215. }
  40216. /**
  40217. * The current color space of the renderer. When not producing screen output,
  40218. * the color space is always the working color space.
  40219. *
  40220. * @type {string}
  40221. */
  40222. get currentColorSpace() {
  40223. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  40224. }
  40225. /**
  40226. * Returns `true` if the rendering settings are set to screen output.
  40227. *
  40228. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  40229. */
  40230. get isOutputTarget() {
  40231. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  40232. }
  40233. /**
  40234. * Frees all internal resources of the renderer. Call this method if the renderer
  40235. * is no longer in use by your app.
  40236. */
  40237. dispose() {
  40238. if ( this._initialized === true ) {
  40239. this.info.dispose();
  40240. this.backend.dispose();
  40241. this._animation.dispose();
  40242. this._objects.dispose();
  40243. this._pipelines.dispose();
  40244. this._nodes.dispose();
  40245. this._bindings.dispose();
  40246. this._renderLists.dispose();
  40247. this._renderContexts.dispose();
  40248. this._textures.dispose();
  40249. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  40250. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  40251. if ( queryPool !== null ) queryPool.dispose();
  40252. } );
  40253. }
  40254. this.setRenderTarget( null );
  40255. this.setAnimationLoop( null );
  40256. }
  40257. /**
  40258. * Sets the given render target. Calling this method means the renderer does not
  40259. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  40260. * Use `null` as the first argument to reset the state.
  40261. *
  40262. * @param {?RenderTarget} renderTarget - The render target to set.
  40263. * @param {number} [activeCubeFace=0] - The active cube face.
  40264. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  40265. */
  40266. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  40267. this._renderTarget = renderTarget;
  40268. this._activeCubeFace = activeCubeFace;
  40269. this._activeMipmapLevel = activeMipmapLevel;
  40270. }
  40271. /**
  40272. * Returns the current render target.
  40273. *
  40274. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  40275. */
  40276. getRenderTarget() {
  40277. return this._renderTarget;
  40278. }
  40279. /**
  40280. * Sets the output render target for the renderer.
  40281. *
  40282. * @param {Object} renderTarget - The render target to set as the output target.
  40283. */
  40284. setOutputRenderTarget( renderTarget ) {
  40285. this._outputRenderTarget = renderTarget;
  40286. }
  40287. /**
  40288. * Returns the current output target.
  40289. *
  40290. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  40291. */
  40292. getOutputRenderTarget() {
  40293. return this._outputRenderTarget;
  40294. }
  40295. /**
  40296. * Resets the renderer to the initial state before WebXR started.
  40297. *
  40298. */
  40299. _resetXRState() {
  40300. this.backend.setXRTarget( null );
  40301. this.setOutputRenderTarget( null );
  40302. this.setRenderTarget( null );
  40303. this._frameBufferTarget.dispose();
  40304. this._frameBufferTarget = null;
  40305. }
  40306. /**
  40307. * Callback for {@link Renderer#setRenderObjectFunction}.
  40308. *
  40309. * @callback renderObjectFunction
  40310. * @param {Object3D} object - The 3D object.
  40311. * @param {Scene} scene - The scene the 3D object belongs to.
  40312. * @param {Camera} camera - The camera the object should be rendered with.
  40313. * @param {BufferGeometry} geometry - The object's geometry.
  40314. * @param {Material} material - The object's material.
  40315. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40316. * @param {LightsNode} lightsNode - The current lights node.
  40317. * @param {ClippingContext} clippingContext - The clipping context.
  40318. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40319. */
  40320. /**
  40321. * Sets the given render object function. Calling this method overwrites the default implementation
  40322. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  40323. * if you want to modify the way objects are rendered. For example you can define things like "every
  40324. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  40325. * The custom function must always call `renderObject()` in its implementation.
  40326. *
  40327. * Use `null` as the first argument to reset the state.
  40328. *
  40329. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  40330. */
  40331. setRenderObjectFunction( renderObjectFunction ) {
  40332. this._renderObjectFunction = renderObjectFunction;
  40333. }
  40334. /**
  40335. * Returns the current render object function.
  40336. *
  40337. * @return {?Function} The current render object function. Returns `null` if no function is set.
  40338. */
  40339. getRenderObjectFunction() {
  40340. return this._renderObjectFunction;
  40341. }
  40342. /**
  40343. * Execute a single or an array of compute nodes. This method can only be called
  40344. * if the renderer has been initialized.
  40345. *
  40346. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  40347. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  40348. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  40349. */
  40350. compute( computeNodes, dispatchSizeOrCount = null ) {
  40351. if ( this._isDeviceLost === true ) return;
  40352. if ( this._initialized === false ) {
  40353. warn( 'Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  40354. return this.computeAsync( computeNodes );
  40355. }
  40356. //
  40357. const nodeFrame = this._nodes.nodeFrame;
  40358. const previousRenderId = nodeFrame.renderId;
  40359. //
  40360. this.info.calls ++;
  40361. this.info.compute.calls ++;
  40362. this.info.compute.frameCalls ++;
  40363. nodeFrame.renderId = this.info.calls;
  40364. //
  40365. const backend = this.backend;
  40366. const pipelines = this._pipelines;
  40367. const bindings = this._bindings;
  40368. const nodes = this._nodes;
  40369. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  40370. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  40371. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  40372. }
  40373. backend.beginCompute( computeNodes );
  40374. for ( const computeNode of computeList ) {
  40375. // onInit
  40376. if ( pipelines.has( computeNode ) === false ) {
  40377. const dispose = () => {
  40378. computeNode.removeEventListener( 'dispose', dispose );
  40379. pipelines.delete( computeNode );
  40380. bindings.deleteForCompute( computeNode );
  40381. nodes.delete( computeNode );
  40382. };
  40383. computeNode.addEventListener( 'dispose', dispose );
  40384. //
  40385. const onInitFn = computeNode.onInitFunction;
  40386. if ( onInitFn !== null ) {
  40387. onInitFn.call( computeNode, { renderer: this } );
  40388. }
  40389. }
  40390. nodes.updateForCompute( computeNode );
  40391. bindings.updateForCompute( computeNode );
  40392. const computeBindings = bindings.getForCompute( computeNode );
  40393. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  40394. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  40395. }
  40396. backend.finishCompute( computeNodes );
  40397. //
  40398. nodeFrame.renderId = previousRenderId;
  40399. }
  40400. /**
  40401. * Execute a single or an array of compute nodes.
  40402. *
  40403. * @async
  40404. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  40405. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  40406. * @return {Promise} A Promise that resolve when the compute has finished.
  40407. */
  40408. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  40409. if ( this._initialized === false ) await this.init();
  40410. this.compute( computeNodes, dispatchSizeOrCount );
  40411. }
  40412. /**
  40413. * Checks if the given feature is supported by the selected backend.
  40414. *
  40415. * @async
  40416. * @param {string} name - The feature's name.
  40417. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  40418. */
  40419. async hasFeatureAsync( name ) {
  40420. if ( this._initialized === false ) await this.init();
  40421. return this.backend.hasFeature( name );
  40422. }
  40423. async resolveTimestampsAsync( type = 'render' ) {
  40424. if ( this._initialized === false ) await this.init();
  40425. return this.backend.resolveTimestampsAsync( type );
  40426. }
  40427. /**
  40428. * Checks if the given feature is supported by the selected backend. If the
  40429. * renderer has not been initialized, this method always returns `false`.
  40430. *
  40431. * @param {string} name - The feature's name.
  40432. * @return {boolean} Whether the feature is supported or not.
  40433. */
  40434. hasFeature( name ) {
  40435. if ( this._initialized === false ) {
  40436. warn( 'Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  40437. return false;
  40438. }
  40439. return this.backend.hasFeature( name );
  40440. }
  40441. /**
  40442. * Returns `true` when the renderer has been initialized.
  40443. *
  40444. * @return {boolean} Whether the renderer has been initialized or not.
  40445. */
  40446. hasInitialized() {
  40447. return this._initialized;
  40448. }
  40449. /**
  40450. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  40451. * (which can cause noticeable lags due to decode and GPU upload overhead).
  40452. *
  40453. * @async
  40454. * @param {Texture} texture - The texture.
  40455. * @return {Promise} A Promise that resolves when the texture has been initialized.
  40456. */
  40457. async initTextureAsync( texture ) {
  40458. if ( this._initialized === false ) await this.init();
  40459. this._textures.updateTexture( texture );
  40460. }
  40461. /**
  40462. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  40463. * (which can cause noticeable lags due to decode and GPU upload overhead).
  40464. *
  40465. * This method can only be used if the renderer has been initialized.
  40466. *
  40467. * @param {Texture} texture - The texture.
  40468. */
  40469. initTexture( texture ) {
  40470. if ( this._initialized === false ) {
  40471. warn( 'Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  40472. }
  40473. this._textures.updateTexture( texture );
  40474. }
  40475. /**
  40476. * Copies the current bound framebuffer into the given texture.
  40477. *
  40478. * @param {FramebufferTexture} framebufferTexture - The texture.
  40479. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  40480. */
  40481. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  40482. if ( rectangle !== null ) {
  40483. if ( rectangle.isVector2 ) {
  40484. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  40485. } else if ( rectangle.isVector4 ) {
  40486. rectangle = _vector4.copy( rectangle ).floor();
  40487. } else {
  40488. error( 'Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  40489. return;
  40490. }
  40491. } else {
  40492. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  40493. }
  40494. //
  40495. let renderContext = this._currentRenderContext;
  40496. let renderTarget;
  40497. if ( renderContext !== null ) {
  40498. renderTarget = renderContext.renderTarget;
  40499. } else {
  40500. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40501. if ( renderTarget !== null ) {
  40502. this._textures.updateRenderTarget( renderTarget );
  40503. renderContext = this._textures.get( renderTarget );
  40504. }
  40505. }
  40506. //
  40507. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  40508. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  40509. }
  40510. /**
  40511. * Copies data of the given source texture into a destination texture.
  40512. *
  40513. * @param {Texture} srcTexture - The source texture.
  40514. * @param {Texture} dstTexture - The destination texture.
  40515. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  40516. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  40517. * @param {number} [srcLevel=0] - The source mip level to copy from.
  40518. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  40519. */
  40520. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  40521. this._textures.updateTexture( srcTexture );
  40522. this._textures.updateTexture( dstTexture );
  40523. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  40524. }
  40525. /**
  40526. * Reads pixel data from the given render target.
  40527. *
  40528. * @async
  40529. * @param {RenderTarget} renderTarget - The render target to read from.
  40530. * @param {number} x - The `x` coordinate of the copy region's origin.
  40531. * @param {number} y - The `y` coordinate of the copy region's origin.
  40532. * @param {number} width - The width of the copy region.
  40533. * @param {number} height - The height of the copy region.
  40534. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  40535. * @param {number} [faceIndex=0] - The active cube face index.
  40536. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  40537. */
  40538. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  40539. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  40540. }
  40541. /**
  40542. * Analyzes the given 3D object's hierarchy and builds render lists from the
  40543. * processed hierarchy.
  40544. *
  40545. * @param {Object3D} object - The 3D object to process (usually a scene).
  40546. * @param {Camera} camera - The camera the object is rendered with.
  40547. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  40548. * @param {RenderList} renderList - The current render list.
  40549. * @param {ClippingContext} clippingContext - The current clipping context.
  40550. */
  40551. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  40552. if ( object.visible === false ) return;
  40553. const visible = object.layers.test( camera.layers );
  40554. if ( visible ) {
  40555. if ( object.isGroup ) {
  40556. groupOrder = object.renderOrder;
  40557. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  40558. } else if ( object.isLOD ) {
  40559. if ( object.autoUpdate === true ) object.update( camera );
  40560. } else if ( object.isLight ) {
  40561. renderList.pushLight( object );
  40562. } else if ( object.isSprite ) {
  40563. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40564. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  40565. if ( this.sortObjects === true ) {
  40566. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  40567. }
  40568. const { geometry, material } = object;
  40569. if ( material.visible ) {
  40570. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  40571. }
  40572. }
  40573. } else if ( object.isLineLoop ) {
  40574. error( 'Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  40575. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  40576. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40577. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  40578. const { geometry, material } = object;
  40579. if ( this.sortObjects === true ) {
  40580. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  40581. _vector4
  40582. .copy( geometry.boundingSphere.center )
  40583. .applyMatrix4( object.matrixWorld )
  40584. .applyMatrix4( _projScreenMatrix );
  40585. }
  40586. if ( Array.isArray( material ) ) {
  40587. const groups = geometry.groups;
  40588. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  40589. const group = groups[ i ];
  40590. const groupMaterial = material[ group.materialIndex ];
  40591. if ( groupMaterial && groupMaterial.visible ) {
  40592. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  40593. }
  40594. }
  40595. } else if ( material.visible ) {
  40596. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  40597. }
  40598. }
  40599. }
  40600. }
  40601. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  40602. const baseRenderList = renderList;
  40603. // replace render list
  40604. renderList = this._renderLists.get( object, camera );
  40605. renderList.begin();
  40606. baseRenderList.pushBundle( {
  40607. bundleGroup: object,
  40608. camera,
  40609. renderList,
  40610. } );
  40611. renderList.finish();
  40612. }
  40613. const children = object.children;
  40614. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40615. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  40616. }
  40617. }
  40618. /**
  40619. * Renders the given render bundles.
  40620. *
  40621. * @private
  40622. * @param {Array<Object>} bundles - Array with render bundle data.
  40623. * @param {Scene} sceneRef - The scene the render bundles belong to.
  40624. * @param {LightsNode} lightsNode - The current lights node.
  40625. */
  40626. _renderBundles( bundles, sceneRef, lightsNode ) {
  40627. for ( const bundle of bundles ) {
  40628. this._renderBundle( bundle, sceneRef, lightsNode );
  40629. }
  40630. }
  40631. /**
  40632. * Renders the transparent objects from the given render lists.
  40633. *
  40634. * @private
  40635. * @param {Array<Object>} renderList - The transparent render list.
  40636. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  40637. * @param {Camera} camera - The camera the render list should be rendered with.
  40638. * @param {Scene} scene - The scene the render list belongs to.
  40639. * @param {LightsNode} lightsNode - The current lights node.
  40640. */
  40641. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  40642. if ( doublePassList.length > 0 ) {
  40643. // render back side
  40644. for ( const { material } of doublePassList ) {
  40645. material.side = BackSide;
  40646. }
  40647. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  40648. // render front side
  40649. for ( const { material } of doublePassList ) {
  40650. material.side = FrontSide;
  40651. }
  40652. this._renderObjects( renderList, camera, scene, lightsNode );
  40653. // restore
  40654. for ( const { material } of doublePassList ) {
  40655. material.side = DoubleSide;
  40656. }
  40657. } else {
  40658. this._renderObjects( renderList, camera, scene, lightsNode );
  40659. }
  40660. }
  40661. /**
  40662. * Renders the objects from the given render list.
  40663. *
  40664. * @private
  40665. * @param {Array<Object>} renderList - The render list.
  40666. * @param {Camera} camera - The camera the render list should be rendered with.
  40667. * @param {Scene} scene - The scene the render list belongs to.
  40668. * @param {LightsNode} lightsNode - The current lights node.
  40669. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40670. */
  40671. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  40672. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  40673. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  40674. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  40675. }
  40676. }
  40677. /**
  40678. * This method represents the default render object function that manages the render lifecycle
  40679. * of the object.
  40680. *
  40681. * @param {Object3D} object - The 3D object.
  40682. * @param {Scene} scene - The scene the 3D object belongs to.
  40683. * @param {Camera} camera - The camera the object should be rendered with.
  40684. * @param {BufferGeometry} geometry - The object's geometry.
  40685. * @param {Material} material - The object's material.
  40686. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40687. * @param {LightsNode} lightsNode - The current lights node.
  40688. * @param {?ClippingContext} clippingContext - The clipping context.
  40689. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40690. */
  40691. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  40692. let overridePositionNode;
  40693. let overrideColorNode;
  40694. let overrideDepthNode;
  40695. //
  40696. object.onBeforeRender( this, scene, camera, geometry, material, group );
  40697. //
  40698. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  40699. const overrideMaterial = scene.overrideMaterial;
  40700. if ( material.positionNode && material.positionNode.isNode ) {
  40701. overridePositionNode = overrideMaterial.positionNode;
  40702. overrideMaterial.positionNode = material.positionNode;
  40703. }
  40704. overrideMaterial.alphaTest = material.alphaTest;
  40705. overrideMaterial.alphaMap = material.alphaMap;
  40706. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  40707. if ( overrideMaterial.isShadowPassMaterial ) {
  40708. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  40709. const hasMap = material.map !== null;
  40710. const hasColorNode = material.colorNode && material.colorNode.isNode;
  40711. const hasCastShadowNode = material.castShadowNode && material.castShadowNode.isNode;
  40712. if ( hasMap || hasColorNode || hasCastShadowNode ) {
  40713. overrideColorNode = overrideMaterial.colorNode;
  40714. let shadowRGB;
  40715. let shadowAlpha;
  40716. if ( hasCastShadowNode ) {
  40717. shadowRGB = material.castShadowNode.rgb;
  40718. shadowAlpha = material.castShadowNode.a;
  40719. } else {
  40720. shadowRGB = vec3( 0 );
  40721. shadowAlpha = float( 1 );
  40722. }
  40723. if ( hasMap ) {
  40724. shadowAlpha = shadowAlpha.mul( reference( 'map', 'texture', material ).a );
  40725. }
  40726. if ( hasColorNode ) {
  40727. shadowAlpha = shadowAlpha.mul( material.colorNode.a );
  40728. }
  40729. overrideMaterial.colorNode = vec4( shadowRGB, shadowAlpha );
  40730. }
  40731. if ( material.depthNode && material.depthNode.isNode ) {
  40732. overrideDepthNode = overrideMaterial.depthNode;
  40733. overrideMaterial.depthNode = material.depthNode;
  40734. }
  40735. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  40736. overridePositionNode = overrideMaterial.positionNode;
  40737. overrideMaterial.positionNode = material.castShadowPositionNode;
  40738. }
  40739. }
  40740. material = overrideMaterial;
  40741. }
  40742. //
  40743. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  40744. material.side = BackSide;
  40745. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  40746. material.side = FrontSide;
  40747. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  40748. material.side = DoubleSide;
  40749. } else {
  40750. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  40751. }
  40752. //
  40753. if ( overridePositionNode !== undefined ) {
  40754. scene.overrideMaterial.positionNode = overridePositionNode;
  40755. }
  40756. if ( overrideDepthNode !== undefined ) {
  40757. scene.overrideMaterial.depthNode = overrideDepthNode;
  40758. }
  40759. if ( overrideColorNode !== undefined ) {
  40760. scene.overrideMaterial.colorNode = overrideColorNode;
  40761. }
  40762. //
  40763. object.onAfterRender( this, scene, camera, geometry, material, group );
  40764. }
  40765. /**
  40766. * This method represents the default `_handleObjectFunction` implementation which creates
  40767. * a render object from the given data and performs the draw command with the selected backend.
  40768. *
  40769. * @private
  40770. * @param {Object3D} object - The 3D object.
  40771. * @param {Material} material - The object's material.
  40772. * @param {Scene} scene - The scene the 3D object belongs to.
  40773. * @param {Camera} camera - The camera the object should be rendered with.
  40774. * @param {LightsNode} lightsNode - The current lights node.
  40775. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40776. * @param {ClippingContext} clippingContext - The clipping context.
  40777. * @param {string} [passId] - An optional ID for identifying the pass.
  40778. */
  40779. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  40780. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  40781. renderObject.drawRange = object.geometry.drawRange;
  40782. renderObject.group = group;
  40783. //
  40784. const needsRefresh = this._nodes.needsRefresh( renderObject );
  40785. if ( needsRefresh ) {
  40786. this._nodes.updateBefore( renderObject );
  40787. this._geometries.updateForRender( renderObject );
  40788. this._nodes.updateForRender( renderObject );
  40789. this._bindings.updateForRender( renderObject );
  40790. }
  40791. this._pipelines.updateForRender( renderObject );
  40792. //
  40793. if ( this._currentRenderBundle !== null ) {
  40794. const renderBundleData = this.backend.get( this._currentRenderBundle );
  40795. renderBundleData.renderObjects.push( renderObject );
  40796. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  40797. }
  40798. this.backend.draw( renderObject, this.info );
  40799. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  40800. }
  40801. /**
  40802. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  40803. * Used in `compileAsync()`.
  40804. *
  40805. * @private
  40806. * @param {Object3D} object - The 3D object.
  40807. * @param {Material} material - The object's material.
  40808. * @param {Scene} scene - The scene the 3D object belongs to.
  40809. * @param {Camera} camera - The camera the object should be rendered with.
  40810. * @param {LightsNode} lightsNode - The current lights node.
  40811. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40812. * @param {ClippingContext} clippingContext - The clipping context.
  40813. * @param {string} [passId] - An optional ID for identifying the pass.
  40814. */
  40815. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  40816. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  40817. renderObject.drawRange = object.geometry.drawRange;
  40818. renderObject.group = group;
  40819. //
  40820. this._nodes.updateBefore( renderObject );
  40821. this._geometries.updateForRender( renderObject );
  40822. this._nodes.updateForRender( renderObject );
  40823. this._bindings.updateForRender( renderObject );
  40824. this._pipelines.getForRender( renderObject, this._compilationPromises );
  40825. this._nodes.updateAfter( renderObject );
  40826. }
  40827. /**
  40828. * Alias for `compileAsync()`.
  40829. *
  40830. * @method
  40831. * @param {Object3D} scene - The scene or 3D object to precompile.
  40832. * @param {Camera} camera - The camera that is used to render the scene.
  40833. * @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.
  40834. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  40835. */
  40836. get compile() {
  40837. return this.compileAsync;
  40838. }
  40839. }
  40840. /**
  40841. * A binding represents the connection between a resource (like a texture, sampler
  40842. * or uniform buffer) and the resource definition in a shader stage.
  40843. *
  40844. * This module is an abstract base class for all concrete bindings types.
  40845. *
  40846. * @abstract
  40847. * @private
  40848. */
  40849. class Binding {
  40850. /**
  40851. * Constructs a new binding.
  40852. *
  40853. * @param {string} [name=''] - The binding's name.
  40854. */
  40855. constructor( name = '' ) {
  40856. /**
  40857. * The binding's name.
  40858. *
  40859. * @type {string}
  40860. */
  40861. this.name = name;
  40862. /**
  40863. * A bitmask that defines in what shader stages the
  40864. * binding's resource is accessible.
  40865. *
  40866. * @type {number}
  40867. */
  40868. this.visibility = 0;
  40869. }
  40870. /**
  40871. * Makes sure binding's resource is visible for the given shader stage.
  40872. *
  40873. * @param {number} visibility - The shader stage.
  40874. */
  40875. setVisibility( visibility ) {
  40876. this.visibility |= visibility;
  40877. }
  40878. /**
  40879. * Clones the binding.
  40880. *
  40881. * @return {Binding} The cloned binding.
  40882. */
  40883. clone() {
  40884. return Object.assign( new this.constructor(), this );
  40885. }
  40886. }
  40887. /**
  40888. * This function is usually called with the length in bytes of an array buffer.
  40889. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  40890. *
  40891. * @function
  40892. * @param {number} floatLength - The buffer length.
  40893. * @return {number} The padded length.
  40894. */
  40895. function getFloatLength( floatLength ) {
  40896. // ensure chunk size alignment (STD140 layout)
  40897. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  40898. }
  40899. /**
  40900. * Represents a buffer binding type.
  40901. *
  40902. * @private
  40903. * @abstract
  40904. * @augments Binding
  40905. */
  40906. class Buffer extends Binding {
  40907. /**
  40908. * Constructs a new buffer.
  40909. *
  40910. * @param {string} name - The buffer's name.
  40911. * @param {TypedArray} [buffer=null] - The buffer.
  40912. */
  40913. constructor( name, buffer = null ) {
  40914. super( name );
  40915. /**
  40916. * This flag can be used for type testing.
  40917. *
  40918. * @type {boolean}
  40919. * @readonly
  40920. * @default true
  40921. */
  40922. this.isBuffer = true;
  40923. /**
  40924. * The bytes per element.
  40925. *
  40926. * @type {number}
  40927. */
  40928. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  40929. /**
  40930. * A reference to the internal buffer.
  40931. *
  40932. * @private
  40933. * @type {TypedArray}
  40934. */
  40935. this._buffer = buffer;
  40936. }
  40937. /**
  40938. * The buffer's byte length.
  40939. *
  40940. * @type {number}
  40941. * @readonly
  40942. */
  40943. get byteLength() {
  40944. return getFloatLength( this._buffer.byteLength );
  40945. }
  40946. /**
  40947. * A reference to the internal buffer.
  40948. *
  40949. * @type {Float32Array}
  40950. * @readonly
  40951. */
  40952. get buffer() {
  40953. return this._buffer;
  40954. }
  40955. /**
  40956. * Updates the binding.
  40957. *
  40958. * @return {boolean} Whether the buffer has been updated and must be
  40959. * uploaded to the GPU.
  40960. */
  40961. update() {
  40962. return true;
  40963. }
  40964. }
  40965. /**
  40966. * Represents a uniform buffer binding type.
  40967. *
  40968. * @private
  40969. * @augments Buffer
  40970. */
  40971. class UniformBuffer extends Buffer {
  40972. /**
  40973. * Constructs a new uniform buffer.
  40974. *
  40975. * @param {string} name - The buffer's name.
  40976. * @param {TypedArray} [buffer=null] - The buffer.
  40977. */
  40978. constructor( name, buffer = null ) {
  40979. super( name, buffer );
  40980. /**
  40981. * This flag can be used for type testing.
  40982. *
  40983. * @type {boolean}
  40984. * @readonly
  40985. * @default true
  40986. */
  40987. this.isUniformBuffer = true;
  40988. }
  40989. }
  40990. let _id$4 = 0;
  40991. /**
  40992. * A special form of uniform buffer binding type.
  40993. * It's buffer value is managed by a node object.
  40994. *
  40995. * @private
  40996. * @augments UniformBuffer
  40997. */
  40998. class NodeUniformBuffer extends UniformBuffer {
  40999. /**
  41000. * Constructs a new node-based uniform buffer.
  41001. *
  41002. * @param {BufferNode} nodeUniform - The uniform buffer node.
  41003. * @param {UniformGroupNode} groupNode - The uniform group node.
  41004. */
  41005. constructor( nodeUniform, groupNode ) {
  41006. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  41007. /**
  41008. * The uniform buffer node.
  41009. *
  41010. * @type {BufferNode}
  41011. */
  41012. this.nodeUniform = nodeUniform;
  41013. /**
  41014. * The uniform group node.
  41015. *
  41016. * @type {UniformGroupNode}
  41017. */
  41018. this.groupNode = groupNode;
  41019. }
  41020. /**
  41021. * The uniform buffer.
  41022. *
  41023. * @type {Float32Array}
  41024. */
  41025. get buffer() {
  41026. return this.nodeUniform.value;
  41027. }
  41028. }
  41029. /**
  41030. * This class represents a uniform buffer binding but with
  41031. * an API that allows to maintain individual uniform objects.
  41032. *
  41033. * @private
  41034. * @augments UniformBuffer
  41035. */
  41036. class UniformsGroup extends UniformBuffer {
  41037. /**
  41038. * Constructs a new uniforms group.
  41039. *
  41040. * @param {string} name - The group's name.
  41041. */
  41042. constructor( name ) {
  41043. super( name );
  41044. /**
  41045. * This flag can be used for type testing.
  41046. *
  41047. * @type {boolean}
  41048. * @readonly
  41049. * @default true
  41050. */
  41051. this.isUniformsGroup = true;
  41052. /**
  41053. * An array with the raw uniform values.
  41054. *
  41055. * @private
  41056. * @type {?Array<number>}
  41057. * @default null
  41058. */
  41059. this._values = null;
  41060. /**
  41061. * An array of uniform objects.
  41062. *
  41063. * The order of uniforms in this array must match the order of uniforms in the shader.
  41064. *
  41065. * @type {Array<Uniform>}
  41066. */
  41067. this.uniforms = [];
  41068. }
  41069. /**
  41070. * Adds a uniform to this group.
  41071. *
  41072. * @param {Uniform} uniform - The uniform to add.
  41073. * @return {UniformsGroup} A reference to this group.
  41074. */
  41075. addUniform( uniform ) {
  41076. this.uniforms.push( uniform );
  41077. return this;
  41078. }
  41079. /**
  41080. * Removes a uniform from this group.
  41081. *
  41082. * @param {Uniform} uniform - The uniform to remove.
  41083. * @return {UniformsGroup} A reference to this group.
  41084. */
  41085. removeUniform( uniform ) {
  41086. const index = this.uniforms.indexOf( uniform );
  41087. if ( index !== -1 ) {
  41088. this.uniforms.splice( index, 1 );
  41089. }
  41090. return this;
  41091. }
  41092. /**
  41093. * An array with the raw uniform values.
  41094. *
  41095. * @type {Array<number>}
  41096. */
  41097. get values() {
  41098. if ( this._values === null ) {
  41099. this._values = Array.from( this.buffer );
  41100. }
  41101. return this._values;
  41102. }
  41103. /**
  41104. * A Float32 array buffer with the uniform values.
  41105. *
  41106. * @type {Float32Array}
  41107. */
  41108. get buffer() {
  41109. let buffer = this._buffer;
  41110. if ( buffer === null ) {
  41111. const byteLength = this.byteLength;
  41112. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  41113. this._buffer = buffer;
  41114. }
  41115. return buffer;
  41116. }
  41117. /**
  41118. * The byte length of the buffer with correct buffer alignment.
  41119. *
  41120. * @type {number}
  41121. */
  41122. get byteLength() {
  41123. const bytesPerElement = this.bytesPerElement;
  41124. let offset = 0; // global buffer offset in bytes
  41125. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  41126. const uniform = this.uniforms[ i ];
  41127. const boundary = uniform.boundary;
  41128. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  41129. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  41130. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  41131. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  41132. offset += chunkPadding;
  41133. // Check for chunk overflow
  41134. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  41135. // Add padding to the end of the chunk
  41136. offset += ( GPU_CHUNK_BYTES - chunkStart );
  41137. }
  41138. uniform.offset = offset / bytesPerElement;
  41139. offset += itemSize;
  41140. }
  41141. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  41142. }
  41143. /**
  41144. * Updates this group by updating each uniform object of
  41145. * the internal uniform list. The uniform objects check if their
  41146. * values has actually changed so this method only returns
  41147. * `true` if there is a real value change.
  41148. *
  41149. * @return {boolean} Whether the uniforms have been updated and
  41150. * must be uploaded to the GPU.
  41151. */
  41152. update() {
  41153. let updated = false;
  41154. for ( const uniform of this.uniforms ) {
  41155. if ( this.updateByType( uniform ) === true ) {
  41156. updated = true;
  41157. }
  41158. }
  41159. return updated;
  41160. }
  41161. /**
  41162. * Updates a given uniform by calling an update method matching
  41163. * the uniforms type.
  41164. *
  41165. * @param {Uniform} uniform - The uniform to update.
  41166. * @return {boolean} Whether the uniform has been updated or not.
  41167. */
  41168. updateByType( uniform ) {
  41169. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  41170. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  41171. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  41172. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  41173. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  41174. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  41175. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  41176. error( 'WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  41177. }
  41178. /**
  41179. * Updates a given Number uniform.
  41180. *
  41181. * @param {NumberUniform} uniform - The Number uniform.
  41182. * @return {boolean} Whether the uniform has been updated or not.
  41183. */
  41184. updateNumber( uniform ) {
  41185. let updated = false;
  41186. const a = this.values;
  41187. const v = uniform.getValue();
  41188. const offset = uniform.offset;
  41189. const type = uniform.getType();
  41190. if ( a[ offset ] !== v ) {
  41191. const b = this._getBufferForType( type );
  41192. b[ offset ] = a[ offset ] = v;
  41193. updated = true;
  41194. }
  41195. return updated;
  41196. }
  41197. /**
  41198. * Updates a given Vector2 uniform.
  41199. *
  41200. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  41201. * @return {boolean} Whether the uniform has been updated or not.
  41202. */
  41203. updateVector2( uniform ) {
  41204. let updated = false;
  41205. const a = this.values;
  41206. const v = uniform.getValue();
  41207. const offset = uniform.offset;
  41208. const type = uniform.getType();
  41209. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  41210. const b = this._getBufferForType( type );
  41211. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  41212. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  41213. updated = true;
  41214. }
  41215. return updated;
  41216. }
  41217. /**
  41218. * Updates a given Vector3 uniform.
  41219. *
  41220. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  41221. * @return {boolean} Whether the uniform has been updated or not.
  41222. */
  41223. updateVector3( uniform ) {
  41224. let updated = false;
  41225. const a = this.values;
  41226. const v = uniform.getValue();
  41227. const offset = uniform.offset;
  41228. const type = uniform.getType();
  41229. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  41230. const b = this._getBufferForType( type );
  41231. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  41232. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  41233. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  41234. updated = true;
  41235. }
  41236. return updated;
  41237. }
  41238. /**
  41239. * Updates a given Vector4 uniform.
  41240. *
  41241. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  41242. * @return {boolean} Whether the uniform has been updated or not.
  41243. */
  41244. updateVector4( uniform ) {
  41245. let updated = false;
  41246. const a = this.values;
  41247. const v = uniform.getValue();
  41248. const offset = uniform.offset;
  41249. const type = uniform.getType();
  41250. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  41251. const b = this._getBufferForType( type );
  41252. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  41253. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  41254. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  41255. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  41256. updated = true;
  41257. }
  41258. return updated;
  41259. }
  41260. /**
  41261. * Updates a given Color uniform.
  41262. *
  41263. * @param {ColorUniform} uniform - The Color uniform.
  41264. * @return {boolean} Whether the uniform has been updated or not.
  41265. */
  41266. updateColor( uniform ) {
  41267. let updated = false;
  41268. const a = this.values;
  41269. const c = uniform.getValue();
  41270. const offset = uniform.offset;
  41271. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  41272. const b = this.buffer;
  41273. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  41274. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  41275. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  41276. updated = true;
  41277. }
  41278. return updated;
  41279. }
  41280. /**
  41281. * Updates a given Matrix3 uniform.
  41282. *
  41283. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  41284. * @return {boolean} Whether the uniform has been updated or not.
  41285. */
  41286. updateMatrix3( uniform ) {
  41287. let updated = false;
  41288. const a = this.values;
  41289. const e = uniform.getValue().elements;
  41290. const offset = uniform.offset;
  41291. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  41292. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  41293. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  41294. const b = this.buffer;
  41295. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  41296. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  41297. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  41298. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  41299. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  41300. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  41301. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  41302. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  41303. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  41304. updated = true;
  41305. }
  41306. return updated;
  41307. }
  41308. /**
  41309. * Updates a given Matrix4 uniform.
  41310. *
  41311. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  41312. * @return {boolean} Whether the uniform has been updated or not.
  41313. */
  41314. updateMatrix4( uniform ) {
  41315. let updated = false;
  41316. const a = this.values;
  41317. const e = uniform.getValue().elements;
  41318. const offset = uniform.offset;
  41319. if ( arraysEqual( a, e, offset ) === false ) {
  41320. const b = this.buffer;
  41321. b.set( e, offset );
  41322. setArray( a, e, offset );
  41323. updated = true;
  41324. }
  41325. return updated;
  41326. }
  41327. /**
  41328. * Returns a typed array that matches the given data type.
  41329. *
  41330. * @param {string} type - The data type.
  41331. * @return {TypedArray} The typed array.
  41332. */
  41333. _getBufferForType( type ) {
  41334. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  41335. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  41336. return this.buffer;
  41337. }
  41338. }
  41339. /**
  41340. * Sets the values of the second array to the first array.
  41341. *
  41342. * @private
  41343. * @param {TypedArray} a - The first array.
  41344. * @param {TypedArray} b - The second array.
  41345. * @param {number} offset - An index offset for the first array.
  41346. */
  41347. function setArray( a, b, offset ) {
  41348. for ( let i = 0, l = b.length; i < l; i ++ ) {
  41349. a[ offset + i ] = b[ i ];
  41350. }
  41351. }
  41352. /**
  41353. * Returns `true` if the given arrays are equal.
  41354. *
  41355. * @private
  41356. * @param {TypedArray} a - The first array.
  41357. * @param {TypedArray} b - The second array.
  41358. * @param {number} offset - An index offset for the first array.
  41359. * @return {boolean} Whether the given arrays are equal or not.
  41360. */
  41361. function arraysEqual( a, b, offset ) {
  41362. for ( let i = 0, l = b.length; i < l; i ++ ) {
  41363. if ( a[ offset + i ] !== b[ i ] ) return false;
  41364. }
  41365. return true;
  41366. }
  41367. let _id$3 = 0;
  41368. /**
  41369. * A special form of uniforms group that represents
  41370. * the individual uniforms as node-based uniforms.
  41371. *
  41372. * @private
  41373. * @augments UniformsGroup
  41374. */
  41375. class NodeUniformsGroup extends UniformsGroup {
  41376. /**
  41377. * Constructs a new node-based uniforms group.
  41378. *
  41379. * @param {string} name - The group's name.
  41380. * @param {UniformGroupNode} groupNode - The uniform group node.
  41381. */
  41382. constructor( name, groupNode ) {
  41383. super( name );
  41384. /**
  41385. * The group's ID.
  41386. *
  41387. * @type {number}
  41388. */
  41389. this.id = _id$3 ++;
  41390. /**
  41391. * The uniform group node.
  41392. *
  41393. * @type {UniformGroupNode}
  41394. */
  41395. this.groupNode = groupNode;
  41396. /**
  41397. * This flag can be used for type testing.
  41398. *
  41399. * @type {boolean}
  41400. * @readonly
  41401. * @default true
  41402. */
  41403. this.isNodeUniformsGroup = true;
  41404. }
  41405. }
  41406. /**
  41407. * Represents a sampler binding type.
  41408. *
  41409. * @private
  41410. * @augments Binding
  41411. */
  41412. class Sampler extends Binding {
  41413. /**
  41414. * Constructs a new sampler.
  41415. *
  41416. * @param {string} name - The samplers's name.
  41417. * @param {?Texture} texture - The texture this binding is referring to.
  41418. */
  41419. constructor( name, texture ) {
  41420. super( name );
  41421. /**
  41422. * The texture the sampler is referring to.
  41423. *
  41424. * @private
  41425. * @type {?Texture}
  41426. */
  41427. this._texture = null;
  41428. /**
  41429. * An event listener which is added to {@link texture}'s dispose event.
  41430. *
  41431. * @private
  41432. * @type {Function}
  41433. */
  41434. this._onTextureDispose = () => {
  41435. this.texture = null;
  41436. };
  41437. // Assignment to the texture via a setter must occur after "_onTextureDispose" is initialized.
  41438. this.texture = texture;
  41439. /**
  41440. * The binding's version.
  41441. *
  41442. * @type {number}
  41443. */
  41444. this.version = texture ? texture.version : 0;
  41445. /**
  41446. * The binding's generation which is an additional version
  41447. * qualifier.
  41448. *
  41449. * @type {?number}
  41450. * @default null
  41451. */
  41452. this.generation = null;
  41453. /**
  41454. * This flag can be used for type testing.
  41455. *
  41456. * @type {boolean}
  41457. * @readonly
  41458. * @default true
  41459. */
  41460. this.isSampler = true;
  41461. }
  41462. /**
  41463. * Sets the texture of this sampler.
  41464. * @param {?Texture} value - The texture to set.
  41465. */
  41466. set texture( value ) {
  41467. if ( this._texture === value ) return;
  41468. if ( this._texture ) {
  41469. this._texture.removeEventListener( 'dispose', this._onTextureDispose );
  41470. }
  41471. this._texture = value;
  41472. this.generation = null;
  41473. this.version = 0;
  41474. if ( this._texture ) {
  41475. this._texture.addEventListener( 'dispose', this._onTextureDispose );
  41476. }
  41477. }
  41478. /**
  41479. * Gets the texture of this sampler.
  41480. * @return {?Texture} The texture.
  41481. */
  41482. get texture() {
  41483. return this._texture;
  41484. }
  41485. /**
  41486. * Updates the binding.
  41487. *
  41488. * @return {boolean} Whether the texture has been updated and must be
  41489. * uploaded to the GPU.
  41490. */
  41491. update() {
  41492. const { texture, version } = this;
  41493. if ( version !== texture.version ) {
  41494. this.version = texture.version;
  41495. return true;
  41496. }
  41497. return false;
  41498. }
  41499. clone() {
  41500. const clonedSampler = super.clone();
  41501. // fix dispose handler for cloned instances
  41502. // TODO: Find better solution, see #31747
  41503. clonedSampler._texture = null;
  41504. clonedSampler._onTextureDispose = () => {
  41505. clonedSampler.texture = null;
  41506. };
  41507. clonedSampler.texture = this.texture;
  41508. return clonedSampler;
  41509. }
  41510. }
  41511. let _id$2 = 0;
  41512. /**
  41513. * Represents a sampled texture binding type.
  41514. *
  41515. * @private
  41516. * @augments Sampler
  41517. */
  41518. class SampledTexture extends Sampler {
  41519. /**
  41520. * Constructs a new sampled texture.
  41521. *
  41522. * @param {string} name - The sampled texture's name.
  41523. * @param {?Texture} texture - The texture this binding is referring to.
  41524. */
  41525. constructor( name, texture ) {
  41526. super( name, texture );
  41527. /**
  41528. * This identifier.
  41529. *
  41530. * @type {number}
  41531. */
  41532. this.id = _id$2 ++;
  41533. /**
  41534. * Whether the texture is a storage texture or not.
  41535. *
  41536. * @type {boolean}
  41537. * @default false
  41538. */
  41539. this.store = false;
  41540. /**
  41541. * This flag can be used for type testing.
  41542. *
  41543. * @type {boolean}
  41544. * @readonly
  41545. * @default true
  41546. */
  41547. this.isSampledTexture = true;
  41548. }
  41549. }
  41550. /**
  41551. * A special form of sampled texture binding type.
  41552. * It's texture value is managed by a node object.
  41553. *
  41554. * @private
  41555. * @augments SampledTexture
  41556. */
  41557. class NodeSampledTexture extends SampledTexture {
  41558. /**
  41559. * Constructs a new node-based sampled texture.
  41560. *
  41561. * @param {string} name - The textures's name.
  41562. * @param {TextureNode} textureNode - The texture node.
  41563. * @param {UniformGroupNode} groupNode - The uniform group node.
  41564. * @param {?string} [access=null] - The access type.
  41565. */
  41566. constructor( name, textureNode, groupNode, access = null ) {
  41567. super( name, textureNode ? textureNode.value : null );
  41568. /**
  41569. * The texture node.
  41570. *
  41571. * @type {TextureNode}
  41572. */
  41573. this.textureNode = textureNode;
  41574. /**
  41575. * The uniform group node.
  41576. *
  41577. * @type {UniformGroupNode}
  41578. */
  41579. this.groupNode = groupNode;
  41580. /**
  41581. * The access type.
  41582. *
  41583. * @type {?string}
  41584. * @default null
  41585. */
  41586. this.access = access;
  41587. }
  41588. /**
  41589. * Updates the binding.
  41590. *
  41591. * @return {boolean} Whether the texture has been updated and must be
  41592. * uploaded to the GPU.
  41593. */
  41594. update() {
  41595. const { textureNode } = this;
  41596. if ( this.texture !== textureNode.value ) {
  41597. this.texture = textureNode.value;
  41598. return true;
  41599. }
  41600. return super.update();
  41601. }
  41602. }
  41603. /**
  41604. * A special form of sampled cube texture binding type.
  41605. * It's texture value is managed by a node object.
  41606. *
  41607. * @private
  41608. * @augments NodeSampledTexture
  41609. */
  41610. class NodeSampledCubeTexture extends NodeSampledTexture {
  41611. /**
  41612. * Constructs a new node-based sampled cube texture.
  41613. *
  41614. * @param {string} name - The textures's name.
  41615. * @param {TextureNode} textureNode - The texture node.
  41616. * @param {UniformGroupNode} groupNode - The uniform group node.
  41617. * @param {?string} [access=null] - The access type.
  41618. */
  41619. constructor( name, textureNode, groupNode, access = null ) {
  41620. super( name, textureNode, groupNode, access );
  41621. /**
  41622. * This flag can be used for type testing.
  41623. *
  41624. * @type {boolean}
  41625. * @readonly
  41626. * @default true
  41627. */
  41628. this.isSampledCubeTexture = true;
  41629. }
  41630. }
  41631. /**
  41632. * A special form of sampled 3D texture binding type.
  41633. * It's texture value is managed by a node object.
  41634. *
  41635. * @private
  41636. * @augments NodeSampledTexture
  41637. */
  41638. class NodeSampledTexture3D extends NodeSampledTexture {
  41639. /**
  41640. * Constructs a new node-based sampled 3D texture.
  41641. *
  41642. * @param {string} name - The textures's name.
  41643. * @param {TextureNode} textureNode - The texture node.
  41644. * @param {UniformGroupNode} groupNode - The uniform group node.
  41645. * @param {?string} [access=null] - The access type.
  41646. */
  41647. constructor( name, textureNode, groupNode, access = null ) {
  41648. super( name, textureNode, groupNode, access );
  41649. /**
  41650. * This flag can be used for type testing.
  41651. *
  41652. * @type {boolean}
  41653. * @readonly
  41654. * @default true
  41655. */
  41656. this.isSampledTexture3D = true;
  41657. }
  41658. }
  41659. const glslMethods = {
  41660. textureDimensions: 'textureSize',
  41661. equals: 'equal',
  41662. bitcast_float_int: 'floatBitsToInt',
  41663. bitcast_int_float: 'intBitsToFloat',
  41664. bitcast_uint_float: 'uintBitsToFloat',
  41665. bitcast_float_uint: 'floatBitsToUint',
  41666. };
  41667. const precisionLib = {
  41668. low: 'lowp',
  41669. medium: 'mediump',
  41670. high: 'highp'
  41671. };
  41672. const supports$1 = {
  41673. swizzleAssign: true,
  41674. storageBuffer: false
  41675. };
  41676. const interpolationTypeMap = {
  41677. perspective: 'smooth',
  41678. linear: 'noperspective'
  41679. };
  41680. const interpolationModeMap = {
  41681. 'centroid': 'centroid'
  41682. };
  41683. const defaultPrecisions = `
  41684. precision highp float;
  41685. precision highp int;
  41686. precision highp sampler2D;
  41687. precision highp sampler3D;
  41688. precision highp samplerCube;
  41689. precision highp sampler2DArray;
  41690. precision highp usampler2D;
  41691. precision highp usampler3D;
  41692. precision highp usamplerCube;
  41693. precision highp usampler2DArray;
  41694. precision highp isampler2D;
  41695. precision highp isampler3D;
  41696. precision highp isamplerCube;
  41697. precision highp isampler2DArray;
  41698. precision lowp sampler2DShadow;
  41699. precision lowp sampler2DArrayShadow;
  41700. precision lowp samplerCubeShadow;
  41701. `;
  41702. /**
  41703. * A node builder targeting GLSL.
  41704. *
  41705. * This module generates GLSL shader code from node materials and also
  41706. * generates the respective bindings and vertex buffer definitions. These
  41707. * data are later used by the renderer to create render and compute pipelines
  41708. * for render objects.
  41709. *
  41710. * @augments NodeBuilder
  41711. */
  41712. class GLSLNodeBuilder extends NodeBuilder {
  41713. /**
  41714. * Constructs a new GLSL node builder renderer.
  41715. *
  41716. * @param {Object3D} object - The 3D object.
  41717. * @param {Renderer} renderer - The renderer.
  41718. */
  41719. constructor( object, renderer ) {
  41720. super( object, renderer, new GLSLNodeParser() );
  41721. /**
  41722. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  41723. * another dictionary which manages UBOs per group ('render','frame','object').
  41724. *
  41725. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  41726. */
  41727. this.uniformGroups = {};
  41728. /**
  41729. * An array that holds objects defining the varying and attribute data in
  41730. * context of Transform Feedback.
  41731. *
  41732. * @type {Array<Object<string,AttributeNode|string>>}
  41733. */
  41734. this.transforms = [];
  41735. /**
  41736. * A dictionary that holds for each shader stage a Map of used extensions.
  41737. *
  41738. * @type {Object<string,Map<string,Object>>}
  41739. */
  41740. this.extensions = {};
  41741. /**
  41742. * A dictionary that holds for each shader stage an Array of used builtins.
  41743. *
  41744. * @type {Object<string,Array<string>>}
  41745. */
  41746. this.builtins = { vertex: [], fragment: [], compute: [] };
  41747. }
  41748. /**
  41749. * Checks if the given texture requires a manual conversion to the working color space.
  41750. *
  41751. * @param {Texture} texture - The texture to check.
  41752. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  41753. */
  41754. needsToWorkingColorSpace( texture ) {
  41755. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  41756. }
  41757. /**
  41758. * Returns the native shader method name for a given generic name.
  41759. *
  41760. * @param {string} method - The method name to resolve.
  41761. * @return {string} The resolved GLSL method name.
  41762. */
  41763. getMethod( method ) {
  41764. return glslMethods[ method ] || method;
  41765. }
  41766. /**
  41767. * Returns the bitcast method name for a given input and outputType.
  41768. *
  41769. * @param {string} type - The output type to bitcast to.
  41770. * @param {string} inputType - The input type of the.
  41771. * @return {string} The resolved WGSL bitcast invocation.
  41772. */
  41773. getBitcastMethod( type, inputType ) {
  41774. return glslMethods[ `bitcast_${ inputType }_${ type }` ];
  41775. }
  41776. /**
  41777. * Returns the native snippet for a ternary operation.
  41778. *
  41779. * @param {string} condSnippet - The condition determining which expression gets resolved.
  41780. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  41781. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  41782. * @return {string} The resolved method name.
  41783. */
  41784. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  41785. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  41786. }
  41787. /**
  41788. * Returns the output struct name. Not relevant for GLSL.
  41789. *
  41790. * @return {string}
  41791. */
  41792. getOutputStructName() {
  41793. return '';
  41794. }
  41795. /**
  41796. * Builds the given shader node.
  41797. *
  41798. * @param {ShaderNodeInternal} shaderNode - The shader node.
  41799. * @return {string} The GLSL function code.
  41800. */
  41801. buildFunctionCode( shaderNode ) {
  41802. const layout = shaderNode.layout;
  41803. const flowData = this.flowShaderNode( shaderNode );
  41804. const parameters = [];
  41805. for ( const input of layout.inputs ) {
  41806. parameters.push( this.getType( input.type ) + ' ' + input.name );
  41807. }
  41808. //
  41809. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  41810. ${ flowData.vars }
  41811. ${ flowData.code }
  41812. return ${ flowData.result };
  41813. }`;
  41814. //
  41815. return code;
  41816. }
  41817. /**
  41818. * Setups the Pixel Buffer Object (PBO) for the given storage
  41819. * buffer node.
  41820. *
  41821. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  41822. */
  41823. setupPBO( storageBufferNode ) {
  41824. const attribute = storageBufferNode.value;
  41825. if ( attribute.pbo === undefined ) {
  41826. const originalArray = attribute.array;
  41827. const numElements = attribute.count * attribute.itemSize;
  41828. const { itemSize } = attribute;
  41829. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  41830. let format = isInteger ? RedIntegerFormat : RedFormat;
  41831. if ( itemSize === 2 ) {
  41832. format = isInteger ? RGIntegerFormat : RGFormat;
  41833. } else if ( itemSize === 3 ) {
  41834. format = isInteger ? RGBIntegerFormat : RGBFormat;
  41835. } else if ( itemSize === 4 ) {
  41836. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  41837. }
  41838. const typeMap = {
  41839. Float32Array: FloatType,
  41840. Uint8Array: UnsignedByteType,
  41841. Uint16Array: UnsignedShortType,
  41842. Uint32Array: UnsignedIntType,
  41843. Int8Array: ByteType,
  41844. Int16Array: ShortType,
  41845. Int32Array: IntType,
  41846. Uint8ClampedArray: UnsignedByteType,
  41847. };
  41848. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  41849. let height = Math.ceil( ( numElements / itemSize ) / width );
  41850. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  41851. const newSize = width * height * itemSize;
  41852. const newArray = new originalArray.constructor( newSize );
  41853. newArray.set( originalArray, 0 );
  41854. attribute.array = newArray;
  41855. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  41856. pboTexture.needsUpdate = true;
  41857. pboTexture.isPBOTexture = true;
  41858. const pbo = new TextureNode( pboTexture, null, null );
  41859. pbo.setPrecision( 'high' );
  41860. attribute.pboNode = pbo;
  41861. attribute.pbo = pbo.value;
  41862. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  41863. }
  41864. }
  41865. /**
  41866. * Returns a GLSL snippet that represents the property name of the given node.
  41867. *
  41868. * @param {Node} node - The node.
  41869. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  41870. * @return {string} The property name.
  41871. */
  41872. getPropertyName( node, shaderStage = this.shaderStage ) {
  41873. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  41874. return shaderStage.charAt( 0 ) + '_' + node.name;
  41875. }
  41876. return super.getPropertyName( node, shaderStage );
  41877. }
  41878. /**
  41879. * Setups the Pixel Buffer Object (PBO) for the given storage
  41880. * buffer node.
  41881. *
  41882. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  41883. * @return {string} The property name.
  41884. */
  41885. generatePBO( storageArrayElementNode ) {
  41886. const { node, indexNode } = storageArrayElementNode;
  41887. const attribute = node.value;
  41888. if ( this.renderer.backend.has( attribute ) ) {
  41889. const attributeData = this.renderer.backend.get( attribute );
  41890. attributeData.pbo = attribute.pbo;
  41891. }
  41892. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  41893. const textureName = this.getPropertyName( nodeUniform );
  41894. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  41895. const indexSnippet = indexNode.build( this, 'uint' );
  41896. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  41897. let propertyName = elementNodeData.propertyName;
  41898. if ( propertyName === undefined ) {
  41899. // property element
  41900. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  41901. propertyName = this.getPropertyName( nodeVar );
  41902. // property size
  41903. const bufferNodeData = this.getDataFromNode( node );
  41904. let propertySizeName = bufferNodeData.propertySizeName;
  41905. if ( propertySizeName === undefined ) {
  41906. propertySizeName = propertyName + 'Size';
  41907. this.getVarFromNode( node, propertySizeName, 'uint' );
  41908. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  41909. bufferNodeData.propertySizeName = propertySizeName;
  41910. }
  41911. //
  41912. const { itemSize } = attribute;
  41913. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  41914. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  41915. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, '0', null, null );
  41916. //
  41917. let prefix = 'vec4';
  41918. if ( attribute.pbo.type === UnsignedIntType ) {
  41919. prefix = 'uvec4';
  41920. } else if ( attribute.pbo.type === IntType ) {
  41921. prefix = 'ivec4';
  41922. }
  41923. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  41924. elementNodeData.propertyName = propertyName;
  41925. }
  41926. return propertyName;
  41927. }
  41928. /**
  41929. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  41930. *
  41931. * @param {?Texture} texture - The texture.
  41932. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41933. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41934. * @param {?string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  41935. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  41936. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  41937. * @return {string} The GLSL snippet.
  41938. */
  41939. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  41940. if ( levelSnippet === null ) levelSnippet = '0';
  41941. let snippet;
  41942. if ( depthSnippet ) {
  41943. if ( offsetSnippet ) {
  41944. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  41945. } else {
  41946. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  41947. }
  41948. } else {
  41949. if ( offsetSnippet ) {
  41950. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  41951. } else {
  41952. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  41953. }
  41954. }
  41955. if ( texture !== null && texture.isDepthTexture ) {
  41956. snippet += '.x';
  41957. }
  41958. return snippet;
  41959. }
  41960. /**
  41961. * Generates the GLSL snippet for sampling/loading the given texture.
  41962. *
  41963. * @param {Texture} texture - The texture.
  41964. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41965. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41966. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  41967. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  41968. * @return {string} The GLSL snippet.
  41969. */
  41970. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  41971. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  41972. if ( texture.isDepthTexture ) {
  41973. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  41974. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  41975. }
  41976. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  41977. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  41978. }
  41979. /**
  41980. * Generates the GLSL snippet when sampling textures with explicit mip level.
  41981. *
  41982. * @param {Texture} texture - The texture.
  41983. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41984. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41985. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  41986. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  41987. * @return {string} The GLSL snippet.
  41988. */
  41989. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  41990. if ( offsetSnippet ) {
  41991. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  41992. }
  41993. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  41994. }
  41995. /**
  41996. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  41997. *
  41998. * @param {Texture} texture - The texture.
  41999. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42000. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42001. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  42002. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42003. * @return {string} The GLSL snippet.
  42004. */
  42005. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  42006. if ( offsetSnippet ) {
  42007. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  42008. }
  42009. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  42010. }
  42011. /**
  42012. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  42013. *
  42014. * @param {Texture} texture - The texture.
  42015. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42016. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42017. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  42018. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42019. * @return {string} The GLSL snippet.
  42020. */
  42021. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  42022. if ( offsetSnippet ) {
  42023. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  42024. }
  42025. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42026. }
  42027. /**
  42028. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  42029. * against a reference value.
  42030. *
  42031. * @param {Texture} texture - The texture.
  42032. * @param {string} textureProperty - The name of the texture uniform in the shader.
  42033. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  42034. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  42035. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  42036. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  42037. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  42038. * @return {string} The GLSL snippet.
  42039. */
  42040. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  42041. if ( shaderStage === 'fragment' ) {
  42042. if ( depthSnippet ) {
  42043. if ( offsetSnippet ) {
  42044. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  42045. }
  42046. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  42047. }
  42048. if ( offsetSnippet ) {
  42049. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  42050. }
  42051. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  42052. } else {
  42053. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42054. }
  42055. }
  42056. /**
  42057. * Returns the variables of the given shader stage as a GLSL string.
  42058. *
  42059. * @param {string} shaderStage - The shader stage.
  42060. * @return {string} The GLSL snippet that defines the variables.
  42061. */
  42062. getVars( shaderStage ) {
  42063. const snippets = [];
  42064. const vars = this.vars[ shaderStage ];
  42065. if ( vars !== undefined ) {
  42066. for ( const variable of vars ) {
  42067. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  42068. }
  42069. }
  42070. return snippets.join( '\n\t' );
  42071. }
  42072. /**
  42073. * Returns the uniforms of the given shader stage as a GLSL string.
  42074. *
  42075. * @param {string} shaderStage - The shader stage.
  42076. * @return {string} The GLSL snippet that defines the uniforms.
  42077. */
  42078. getUniforms( shaderStage ) {
  42079. const uniforms = this.uniforms[ shaderStage ];
  42080. const bindingSnippets = [];
  42081. const uniformGroups = {};
  42082. for ( const uniform of uniforms ) {
  42083. let snippet = null;
  42084. let group = false;
  42085. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  42086. const texture = uniform.node.value;
  42087. let typePrefix = '';
  42088. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  42089. if ( texture.type === UnsignedIntType ) {
  42090. typePrefix = 'u';
  42091. } else if ( texture.type === IntType ) {
  42092. typePrefix = 'i';
  42093. }
  42094. }
  42095. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  42096. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  42097. } else if ( texture.compareFunction ) {
  42098. if ( texture.isArrayTexture === true ) {
  42099. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  42100. } else {
  42101. snippet = `sampler2DShadow ${ uniform.name };`;
  42102. }
  42103. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  42104. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  42105. } else {
  42106. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  42107. }
  42108. } else if ( uniform.type === 'cubeTexture' ) {
  42109. snippet = `samplerCube ${ uniform.name };`;
  42110. } else if ( uniform.type === 'buffer' ) {
  42111. const bufferNode = uniform.node;
  42112. const bufferType = this.getType( bufferNode.bufferType );
  42113. const bufferCount = bufferNode.bufferCount;
  42114. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  42115. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  42116. } else {
  42117. const vectorType = this.getVectorType( uniform.type );
  42118. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  42119. group = true;
  42120. }
  42121. const precision = uniform.node.precision;
  42122. if ( precision !== null ) {
  42123. snippet = precisionLib[ precision ] + ' ' + snippet;
  42124. }
  42125. if ( group ) {
  42126. snippet = '\t' + snippet;
  42127. const groupName = uniform.groupNode.name;
  42128. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  42129. groupSnippets.push( snippet );
  42130. } else {
  42131. snippet = 'uniform ' + snippet;
  42132. bindingSnippets.push( snippet );
  42133. }
  42134. }
  42135. let output = '';
  42136. for ( const name in uniformGroups ) {
  42137. const groupSnippets = uniformGroups[ name ];
  42138. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  42139. }
  42140. output += bindingSnippets.join( '\n' );
  42141. return output;
  42142. }
  42143. /**
  42144. * Returns the type for a given buffer attribute.
  42145. *
  42146. * @param {BufferAttribute} attribute - The buffer attribute.
  42147. * @return {string} The type.
  42148. */
  42149. getTypeFromAttribute( attribute ) {
  42150. let nodeType = super.getTypeFromAttribute( attribute );
  42151. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  42152. let dataAttribute = attribute;
  42153. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  42154. const array = dataAttribute.array;
  42155. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  42156. nodeType = nodeType.slice( 1 );
  42157. }
  42158. }
  42159. return nodeType;
  42160. }
  42161. /**
  42162. * Returns the shader attributes of the given shader stage as a GLSL string.
  42163. *
  42164. * @param {string} shaderStage - The shader stage.
  42165. * @return {string} The GLSL snippet that defines the shader attributes.
  42166. */
  42167. getAttributes( shaderStage ) {
  42168. let snippet = '';
  42169. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  42170. const attributes = this.getAttributesArray();
  42171. let location = 0;
  42172. for ( const attribute of attributes ) {
  42173. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  42174. }
  42175. }
  42176. return snippet;
  42177. }
  42178. /**
  42179. * Returns the members of the given struct type node as a GLSL string.
  42180. *
  42181. * @param {StructTypeNode} struct - The struct type node.
  42182. * @return {string} The GLSL snippet that defines the struct members.
  42183. */
  42184. getStructMembers( struct ) {
  42185. const snippets = [];
  42186. for ( const member of struct.members ) {
  42187. snippets.push( `\t${ member.type } ${ member.name };` );
  42188. }
  42189. return snippets.join( '\n' );
  42190. }
  42191. /**
  42192. * Returns the structs of the given shader stage as a GLSL string.
  42193. *
  42194. * @param {string} shaderStage - The shader stage.
  42195. * @return {string} The GLSL snippet that defines the structs.
  42196. */
  42197. getStructs( shaderStage ) {
  42198. const snippets = [];
  42199. const structs = this.structs[ shaderStage ];
  42200. const outputSnippet = [];
  42201. for ( const struct of structs ) {
  42202. if ( struct.output ) {
  42203. for ( const member of struct.members ) {
  42204. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  42205. }
  42206. } else {
  42207. let snippet = 'struct ' + struct.name + ' {\n';
  42208. snippet += this.getStructMembers( struct );
  42209. snippet += '\n};\n';
  42210. snippets.push( snippet );
  42211. }
  42212. }
  42213. if ( outputSnippet.length === 0 ) {
  42214. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  42215. }
  42216. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  42217. }
  42218. /**
  42219. * Returns the varyings of the given shader stage as a GLSL string.
  42220. *
  42221. * @param {string} shaderStage - The shader stage.
  42222. * @return {string} The GLSL snippet that defines the varyings.
  42223. */
  42224. getVaryings( shaderStage ) {
  42225. let snippet = '';
  42226. const varyings = this.varyings;
  42227. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  42228. for ( const varying of varyings ) {
  42229. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  42230. const type = this.getType( varying.type );
  42231. if ( varying.needsInterpolation ) {
  42232. if ( varying.interpolationType ) {
  42233. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  42234. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  42235. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  42236. } else {
  42237. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  42238. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  42239. }
  42240. } else {
  42241. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  42242. }
  42243. }
  42244. } else if ( shaderStage === 'fragment' ) {
  42245. for ( const varying of varyings ) {
  42246. if ( varying.needsInterpolation ) {
  42247. const type = this.getType( varying.type );
  42248. if ( varying.interpolationType ) {
  42249. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  42250. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  42251. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  42252. } else {
  42253. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  42254. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  42255. }
  42256. }
  42257. }
  42258. }
  42259. for ( const builtin of this.builtins[ shaderStage ] ) {
  42260. snippet += `${builtin};\n`;
  42261. }
  42262. return snippet;
  42263. }
  42264. /**
  42265. * Returns the vertex index builtin.
  42266. *
  42267. * @return {string} The vertex index.
  42268. */
  42269. getVertexIndex() {
  42270. return 'uint( gl_VertexID )';
  42271. }
  42272. /**
  42273. * Returns the instance index builtin.
  42274. *
  42275. * @return {string} The instance index.
  42276. */
  42277. getInstanceIndex() {
  42278. return 'uint( gl_InstanceID )';
  42279. }
  42280. /**
  42281. * Returns the invocation local index builtin.
  42282. *
  42283. * @return {string} The invocation local index.
  42284. */
  42285. getInvocationLocalIndex() {
  42286. const workgroupSize = this.object.workgroupSize;
  42287. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  42288. return `uint( gl_InstanceID ) % ${size}u`;
  42289. }
  42290. /**
  42291. * Returns the draw index builtin.
  42292. *
  42293. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  42294. */
  42295. getDrawIndex() {
  42296. const extensions = this.renderer.backend.extensions;
  42297. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  42298. return 'uint( gl_DrawID )';
  42299. }
  42300. return null;
  42301. }
  42302. /**
  42303. * Returns the front facing builtin.
  42304. *
  42305. * @return {string} The front facing builtin.
  42306. */
  42307. getFrontFacing() {
  42308. return 'gl_FrontFacing';
  42309. }
  42310. /**
  42311. * Returns the frag coord builtin.
  42312. *
  42313. * @return {string} The frag coord builtin.
  42314. */
  42315. getFragCoord() {
  42316. return 'gl_FragCoord.xy';
  42317. }
  42318. /**
  42319. * Returns the frag depth builtin.
  42320. *
  42321. * @return {string} The frag depth builtin.
  42322. */
  42323. getFragDepth() {
  42324. return 'gl_FragDepth';
  42325. }
  42326. /**
  42327. * Enables the given extension.
  42328. *
  42329. * @param {string} name - The extension name.
  42330. * @param {string} behavior - The extension behavior.
  42331. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  42332. */
  42333. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  42334. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  42335. if ( map.has( name ) === false ) {
  42336. map.set( name, {
  42337. name,
  42338. behavior
  42339. } );
  42340. }
  42341. }
  42342. /**
  42343. * Returns the enabled extensions of the given shader stage as a GLSL string.
  42344. *
  42345. * @param {string} shaderStage - The shader stage.
  42346. * @return {string} The GLSL snippet that defines the enabled extensions.
  42347. */
  42348. getExtensions( shaderStage ) {
  42349. const snippets = [];
  42350. if ( shaderStage === 'vertex' ) {
  42351. const ext = this.renderer.backend.extensions;
  42352. const isBatchedMesh = this.object.isBatchedMesh;
  42353. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  42354. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  42355. }
  42356. }
  42357. const extensions = this.extensions[ shaderStage ];
  42358. if ( extensions !== undefined ) {
  42359. for ( const { name, behavior } of extensions.values() ) {
  42360. snippets.push( `#extension ${name} : ${behavior}` );
  42361. }
  42362. }
  42363. return snippets.join( '\n' );
  42364. }
  42365. /**
  42366. * Returns the clip distances builtin.
  42367. *
  42368. * @return {string} The clip distances builtin.
  42369. */
  42370. getClipDistance() {
  42371. return 'gl_ClipDistance';
  42372. }
  42373. /**
  42374. * Whether the requested feature is available or not.
  42375. *
  42376. * @param {string} name - The requested feature.
  42377. * @return {boolean} Whether the requested feature is supported or not.
  42378. */
  42379. isAvailable( name ) {
  42380. let result = supports$1[ name ];
  42381. if ( result === undefined ) {
  42382. let extensionName;
  42383. result = false;
  42384. switch ( name ) {
  42385. case 'float32Filterable':
  42386. extensionName = 'OES_texture_float_linear';
  42387. break;
  42388. case 'clipDistance':
  42389. extensionName = 'WEBGL_clip_cull_distance';
  42390. break;
  42391. }
  42392. if ( extensionName !== undefined ) {
  42393. const extensions = this.renderer.backend.extensions;
  42394. if ( extensions.has( extensionName ) ) {
  42395. extensions.get( extensionName );
  42396. result = true;
  42397. }
  42398. }
  42399. supports$1[ name ] = result;
  42400. }
  42401. return result;
  42402. }
  42403. /**
  42404. * Whether to flip texture data along its vertical axis or not.
  42405. *
  42406. * @return {boolean} Returns always `true` in context of GLSL.
  42407. */
  42408. isFlipY() {
  42409. return true;
  42410. }
  42411. /**
  42412. * Enables hardware clipping.
  42413. *
  42414. * @param {string} planeCount - The clipping plane count.
  42415. */
  42416. enableHardwareClipping( planeCount ) {
  42417. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  42418. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  42419. }
  42420. /**
  42421. * Enables multiview.
  42422. */
  42423. enableMultiview() {
  42424. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  42425. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  42426. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  42427. }
  42428. /**
  42429. * Registers a transform in context of Transform Feedback.
  42430. *
  42431. * @param {string} varyingName - The varying name.
  42432. * @param {AttributeNode} attributeNode - The attribute node.
  42433. */
  42434. registerTransform( varyingName, attributeNode ) {
  42435. this.transforms.push( { varyingName, attributeNode } );
  42436. }
  42437. /**
  42438. * Returns the transforms of the given shader stage as a GLSL string.
  42439. *
  42440. * @param {string} shaderStage - The shader stage.
  42441. * @return {string} The GLSL snippet that defines the transforms.
  42442. */
  42443. getTransforms( /* shaderStage */ ) {
  42444. const transforms = this.transforms;
  42445. let snippet = '';
  42446. for ( let i = 0; i < transforms.length; i ++ ) {
  42447. const transform = transforms[ i ];
  42448. const attributeName = this.getPropertyName( transform.attributeNode );
  42449. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  42450. }
  42451. return snippet;
  42452. }
  42453. /**
  42454. * Returns a GLSL struct based on the given name and variables.
  42455. *
  42456. * @private
  42457. * @param {string} name - The struct name.
  42458. * @param {string} vars - The struct variables.
  42459. * @return {string} The GLSL snippet representing a struct.
  42460. */
  42461. _getGLSLUniformStruct( name, vars ) {
  42462. return `
  42463. layout( std140 ) uniform ${name} {
  42464. ${vars}
  42465. };`;
  42466. }
  42467. /**
  42468. * Returns a GLSL vertex shader based on the given shader data.
  42469. *
  42470. * @private
  42471. * @param {Object} shaderData - The shader data.
  42472. * @return {string} The vertex shader.
  42473. */
  42474. _getGLSLVertexCode( shaderData ) {
  42475. return `#version 300 es
  42476. ${ this.getSignature() }
  42477. // extensions
  42478. ${shaderData.extensions}
  42479. // precision
  42480. ${ defaultPrecisions }
  42481. // uniforms
  42482. ${shaderData.uniforms}
  42483. // varyings
  42484. ${shaderData.varyings}
  42485. // attributes
  42486. ${shaderData.attributes}
  42487. // codes
  42488. ${shaderData.codes}
  42489. void main() {
  42490. // vars
  42491. ${shaderData.vars}
  42492. // transforms
  42493. ${shaderData.transforms}
  42494. // flow
  42495. ${shaderData.flow}
  42496. gl_PointSize = 1.0;
  42497. }
  42498. `;
  42499. }
  42500. /**
  42501. * Returns a GLSL fragment shader based on the given shader data.
  42502. *
  42503. * @private
  42504. * @param {Object} shaderData - The shader data.
  42505. * @return {string} The vertex shader.
  42506. */
  42507. _getGLSLFragmentCode( shaderData ) {
  42508. return `#version 300 es
  42509. ${ this.getSignature() }
  42510. // extensions
  42511. ${shaderData.extensions}
  42512. // precision
  42513. ${ defaultPrecisions }
  42514. // uniforms
  42515. ${shaderData.uniforms}
  42516. // varyings
  42517. ${shaderData.varyings}
  42518. // codes
  42519. ${shaderData.codes}
  42520. // structs
  42521. ${shaderData.structs}
  42522. void main() {
  42523. // vars
  42524. ${shaderData.vars}
  42525. // flow
  42526. ${shaderData.flow}
  42527. }
  42528. `;
  42529. }
  42530. /**
  42531. * Controls the code build of the shader stages.
  42532. */
  42533. buildCode() {
  42534. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  42535. this.sortBindingGroups();
  42536. for ( const shaderStage in shadersData ) {
  42537. let flow = '// code\n\n';
  42538. flow += this.flowCode[ shaderStage ];
  42539. const flowNodes = this.flowNodes[ shaderStage ];
  42540. const mainNode = flowNodes[ flowNodes.length - 1 ];
  42541. for ( const node of flowNodes ) {
  42542. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  42543. const slotName = node.name;
  42544. if ( slotName ) {
  42545. if ( flow.length > 0 ) flow += '\n';
  42546. flow += `\t// flow -> ${ slotName }\n\t`;
  42547. }
  42548. flow += `${ flowSlotData.code }\n\t`;
  42549. if ( node === mainNode && shaderStage !== 'compute' ) {
  42550. flow += '// result\n\t';
  42551. if ( shaderStage === 'vertex' ) {
  42552. flow += 'gl_Position = ';
  42553. flow += `${ flowSlotData.result };`;
  42554. } else if ( shaderStage === 'fragment' ) {
  42555. if ( ! node.outputNode.isOutputStructNode ) {
  42556. flow += 'fragColor = ';
  42557. flow += `${ flowSlotData.result };`;
  42558. }
  42559. }
  42560. }
  42561. }
  42562. const stageData = shadersData[ shaderStage ];
  42563. stageData.extensions = this.getExtensions( shaderStage );
  42564. stageData.uniforms = this.getUniforms( shaderStage );
  42565. stageData.attributes = this.getAttributes( shaderStage );
  42566. stageData.varyings = this.getVaryings( shaderStage );
  42567. stageData.vars = this.getVars( shaderStage );
  42568. stageData.structs = this.getStructs( shaderStage );
  42569. stageData.codes = this.getCodes( shaderStage );
  42570. stageData.transforms = this.getTransforms( shaderStage );
  42571. stageData.flow = flow;
  42572. }
  42573. if ( this.material !== null ) {
  42574. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  42575. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  42576. } else {
  42577. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  42578. }
  42579. }
  42580. /**
  42581. * This method is one of the more important ones since it's responsible
  42582. * for generating a matching binding instance for the given uniform node.
  42583. *
  42584. * These bindings are later used in the renderer to create bind groups
  42585. * and layouts.
  42586. *
  42587. * @param {UniformNode} node - The uniform node.
  42588. * @param {string} type - The node data type.
  42589. * @param {string} shaderStage - The shader stage.
  42590. * @param {?string} [name=null] - An optional uniform name.
  42591. * @return {NodeUniform} The node uniform object.
  42592. */
  42593. getUniformFromNode( node, type, shaderStage, name = null ) {
  42594. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42595. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42596. let uniformGPU = nodeData.uniformGPU;
  42597. if ( uniformGPU === undefined ) {
  42598. const group = node.groupNode;
  42599. const groupName = group.name;
  42600. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42601. if ( type === 'texture' ) {
  42602. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  42603. bindings.push( uniformGPU );
  42604. } else if ( type === 'cubeTexture' ) {
  42605. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  42606. bindings.push( uniformGPU );
  42607. } else if ( type === 'texture3D' ) {
  42608. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  42609. bindings.push( uniformGPU );
  42610. } else if ( type === 'buffer' ) {
  42611. node.name = `NodeBuffer_${ node.id }`;
  42612. uniformNode.name = `buffer${ node.id }`;
  42613. const buffer = new NodeUniformBuffer( node, group );
  42614. buffer.name = node.name;
  42615. bindings.push( buffer );
  42616. uniformGPU = buffer;
  42617. } else {
  42618. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42619. let uniformsGroup = uniformsStage[ groupName ];
  42620. if ( uniformsGroup === undefined ) {
  42621. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  42622. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42623. uniformsStage[ groupName ] = uniformsGroup;
  42624. bindings.push( uniformsGroup );
  42625. }
  42626. uniformGPU = this.getNodeUniform( uniformNode, type );
  42627. uniformsGroup.addUniform( uniformGPU );
  42628. }
  42629. nodeData.uniformGPU = uniformGPU;
  42630. }
  42631. return uniformNode;
  42632. }
  42633. }
  42634. let _vector2 = null;
  42635. let _color4 = null;
  42636. /**
  42637. * Most of the rendering related logic is implemented in the
  42638. * {@link Renderer} module and related management components.
  42639. * Sometimes it is required though to execute commands which are
  42640. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  42641. * This abstract base class defines an interface that encapsulates
  42642. * all backend-related logic. Derived classes for each backend must
  42643. * implement the interface.
  42644. *
  42645. * @abstract
  42646. * @private
  42647. */
  42648. class Backend {
  42649. /**
  42650. * Constructs a new backend.
  42651. *
  42652. * @param {Object} parameters - An object holding parameters for the backend.
  42653. */
  42654. constructor( parameters = {} ) {
  42655. /**
  42656. * The parameters of the backend.
  42657. *
  42658. * @type {Object}
  42659. */
  42660. this.parameters = Object.assign( {}, parameters );
  42661. /**
  42662. * This weak map holds backend-specific data of objects
  42663. * like textures, attributes or render targets.
  42664. *
  42665. * @type {WeakMap<Object, Object>}
  42666. */
  42667. this.data = new WeakMap();
  42668. /**
  42669. * A reference to the renderer.
  42670. *
  42671. * @type {?Renderer}
  42672. * @default null
  42673. */
  42674. this.renderer = null;
  42675. /**
  42676. * A reference to the canvas element the renderer is drawing to.
  42677. *
  42678. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  42679. * @default null
  42680. */
  42681. this.domElement = null;
  42682. /**
  42683. * A reference to the timestamp query pool.
  42684. *
  42685. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  42686. */
  42687. this.timestampQueryPool = {
  42688. 'render': null,
  42689. 'compute': null
  42690. };
  42691. /**
  42692. * Whether to track timestamps with a Timestamp Query API or not.
  42693. *
  42694. * @type {boolean}
  42695. * @default false
  42696. */
  42697. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42698. }
  42699. /**
  42700. * Initializes the backend so it is ready for usage. Concrete backends
  42701. * are supposed to implement their rendering context creation and related
  42702. * operations in this method.
  42703. *
  42704. * @async
  42705. * @param {Renderer} renderer - The renderer.
  42706. * @return {Promise} A Promise that resolves when the backend has been initialized.
  42707. */
  42708. async init( renderer ) {
  42709. this.renderer = renderer;
  42710. }
  42711. /**
  42712. * The coordinate system of the backend.
  42713. *
  42714. * @abstract
  42715. * @type {number}
  42716. * @readonly
  42717. */
  42718. get coordinateSystem() {}
  42719. // render context
  42720. /**
  42721. * This method is executed at the beginning of a render call and
  42722. * can be used by the backend to prepare the state for upcoming
  42723. * draw calls.
  42724. *
  42725. * @abstract
  42726. * @param {RenderContext} renderContext - The render context.
  42727. */
  42728. beginRender( /*renderContext*/ ) {}
  42729. /**
  42730. * This method is executed at the end of a render call and
  42731. * can be used by the backend to finalize work after draw
  42732. * calls.
  42733. *
  42734. * @abstract
  42735. * @param {RenderContext} renderContext - The render context.
  42736. */
  42737. finishRender( /*renderContext*/ ) {}
  42738. /**
  42739. * This method is executed at the beginning of a compute call and
  42740. * can be used by the backend to prepare the state for upcoming
  42741. * compute tasks.
  42742. *
  42743. * @abstract
  42744. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42745. */
  42746. beginCompute( /*computeGroup*/ ) {}
  42747. /**
  42748. * This method is executed at the end of a compute call and
  42749. * can be used by the backend to finalize work after compute
  42750. * tasks.
  42751. *
  42752. * @abstract
  42753. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42754. */
  42755. finishCompute( /*computeGroup*/ ) {}
  42756. // render object
  42757. /**
  42758. * Executes a draw command for the given render object.
  42759. *
  42760. * @abstract
  42761. * @param {RenderObject} renderObject - The render object to draw.
  42762. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  42763. */
  42764. draw( /*renderObject, info*/ ) { }
  42765. // compute node
  42766. /**
  42767. * Executes a compute command for the given compute node.
  42768. *
  42769. * @abstract
  42770. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  42771. * @param {Node} computeNode - The compute node.
  42772. * @param {Array<BindGroup>} bindings - The bindings.
  42773. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42774. */
  42775. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  42776. // program
  42777. /**
  42778. * Creates a shader program from the given programmable stage.
  42779. *
  42780. * @abstract
  42781. * @param {ProgrammableStage} program - The programmable stage.
  42782. */
  42783. createProgram( /*program*/ ) { }
  42784. /**
  42785. * Destroys the shader program of the given programmable stage.
  42786. *
  42787. * @abstract
  42788. * @param {ProgrammableStage} program - The programmable stage.
  42789. */
  42790. destroyProgram( /*program*/ ) { }
  42791. // bindings
  42792. /**
  42793. * Creates bindings from the given bind group definition.
  42794. *
  42795. * @abstract
  42796. * @param {BindGroup} bindGroup - The bind group.
  42797. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42798. * @param {number} cacheIndex - The cache index.
  42799. * @param {number} version - The version.
  42800. */
  42801. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  42802. /**
  42803. * Updates the given bind group definition.
  42804. *
  42805. * @abstract
  42806. * @param {BindGroup} bindGroup - The bind group.
  42807. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42808. * @param {number} cacheIndex - The cache index.
  42809. * @param {number} version - The version.
  42810. */
  42811. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  42812. /**
  42813. * Updates a buffer binding.
  42814. *
  42815. * @abstract
  42816. * @param {Buffer} binding - The buffer binding to update.
  42817. */
  42818. updateBinding( /*binding*/ ) { }
  42819. // pipeline
  42820. /**
  42821. * Creates a render pipeline for the given render object.
  42822. *
  42823. * @abstract
  42824. * @param {RenderObject} renderObject - The render object.
  42825. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  42826. */
  42827. createRenderPipeline( /*renderObject, promises*/ ) { }
  42828. /**
  42829. * Creates a compute pipeline for the given compute node.
  42830. *
  42831. * @abstract
  42832. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42833. * @param {Array<BindGroup>} bindings - The bindings.
  42834. */
  42835. createComputePipeline( /*computePipeline, bindings*/ ) { }
  42836. // cache key
  42837. /**
  42838. * Returns `true` if the render pipeline requires an update.
  42839. *
  42840. * @abstract
  42841. * @param {RenderObject} renderObject - The render object.
  42842. * @return {boolean} Whether the render pipeline requires an update or not.
  42843. */
  42844. needsRenderUpdate( /*renderObject*/ ) { }
  42845. /**
  42846. * Returns a cache key that is used to identify render pipelines.
  42847. *
  42848. * @abstract
  42849. * @param {RenderObject} renderObject - The render object.
  42850. * @return {string} The cache key.
  42851. */
  42852. getRenderCacheKey( /*renderObject*/ ) { }
  42853. // node builder
  42854. /**
  42855. * Returns a node builder for the given render object.
  42856. *
  42857. * @abstract
  42858. * @param {RenderObject} renderObject - The render object.
  42859. * @param {Renderer} renderer - The renderer.
  42860. * @return {NodeBuilder} The node builder.
  42861. */
  42862. createNodeBuilder( /*renderObject, renderer*/ ) { }
  42863. // textures
  42864. /**
  42865. * Creates a GPU sampler for the given texture.
  42866. *
  42867. * @abstract
  42868. * @param {Texture} texture - The texture to create the sampler for.
  42869. */
  42870. createSampler( /*texture*/ ) { }
  42871. /**
  42872. * Destroys the GPU sampler for the given texture.
  42873. *
  42874. * @abstract
  42875. * @param {Texture} texture - The texture to destroy the sampler for.
  42876. */
  42877. destroySampler( /*texture*/ ) {}
  42878. /**
  42879. * Creates a default texture for the given texture that can be used
  42880. * as a placeholder until the actual texture is ready for usage.
  42881. *
  42882. * @abstract
  42883. * @param {Texture} texture - The texture to create a default texture for.
  42884. */
  42885. createDefaultTexture( /*texture*/ ) { }
  42886. /**
  42887. * Defines a texture on the GPU for the given texture object.
  42888. *
  42889. * @abstract
  42890. * @param {Texture} texture - The texture.
  42891. * @param {Object} [options={}] - Optional configuration parameter.
  42892. */
  42893. createTexture( /*texture, options={}*/ ) { }
  42894. /**
  42895. * Uploads the updated texture data to the GPU.
  42896. *
  42897. * @abstract
  42898. * @param {Texture} texture - The texture.
  42899. * @param {Object} [options={}] - Optional configuration parameter.
  42900. */
  42901. updateTexture( /*texture, options = {}*/ ) { }
  42902. /**
  42903. * Generates mipmaps for the given texture.
  42904. *
  42905. * @abstract
  42906. * @param {Texture} texture - The texture.
  42907. */
  42908. generateMipmaps( /*texture*/ ) { }
  42909. /**
  42910. * Destroys the GPU data for the given texture object.
  42911. *
  42912. * @abstract
  42913. * @param {Texture} texture - The texture.
  42914. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  42915. */
  42916. destroyTexture( /*texture, isDefaultTexture*/ ) { }
  42917. /**
  42918. * Returns texture data as a typed array.
  42919. *
  42920. * @abstract
  42921. * @async
  42922. * @param {Texture} texture - The texture to copy.
  42923. * @param {number} x - The x coordinate of the copy origin.
  42924. * @param {number} y - The y coordinate of the copy origin.
  42925. * @param {number} width - The width of the copy.
  42926. * @param {number} height - The height of the copy.
  42927. * @param {number} faceIndex - The face index.
  42928. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42929. */
  42930. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  42931. /**
  42932. * Copies data of the given source texture to the given destination texture.
  42933. *
  42934. * @abstract
  42935. * @param {Texture} srcTexture - The source texture.
  42936. * @param {Texture} dstTexture - The destination texture.
  42937. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  42938. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42939. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42940. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42941. */
  42942. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  42943. /**
  42944. * Copies the current bound framebuffer to the given texture.
  42945. *
  42946. * @abstract
  42947. * @param {Texture} texture - The destination texture.
  42948. * @param {RenderContext} renderContext - The render context.
  42949. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42950. */
  42951. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  42952. // attributes
  42953. /**
  42954. * Creates the GPU buffer of a shader attribute.
  42955. *
  42956. * @abstract
  42957. * @param {BufferAttribute} attribute - The buffer attribute.
  42958. */
  42959. createAttribute( /*attribute*/ ) { }
  42960. /**
  42961. * Creates the GPU buffer of an indexed shader attribute.
  42962. *
  42963. * @abstract
  42964. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  42965. */
  42966. createIndexAttribute( /*attribute*/ ) { }
  42967. /**
  42968. * Creates the GPU buffer of a storage attribute.
  42969. *
  42970. * @abstract
  42971. * @param {BufferAttribute} attribute - The buffer attribute.
  42972. */
  42973. createStorageAttribute( /*attribute*/ ) { }
  42974. /**
  42975. * Updates the GPU buffer of a shader attribute.
  42976. *
  42977. * @abstract
  42978. * @param {BufferAttribute} attribute - The buffer attribute to update.
  42979. */
  42980. updateAttribute( /*attribute*/ ) { }
  42981. /**
  42982. * Destroys the GPU buffer of a shader attribute.
  42983. *
  42984. * @abstract
  42985. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  42986. */
  42987. destroyAttribute( /*attribute*/ ) { }
  42988. // canvas
  42989. /**
  42990. * Returns the backend's rendering context.
  42991. *
  42992. * @abstract
  42993. * @return {Object} The rendering context.
  42994. */
  42995. getContext() { }
  42996. /**
  42997. * Backends can use this method if they have to run
  42998. * logic when the renderer gets resized.
  42999. *
  43000. * @abstract
  43001. */
  43002. updateSize() { }
  43003. /**
  43004. * Updates the viewport with the values from the given render context.
  43005. *
  43006. * @abstract
  43007. * @param {RenderContext} renderContext - The render context.
  43008. */
  43009. updateViewport( /*renderContext*/ ) {}
  43010. // utils
  43011. /**
  43012. * Returns a unique identifier for the given render context that can be used
  43013. * to allocate resources like occlusion queries or timestamp queries.
  43014. *
  43015. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  43016. * @return {string} The unique identifier.
  43017. */
  43018. getTimestampUID( abstractRenderContext ) {
  43019. const contextData = this.get( abstractRenderContext );
  43020. let uid = abstractRenderContext.isComputeNode === true ? 'c' : 'r';
  43021. uid += ':' + contextData.frameCalls + ':' + abstractRenderContext.id;
  43022. return uid;
  43023. }
  43024. /**
  43025. * Returns `true` if the given 3D object is fully occluded by other
  43026. * 3D objects in the scene. Backends must implement this method by using
  43027. * a Occlusion Query API.
  43028. *
  43029. * @abstract
  43030. * @param {RenderContext} renderContext - The render context.
  43031. * @param {Object3D} object - The 3D object to test.
  43032. * @return {boolean} Whether the 3D object is fully occluded or not.
  43033. */
  43034. isOccluded( /*renderContext, object*/ ) {}
  43035. /**
  43036. * Resolves the time stamp for the given render context and type.
  43037. *
  43038. * @async
  43039. * @abstract
  43040. * @param {string} [type='render'] - The type of the time stamp.
  43041. * @return {Promise<number>} A Promise that resolves with the time stamp.
  43042. */
  43043. async resolveTimestampsAsync( type = 'render' ) {
  43044. if ( ! this.trackTimestamp ) {
  43045. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  43046. return;
  43047. }
  43048. const queryPool = this.timestampQueryPool[ type ];
  43049. if ( ! queryPool ) {
  43050. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  43051. return;
  43052. }
  43053. const duration = await queryPool.resolveQueriesAsync();
  43054. this.renderer.info[ type ].timestamp = duration;
  43055. return duration;
  43056. }
  43057. /**
  43058. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43059. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43060. *
  43061. * @async
  43062. * @abstract
  43063. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43064. */
  43065. async waitForGPU() {}
  43066. /**
  43067. * This method performs a readback operation by moving buffer data from
  43068. * a storage buffer attribute from the GPU to the CPU.
  43069. *
  43070. * @async
  43071. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43072. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43073. */
  43074. async getArrayBufferAsync( /* attribute */ ) {}
  43075. /**
  43076. * Checks if the given feature is supported by the backend.
  43077. *
  43078. * @async
  43079. * @abstract
  43080. * @param {string} name - The feature's name.
  43081. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  43082. */
  43083. async hasFeatureAsync( /*name*/ ) { }
  43084. /**
  43085. * Checks if the given feature is supported by the backend.
  43086. *
  43087. * @abstract
  43088. * @param {string} name - The feature's name.
  43089. * @return {boolean} Whether the feature is supported or not.
  43090. */
  43091. hasFeature( /*name*/ ) {}
  43092. /**
  43093. * Returns the maximum anisotropy texture filtering value.
  43094. *
  43095. * @abstract
  43096. * @return {number} The maximum anisotropy texture filtering value.
  43097. */
  43098. getMaxAnisotropy() {}
  43099. /**
  43100. * Returns the drawing buffer size.
  43101. *
  43102. * @return {Vector2} The drawing buffer size.
  43103. */
  43104. getDrawingBufferSize() {
  43105. _vector2 = _vector2 || new Vector2();
  43106. return this.renderer.getDrawingBufferSize( _vector2 );
  43107. }
  43108. /**
  43109. * Defines the scissor test.
  43110. *
  43111. * @abstract
  43112. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43113. */
  43114. setScissorTest( /*boolean*/ ) { }
  43115. /**
  43116. * Returns the clear color and alpha into a single
  43117. * color object.
  43118. *
  43119. * @return {Color4} The clear color.
  43120. */
  43121. getClearColor() {
  43122. const renderer = this.renderer;
  43123. _color4 = _color4 || new Color4();
  43124. renderer.getClearColor( _color4 );
  43125. _color4.getRGB( _color4 );
  43126. return _color4;
  43127. }
  43128. /**
  43129. * Returns the DOM element. If no DOM element exists, the backend
  43130. * creates a new one.
  43131. *
  43132. * @return {HTMLCanvasElement} The DOM element.
  43133. */
  43134. getDomElement() {
  43135. let domElement = this.domElement;
  43136. if ( domElement === null ) {
  43137. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  43138. // OffscreenCanvas does not have setAttribute, see #22811
  43139. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  43140. this.domElement = domElement;
  43141. }
  43142. return domElement;
  43143. }
  43144. /**
  43145. * Sets a dictionary for the given object into the
  43146. * internal data structure.
  43147. *
  43148. * @param {Object} object - The object.
  43149. * @param {Object} value - The dictionary to set.
  43150. */
  43151. set( object, value ) {
  43152. this.data.set( object, value );
  43153. }
  43154. /**
  43155. * Returns the dictionary for the given object.
  43156. *
  43157. * @param {Object} object - The object.
  43158. * @return {Object} The object's dictionary.
  43159. */
  43160. get( object ) {
  43161. let map = this.data.get( object );
  43162. if ( map === undefined ) {
  43163. map = {};
  43164. this.data.set( object, map );
  43165. }
  43166. return map;
  43167. }
  43168. /**
  43169. * Checks if the given object has a dictionary
  43170. * with data defined.
  43171. *
  43172. * @param {Object} object - The object.
  43173. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  43174. */
  43175. has( object ) {
  43176. return this.data.has( object );
  43177. }
  43178. /**
  43179. * Deletes an object from the internal data structure.
  43180. *
  43181. * @param {Object} object - The object to delete.
  43182. */
  43183. delete( object ) {
  43184. this.data.delete( object );
  43185. }
  43186. /**
  43187. * Frees internal resources.
  43188. *
  43189. * @abstract
  43190. */
  43191. dispose() { }
  43192. }
  43193. let _id$1 = 0;
  43194. /**
  43195. * This module is internally used in context of compute shaders.
  43196. * This type of shader is not natively supported in WebGL 2 and
  43197. * thus implemented via Transform Feedback. `DualAttributeData`
  43198. * manages the related data.
  43199. *
  43200. * @private
  43201. */
  43202. class DualAttributeData {
  43203. constructor( attributeData, dualBuffer ) {
  43204. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  43205. this.type = attributeData.type;
  43206. this.bufferType = attributeData.bufferType;
  43207. this.pbo = attributeData.pbo;
  43208. this.byteLength = attributeData.byteLength;
  43209. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  43210. this.version = attributeData.version;
  43211. this.isInteger = attributeData.isInteger;
  43212. this.activeBufferIndex = 0;
  43213. this.baseId = attributeData.id;
  43214. }
  43215. get id() {
  43216. return `${ this.baseId }|${ this.activeBufferIndex }`;
  43217. }
  43218. get bufferGPU() {
  43219. return this.buffers[ this.activeBufferIndex ];
  43220. }
  43221. get transformBuffer() {
  43222. return this.buffers[ this.activeBufferIndex ^ 1 ];
  43223. }
  43224. switchBuffers() {
  43225. this.activeBufferIndex ^= 1;
  43226. }
  43227. }
  43228. /**
  43229. * A WebGL 2 backend utility module for managing shader attributes.
  43230. *
  43231. * @private
  43232. */
  43233. class WebGLAttributeUtils {
  43234. /**
  43235. * Constructs a new utility object.
  43236. *
  43237. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43238. */
  43239. constructor( backend ) {
  43240. /**
  43241. * A reference to the WebGL 2 backend.
  43242. *
  43243. * @type {WebGLBackend}
  43244. */
  43245. this.backend = backend;
  43246. }
  43247. /**
  43248. * Creates the GPU buffer for the given buffer attribute.
  43249. *
  43250. * @param {BufferAttribute} attribute - The buffer attribute.
  43251. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  43252. */
  43253. createAttribute( attribute, bufferType ) {
  43254. const backend = this.backend;
  43255. const { gl } = backend;
  43256. const array = attribute.array;
  43257. const usage = attribute.usage || gl.STATIC_DRAW;
  43258. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  43259. const bufferData = backend.get( bufferAttribute );
  43260. let bufferGPU = bufferData.bufferGPU;
  43261. if ( bufferGPU === undefined ) {
  43262. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  43263. bufferData.bufferGPU = bufferGPU;
  43264. bufferData.bufferType = bufferType;
  43265. bufferData.version = bufferAttribute.version;
  43266. }
  43267. //attribute.onUploadCallback();
  43268. let type;
  43269. if ( array instanceof Float32Array ) {
  43270. type = gl.FLOAT;
  43271. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  43272. type = gl.HALF_FLOAT;
  43273. } else if ( array instanceof Uint16Array ) {
  43274. if ( attribute.isFloat16BufferAttribute ) {
  43275. type = gl.HALF_FLOAT;
  43276. } else {
  43277. type = gl.UNSIGNED_SHORT;
  43278. }
  43279. } else if ( array instanceof Int16Array ) {
  43280. type = gl.SHORT;
  43281. } else if ( array instanceof Uint32Array ) {
  43282. type = gl.UNSIGNED_INT;
  43283. } else if ( array instanceof Int32Array ) {
  43284. type = gl.INT;
  43285. } else if ( array instanceof Int8Array ) {
  43286. type = gl.BYTE;
  43287. } else if ( array instanceof Uint8Array ) {
  43288. type = gl.UNSIGNED_BYTE;
  43289. } else if ( array instanceof Uint8ClampedArray ) {
  43290. type = gl.UNSIGNED_BYTE;
  43291. } else {
  43292. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  43293. }
  43294. let attributeData = {
  43295. bufferGPU,
  43296. bufferType,
  43297. type,
  43298. byteLength: array.byteLength,
  43299. bytesPerElement: array.BYTES_PER_ELEMENT,
  43300. version: attribute.version,
  43301. pbo: attribute.pbo,
  43302. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  43303. id: _id$1 ++
  43304. };
  43305. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  43306. // create buffer for transform feedback use
  43307. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  43308. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  43309. }
  43310. backend.set( attribute, attributeData );
  43311. }
  43312. /**
  43313. * Updates the GPU buffer of the given buffer attribute.
  43314. *
  43315. * @param {BufferAttribute} attribute - The buffer attribute.
  43316. */
  43317. updateAttribute( attribute ) {
  43318. const backend = this.backend;
  43319. const { gl } = backend;
  43320. const array = attribute.array;
  43321. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  43322. const bufferData = backend.get( bufferAttribute );
  43323. const bufferType = bufferData.bufferType;
  43324. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  43325. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  43326. if ( updateRanges.length === 0 ) {
  43327. // Not using update ranges
  43328. gl.bufferSubData( bufferType, 0, array );
  43329. } else {
  43330. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43331. const range = updateRanges[ i ];
  43332. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  43333. array, range.start, range.count );
  43334. }
  43335. bufferAttribute.clearUpdateRanges();
  43336. }
  43337. gl.bindBuffer( bufferType, null );
  43338. bufferData.version = bufferAttribute.version;
  43339. }
  43340. /**
  43341. * Destroys the GPU buffer of the given buffer attribute.
  43342. *
  43343. * @param {BufferAttribute} attribute - The buffer attribute.
  43344. */
  43345. destroyAttribute( attribute ) {
  43346. const backend = this.backend;
  43347. const { gl } = backend;
  43348. if ( attribute.isInterleavedBufferAttribute ) {
  43349. backend.delete( attribute.data );
  43350. }
  43351. const attributeData = backend.get( attribute );
  43352. gl.deleteBuffer( attributeData.bufferGPU );
  43353. backend.delete( attribute );
  43354. }
  43355. /**
  43356. * This method performs a readback operation by moving buffer data from
  43357. * a storage buffer attribute from the GPU to the CPU.
  43358. *
  43359. * @async
  43360. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43361. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43362. */
  43363. async getArrayBufferAsync( attribute ) {
  43364. const backend = this.backend;
  43365. const { gl } = backend;
  43366. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  43367. const { bufferGPU } = backend.get( bufferAttribute );
  43368. const array = attribute.array;
  43369. const byteLength = array.byteLength;
  43370. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  43371. const writeBuffer = gl.createBuffer();
  43372. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  43373. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  43374. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  43375. await backend.utils._clientWaitAsync();
  43376. const dstBuffer = new attribute.array.constructor( array.length );
  43377. // Ensure the buffer is bound before reading
  43378. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  43379. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  43380. gl.deleteBuffer( writeBuffer );
  43381. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  43382. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  43383. return dstBuffer.buffer;
  43384. }
  43385. /**
  43386. * Creates a WebGL buffer with the given data.
  43387. *
  43388. * @private
  43389. * @param {WebGL2RenderingContext} gl - The rendering context.
  43390. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  43391. * @param {TypedArray} array - The array of the buffer attribute.
  43392. * @param {GLenum} usage - The usage.
  43393. * @return {WebGLBuffer} The WebGL buffer.
  43394. */
  43395. _createBuffer( gl, bufferType, array, usage ) {
  43396. const bufferGPU = gl.createBuffer();
  43397. gl.bindBuffer( bufferType, bufferGPU );
  43398. gl.bufferData( bufferType, array, usage );
  43399. gl.bindBuffer( bufferType, null );
  43400. return bufferGPU;
  43401. }
  43402. }
  43403. let equationToGL, factorToGL;
  43404. /**
  43405. * A WebGL 2 backend utility module for managing the WebGL state.
  43406. *
  43407. * The major goal of this module is to reduce the number of state changes
  43408. * by caching the WEbGL state with a series of variables. In this way, the
  43409. * renderer only executes state change commands when necessary which
  43410. * improves the overall performance.
  43411. *
  43412. * @private
  43413. */
  43414. class WebGLState {
  43415. /**
  43416. * Constructs a new utility object.
  43417. *
  43418. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43419. */
  43420. constructor( backend ) {
  43421. /**
  43422. * A reference to the WebGL 2 backend.
  43423. *
  43424. * @type {WebGLBackend}
  43425. */
  43426. this.backend = backend;
  43427. /**
  43428. * A reference to the rendering context.
  43429. *
  43430. * @type {WebGL2RenderingContext}
  43431. */
  43432. this.gl = this.backend.gl;
  43433. // Below properties are intended to cache
  43434. // the WebGL state and are not explicitly
  43435. // documented for convenience reasons.
  43436. this.enabled = {};
  43437. this.currentFlipSided = null;
  43438. this.currentCullFace = null;
  43439. this.currentProgram = null;
  43440. this.currentBlendingEnabled = false;
  43441. this.currentBlending = null;
  43442. this.currentBlendSrc = null;
  43443. this.currentBlendDst = null;
  43444. this.currentBlendSrcAlpha = null;
  43445. this.currentBlendDstAlpha = null;
  43446. this.currentPremultipledAlpha = null;
  43447. this.currentPolygonOffsetFactor = null;
  43448. this.currentPolygonOffsetUnits = null;
  43449. this.currentColorMask = null;
  43450. this.currentDepthFunc = null;
  43451. this.currentDepthMask = null;
  43452. this.currentStencilFunc = null;
  43453. this.currentStencilRef = null;
  43454. this.currentStencilFuncMask = null;
  43455. this.currentStencilFail = null;
  43456. this.currentStencilZFail = null;
  43457. this.currentStencilZPass = null;
  43458. this.currentStencilMask = null;
  43459. this.currentLineWidth = null;
  43460. this.currentClippingPlanes = 0;
  43461. this.currentVAO = null;
  43462. this.currentIndex = null;
  43463. this.currentBoundFramebuffers = {};
  43464. this.currentDrawbuffers = new WeakMap();
  43465. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  43466. this.currentTextureSlot = null;
  43467. this.currentBoundTextures = {};
  43468. this.currentBoundBufferBases = {};
  43469. this._init();
  43470. }
  43471. /**
  43472. * Inits the state of the utility.
  43473. *
  43474. * @private
  43475. */
  43476. _init() {
  43477. const gl = this.gl;
  43478. // Store only WebGL constants here.
  43479. equationToGL = {
  43480. [ AddEquation ]: gl.FUNC_ADD,
  43481. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  43482. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  43483. };
  43484. factorToGL = {
  43485. [ ZeroFactor ]: gl.ZERO,
  43486. [ OneFactor ]: gl.ONE,
  43487. [ SrcColorFactor ]: gl.SRC_COLOR,
  43488. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  43489. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  43490. [ DstColorFactor ]: gl.DST_COLOR,
  43491. [ DstAlphaFactor ]: gl.DST_ALPHA,
  43492. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  43493. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  43494. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  43495. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  43496. };
  43497. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  43498. const viewportParam = gl.getParameter( gl.VIEWPORT );
  43499. this.currentScissor = new Vector4().fromArray( scissorParam );
  43500. this.currentViewport = new Vector4().fromArray( viewportParam );
  43501. this._tempVec4 = new Vector4();
  43502. }
  43503. /**
  43504. * Enables the given WebGL capability.
  43505. *
  43506. * This method caches the capability state so
  43507. * `gl.enable()` is only called when necessary.
  43508. *
  43509. * @param {GLenum} id - The capability to enable.
  43510. */
  43511. enable( id ) {
  43512. const { enabled } = this;
  43513. if ( enabled[ id ] !== true ) {
  43514. this.gl.enable( id );
  43515. enabled[ id ] = true;
  43516. }
  43517. }
  43518. /**
  43519. * Disables the given WebGL capability.
  43520. *
  43521. * This method caches the capability state so
  43522. * `gl.disable()` is only called when necessary.
  43523. *
  43524. * @param {GLenum} id - The capability to enable.
  43525. */
  43526. disable( id ) {
  43527. const { enabled } = this;
  43528. if ( enabled[ id ] !== false ) {
  43529. this.gl.disable( id );
  43530. enabled[ id ] = false;
  43531. }
  43532. }
  43533. /**
  43534. * Specifies whether polygons are front- or back-facing
  43535. * by setting the winding orientation.
  43536. *
  43537. * This method caches the state so `gl.frontFace()` is only
  43538. * called when necessary.
  43539. *
  43540. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  43541. */
  43542. setFlipSided( flipSided ) {
  43543. if ( this.currentFlipSided !== flipSided ) {
  43544. const { gl } = this;
  43545. if ( flipSided ) {
  43546. gl.frontFace( gl.CW );
  43547. } else {
  43548. gl.frontFace( gl.CCW );
  43549. }
  43550. this.currentFlipSided = flipSided;
  43551. }
  43552. }
  43553. /**
  43554. * Specifies whether or not front- and/or back-facing
  43555. * polygons can be culled.
  43556. *
  43557. * This method caches the state so `gl.cullFace()` is only
  43558. * called when necessary.
  43559. *
  43560. * @param {number} cullFace - Defines which polygons are candidates for culling.
  43561. */
  43562. setCullFace( cullFace ) {
  43563. const { gl } = this;
  43564. if ( cullFace !== CullFaceNone ) {
  43565. this.enable( gl.CULL_FACE );
  43566. if ( cullFace !== this.currentCullFace ) {
  43567. if ( cullFace === CullFaceBack ) {
  43568. gl.cullFace( gl.BACK );
  43569. } else if ( cullFace === CullFaceFront ) {
  43570. gl.cullFace( gl.FRONT );
  43571. } else {
  43572. gl.cullFace( gl.FRONT_AND_BACK );
  43573. }
  43574. }
  43575. } else {
  43576. this.disable( gl.CULL_FACE );
  43577. }
  43578. this.currentCullFace = cullFace;
  43579. }
  43580. /**
  43581. * Specifies the width of line primitives.
  43582. *
  43583. * This method caches the state so `gl.lineWidth()` is only
  43584. * called when necessary.
  43585. *
  43586. * @param {number} width - The line width.
  43587. */
  43588. setLineWidth( width ) {
  43589. const { currentLineWidth, gl } = this;
  43590. if ( width !== currentLineWidth ) {
  43591. gl.lineWidth( width );
  43592. this.currentLineWidth = width;
  43593. }
  43594. }
  43595. /**
  43596. * Defines the blending.
  43597. *
  43598. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  43599. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  43600. *
  43601. * @param {number} blending - The blending type.
  43602. * @param {number} blendEquation - The blending equation.
  43603. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  43604. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  43605. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  43606. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  43607. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  43608. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  43609. */
  43610. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  43611. const { gl } = this;
  43612. if ( blending === NoBlending ) {
  43613. if ( this.currentBlendingEnabled === true ) {
  43614. this.disable( gl.BLEND );
  43615. this.currentBlendingEnabled = false;
  43616. }
  43617. return;
  43618. }
  43619. if ( this.currentBlendingEnabled === false ) {
  43620. this.enable( gl.BLEND );
  43621. this.currentBlendingEnabled = true;
  43622. }
  43623. if ( blending !== CustomBlending ) {
  43624. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  43625. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  43626. gl.blendEquation( gl.FUNC_ADD );
  43627. this.currentBlendEquation = AddEquation;
  43628. this.currentBlendEquationAlpha = AddEquation;
  43629. }
  43630. if ( premultipliedAlpha ) {
  43631. switch ( blending ) {
  43632. case NormalBlending:
  43633. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  43634. break;
  43635. case AdditiveBlending:
  43636. gl.blendFunc( gl.ONE, gl.ONE );
  43637. break;
  43638. case SubtractiveBlending:
  43639. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  43640. break;
  43641. case MultiplyBlending:
  43642. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  43643. break;
  43644. default:
  43645. error( 'WebGLState: Invalid blending: ', blending );
  43646. break;
  43647. }
  43648. } else {
  43649. switch ( blending ) {
  43650. case NormalBlending:
  43651. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  43652. break;
  43653. case AdditiveBlending:
  43654. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  43655. break;
  43656. case SubtractiveBlending:
  43657. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  43658. break;
  43659. case MultiplyBlending:
  43660. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  43661. break;
  43662. default:
  43663. error( 'WebGLState: Invalid blending: ', blending );
  43664. break;
  43665. }
  43666. }
  43667. this.currentBlendSrc = null;
  43668. this.currentBlendDst = null;
  43669. this.currentBlendSrcAlpha = null;
  43670. this.currentBlendDstAlpha = null;
  43671. this.currentBlending = blending;
  43672. this.currentPremultipledAlpha = premultipliedAlpha;
  43673. }
  43674. return;
  43675. }
  43676. // custom blending
  43677. blendEquationAlpha = blendEquationAlpha || blendEquation;
  43678. blendSrcAlpha = blendSrcAlpha || blendSrc;
  43679. blendDstAlpha = blendDstAlpha || blendDst;
  43680. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  43681. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  43682. this.currentBlendEquation = blendEquation;
  43683. this.currentBlendEquationAlpha = blendEquationAlpha;
  43684. }
  43685. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  43686. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  43687. this.currentBlendSrc = blendSrc;
  43688. this.currentBlendDst = blendDst;
  43689. this.currentBlendSrcAlpha = blendSrcAlpha;
  43690. this.currentBlendDstAlpha = blendDstAlpha;
  43691. }
  43692. this.currentBlending = blending;
  43693. this.currentPremultipledAlpha = false;
  43694. }
  43695. /**
  43696. * Specifies whether colors can be written when rendering
  43697. * into a framebuffer or not.
  43698. *
  43699. * This method caches the state so `gl.colorMask()` is only
  43700. * called when necessary.
  43701. *
  43702. * @param {boolean} colorMask - The color mask.
  43703. */
  43704. setColorMask( colorMask ) {
  43705. if ( this.currentColorMask !== colorMask ) {
  43706. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  43707. this.currentColorMask = colorMask;
  43708. }
  43709. }
  43710. /**
  43711. * Specifies whether the depth test is enabled or not.
  43712. *
  43713. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  43714. */
  43715. setDepthTest( depthTest ) {
  43716. const { gl } = this;
  43717. if ( depthTest ) {
  43718. this.enable( gl.DEPTH_TEST );
  43719. } else {
  43720. this.disable( gl.DEPTH_TEST );
  43721. }
  43722. }
  43723. /**
  43724. * Specifies whether depth values can be written when rendering
  43725. * into a framebuffer or not.
  43726. *
  43727. * This method caches the state so `gl.depthMask()` is only
  43728. * called when necessary.
  43729. *
  43730. * @param {boolean} depthMask - The depth mask.
  43731. */
  43732. setDepthMask( depthMask ) {
  43733. if ( this.currentDepthMask !== depthMask ) {
  43734. this.gl.depthMask( depthMask );
  43735. this.currentDepthMask = depthMask;
  43736. }
  43737. }
  43738. /**
  43739. * Specifies the depth compare function.
  43740. *
  43741. * This method caches the state so `gl.depthFunc()` is only
  43742. * called when necessary.
  43743. *
  43744. * @param {number} depthFunc - The depth compare function.
  43745. */
  43746. setDepthFunc( depthFunc ) {
  43747. if ( this.currentDepthFunc !== depthFunc ) {
  43748. const { gl } = this;
  43749. switch ( depthFunc ) {
  43750. case NeverDepth:
  43751. gl.depthFunc( gl.NEVER );
  43752. break;
  43753. case AlwaysDepth:
  43754. gl.depthFunc( gl.ALWAYS );
  43755. break;
  43756. case LessDepth:
  43757. gl.depthFunc( gl.LESS );
  43758. break;
  43759. case LessEqualDepth:
  43760. gl.depthFunc( gl.LEQUAL );
  43761. break;
  43762. case EqualDepth:
  43763. gl.depthFunc( gl.EQUAL );
  43764. break;
  43765. case GreaterEqualDepth:
  43766. gl.depthFunc( gl.GEQUAL );
  43767. break;
  43768. case GreaterDepth:
  43769. gl.depthFunc( gl.GREATER );
  43770. break;
  43771. case NotEqualDepth:
  43772. gl.depthFunc( gl.NOTEQUAL );
  43773. break;
  43774. default:
  43775. gl.depthFunc( gl.LEQUAL );
  43776. }
  43777. this.currentDepthFunc = depthFunc;
  43778. }
  43779. }
  43780. /**
  43781. * Specifies the scissor box.
  43782. *
  43783. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  43784. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  43785. * @param {number} width - The width of the viewport.
  43786. * @param {number} height - The height of the viewport.
  43787. *
  43788. */
  43789. scissor( x, y, width, height ) {
  43790. const scissor = this._tempVec4.set( x, y, width, height );
  43791. if ( this.currentScissor.equals( scissor ) === false ) {
  43792. const { gl } = this;
  43793. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  43794. this.currentScissor.copy( scissor );
  43795. }
  43796. }
  43797. /**
  43798. * Specifies the viewport.
  43799. *
  43800. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  43801. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  43802. * @param {number} width - The width of the viewport.
  43803. * @param {number} height - The height of the viewport.
  43804. *
  43805. */
  43806. viewport( x, y, width, height ) {
  43807. const viewport = this._tempVec4.set( x, y, width, height );
  43808. if ( this.currentViewport.equals( viewport ) === false ) {
  43809. const { gl } = this;
  43810. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  43811. this.currentViewport.copy( viewport );
  43812. }
  43813. }
  43814. /**
  43815. * Defines the scissor test.
  43816. *
  43817. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43818. */
  43819. setScissorTest( boolean ) {
  43820. const gl = this.gl;
  43821. if ( boolean ) {
  43822. gl.enable( gl.SCISSOR_TEST );
  43823. } else {
  43824. gl.disable( gl.SCISSOR_TEST );
  43825. }
  43826. }
  43827. /**
  43828. * Specifies whether the stencil test is enabled or not.
  43829. *
  43830. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  43831. */
  43832. setStencilTest( stencilTest ) {
  43833. const { gl } = this;
  43834. if ( stencilTest ) {
  43835. this.enable( gl.STENCIL_TEST );
  43836. } else {
  43837. this.disable( gl.STENCIL_TEST );
  43838. }
  43839. }
  43840. /**
  43841. * Specifies whether stencil values can be written when rendering
  43842. * into a framebuffer or not.
  43843. *
  43844. * This method caches the state so `gl.stencilMask()` is only
  43845. * called when necessary.
  43846. *
  43847. * @param {boolean} stencilMask - The stencil mask.
  43848. */
  43849. setStencilMask( stencilMask ) {
  43850. if ( this.currentStencilMask !== stencilMask ) {
  43851. this.gl.stencilMask( stencilMask );
  43852. this.currentStencilMask = stencilMask;
  43853. }
  43854. }
  43855. /**
  43856. * Specifies whether the stencil test functions.
  43857. *
  43858. * This method caches the state so `gl.stencilFunc()` is only
  43859. * called when necessary.
  43860. *
  43861. * @param {number} stencilFunc - The stencil compare function.
  43862. * @param {number} stencilRef - The reference value for the stencil test.
  43863. * @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.
  43864. */
  43865. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  43866. if ( this.currentStencilFunc !== stencilFunc ||
  43867. this.currentStencilRef !== stencilRef ||
  43868. this.currentStencilFuncMask !== stencilMask ) {
  43869. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  43870. this.currentStencilFunc = stencilFunc;
  43871. this.currentStencilRef = stencilRef;
  43872. this.currentStencilFuncMask = stencilMask;
  43873. }
  43874. }
  43875. /**
  43876. * Specifies whether the stencil test operation.
  43877. *
  43878. * This method caches the state so `gl.stencilOp()` is only
  43879. * called when necessary.
  43880. *
  43881. * @param {number} stencilFail - The function to use when the stencil test fails.
  43882. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  43883. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  43884. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  43885. */
  43886. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  43887. if ( this.currentStencilFail !== stencilFail ||
  43888. this.currentStencilZFail !== stencilZFail ||
  43889. this.currentStencilZPass !== stencilZPass ) {
  43890. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  43891. this.currentStencilFail = stencilFail;
  43892. this.currentStencilZFail = stencilZFail;
  43893. this.currentStencilZPass = stencilZPass;
  43894. }
  43895. }
  43896. /**
  43897. * Configures the WebGL state for the given material.
  43898. *
  43899. * @param {Material} material - The material to configure the state for.
  43900. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  43901. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  43902. */
  43903. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  43904. const { gl } = this;
  43905. material.side === DoubleSide
  43906. ? this.disable( gl.CULL_FACE )
  43907. : this.enable( gl.CULL_FACE );
  43908. let flipSided = ( material.side === BackSide );
  43909. if ( frontFaceCW ) flipSided = ! flipSided;
  43910. this.setFlipSided( flipSided );
  43911. ( material.blending === NormalBlending && material.transparent === false )
  43912. ? this.setBlending( NoBlending )
  43913. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  43914. this.setDepthFunc( material.depthFunc );
  43915. this.setDepthTest( material.depthTest );
  43916. this.setDepthMask( material.depthWrite );
  43917. this.setColorMask( material.colorWrite );
  43918. const stencilWrite = material.stencilWrite;
  43919. this.setStencilTest( stencilWrite );
  43920. if ( stencilWrite ) {
  43921. this.setStencilMask( material.stencilWriteMask );
  43922. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  43923. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  43924. }
  43925. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  43926. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  43927. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  43928. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  43929. if ( hardwareClippingPlanes > 0 ) {
  43930. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  43931. const CLIP_DISTANCE0_WEBGL = 0x3000;
  43932. for ( let i = 0; i < 8; i ++ ) {
  43933. if ( i < hardwareClippingPlanes ) {
  43934. this.enable( CLIP_DISTANCE0_WEBGL + i );
  43935. } else {
  43936. this.disable( CLIP_DISTANCE0_WEBGL + i );
  43937. }
  43938. }
  43939. }
  43940. }
  43941. }
  43942. /**
  43943. * Specifies the polygon offset.
  43944. *
  43945. * This method caches the state so `gl.polygonOffset()` is only
  43946. * called when necessary.
  43947. *
  43948. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  43949. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  43950. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  43951. */
  43952. setPolygonOffset( polygonOffset, factor, units ) {
  43953. const { gl } = this;
  43954. if ( polygonOffset ) {
  43955. this.enable( gl.POLYGON_OFFSET_FILL );
  43956. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  43957. gl.polygonOffset( factor, units );
  43958. this.currentPolygonOffsetFactor = factor;
  43959. this.currentPolygonOffsetUnits = units;
  43960. }
  43961. } else {
  43962. this.disable( gl.POLYGON_OFFSET_FILL );
  43963. }
  43964. }
  43965. /**
  43966. * Defines the usage of the given WebGL program.
  43967. *
  43968. * This method caches the state so `gl.useProgram()` is only
  43969. * called when necessary.
  43970. *
  43971. * @param {WebGLProgram} program - The WebGL program to use.
  43972. * @return {boolean} Whether a program change has been executed or not.
  43973. */
  43974. useProgram( program ) {
  43975. if ( this.currentProgram !== program ) {
  43976. this.gl.useProgram( program );
  43977. this.currentProgram = program;
  43978. return true;
  43979. }
  43980. return false;
  43981. }
  43982. /**
  43983. * Sets the vertex state by binding the given VAO and element buffer.
  43984. *
  43985. * @param {WebGLVertexArrayObject} vao - The VAO.
  43986. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  43987. * @return {boolean} Whether a vertex state has been changed or not.
  43988. */
  43989. setVertexState( vao, indexBuffer = null ) {
  43990. const gl = this.gl;
  43991. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  43992. gl.bindVertexArray( vao );
  43993. if ( indexBuffer !== null ) {
  43994. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  43995. }
  43996. this.currentVAO = vao;
  43997. this.currentIndex = indexBuffer;
  43998. return true;
  43999. }
  44000. return false;
  44001. }
  44002. /**
  44003. * Resets the vertex array state by resetting the VAO and element buffer.
  44004. */
  44005. resetVertexState() {
  44006. const gl = this.gl;
  44007. gl.bindVertexArray( null );
  44008. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  44009. this.currentVAO = null;
  44010. this.currentIndex = null;
  44011. }
  44012. // framebuffer
  44013. /**
  44014. * Binds the given framebuffer.
  44015. *
  44016. * This method caches the state so `gl.bindFramebuffer()` is only
  44017. * called when necessary.
  44018. *
  44019. * @param {number} target - The binding point (target).
  44020. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  44021. * @return {boolean} Whether a bind has been executed or not.
  44022. */
  44023. bindFramebuffer( target, framebuffer ) {
  44024. const { gl, currentBoundFramebuffers } = this;
  44025. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  44026. gl.bindFramebuffer( target, framebuffer );
  44027. currentBoundFramebuffers[ target ] = framebuffer;
  44028. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  44029. if ( target === gl.DRAW_FRAMEBUFFER ) {
  44030. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  44031. }
  44032. if ( target === gl.FRAMEBUFFER ) {
  44033. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  44034. }
  44035. return true;
  44036. }
  44037. return false;
  44038. }
  44039. /**
  44040. * Defines draw buffers to which fragment colors are written into.
  44041. * Configures the MRT setup of custom framebuffers.
  44042. *
  44043. * This method caches the state so `gl.drawBuffers()` is only
  44044. * called when necessary.
  44045. *
  44046. * @param {RenderContext} renderContext - The render context.
  44047. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  44048. */
  44049. drawBuffers( renderContext, framebuffer ) {
  44050. const { gl } = this;
  44051. let drawBuffers = [];
  44052. let needsUpdate = false;
  44053. if ( renderContext.textures !== null ) {
  44054. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  44055. if ( drawBuffers === undefined ) {
  44056. drawBuffers = [];
  44057. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  44058. }
  44059. const textures = renderContext.textures;
  44060. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  44061. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  44062. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  44063. }
  44064. drawBuffers.length = textures.length;
  44065. needsUpdate = true;
  44066. }
  44067. } else {
  44068. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  44069. drawBuffers[ 0 ] = gl.BACK;
  44070. needsUpdate = true;
  44071. }
  44072. }
  44073. if ( needsUpdate ) {
  44074. gl.drawBuffers( drawBuffers );
  44075. }
  44076. }
  44077. // texture
  44078. /**
  44079. * Makes the given texture unit active.
  44080. *
  44081. * This method caches the state so `gl.activeTexture()` is only
  44082. * called when necessary.
  44083. *
  44084. * @param {number} webglSlot - The texture unit to make active.
  44085. */
  44086. activeTexture( webglSlot ) {
  44087. const { gl, currentTextureSlot, maxTextures } = this;
  44088. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  44089. if ( currentTextureSlot !== webglSlot ) {
  44090. gl.activeTexture( webglSlot );
  44091. this.currentTextureSlot = webglSlot;
  44092. }
  44093. }
  44094. /**
  44095. * Binds the given WebGL texture to a target.
  44096. *
  44097. * This method caches the state so `gl.bindTexture()` is only
  44098. * called when necessary.
  44099. *
  44100. * @param {number} webglType - The binding point (target).
  44101. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  44102. * @param {number} webglSlot - The texture.
  44103. */
  44104. bindTexture( webglType, webglTexture, webglSlot ) {
  44105. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  44106. if ( webglSlot === undefined ) {
  44107. if ( currentTextureSlot === null ) {
  44108. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  44109. } else {
  44110. webglSlot = currentTextureSlot;
  44111. }
  44112. }
  44113. let boundTexture = currentBoundTextures[ webglSlot ];
  44114. if ( boundTexture === undefined ) {
  44115. boundTexture = { type: undefined, texture: undefined };
  44116. currentBoundTextures[ webglSlot ] = boundTexture;
  44117. }
  44118. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  44119. if ( currentTextureSlot !== webglSlot ) {
  44120. gl.activeTexture( webglSlot );
  44121. this.currentTextureSlot = webglSlot;
  44122. }
  44123. gl.bindTexture( webglType, webglTexture );
  44124. boundTexture.type = webglType;
  44125. boundTexture.texture = webglTexture;
  44126. }
  44127. }
  44128. /**
  44129. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  44130. *
  44131. * This method caches the state so `gl.bindBufferBase()` is only
  44132. * called when necessary.
  44133. *
  44134. * @param {number} target - The target for the bind operation.
  44135. * @param {number} index - The index of the target.
  44136. * @param {WebGLBuffer} buffer - The WebGL buffer.
  44137. * @return {boolean} Whether a bind has been executed or not.
  44138. */
  44139. bindBufferBase( target, index, buffer ) {
  44140. const { gl } = this;
  44141. const key = `${target}-${index}`;
  44142. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  44143. gl.bindBufferBase( target, index, buffer );
  44144. this.currentBoundBufferBases[ key ] = buffer;
  44145. return true;
  44146. }
  44147. return false;
  44148. }
  44149. /**
  44150. * Unbinds the current bound texture.
  44151. *
  44152. * This method caches the state so `gl.bindTexture()` is only
  44153. * called when necessary.
  44154. */
  44155. unbindTexture() {
  44156. const { gl, currentTextureSlot, currentBoundTextures } = this;
  44157. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  44158. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  44159. gl.bindTexture( boundTexture.type, null );
  44160. boundTexture.type = undefined;
  44161. boundTexture.texture = undefined;
  44162. }
  44163. }
  44164. }
  44165. /**
  44166. * A WebGL 2 backend utility module with common helpers.
  44167. *
  44168. * @private
  44169. */
  44170. class WebGLUtils {
  44171. /**
  44172. * Constructs a new utility object.
  44173. *
  44174. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44175. */
  44176. constructor( backend ) {
  44177. /**
  44178. * A reference to the WebGL 2 backend.
  44179. *
  44180. * @type {WebGLBackend}
  44181. */
  44182. this.backend = backend;
  44183. /**
  44184. * A reference to the rendering context.
  44185. *
  44186. * @type {WebGL2RenderingContext}
  44187. */
  44188. this.gl = this.backend.gl;
  44189. /**
  44190. * A reference to a backend module holding extension-related
  44191. * utility functions.
  44192. *
  44193. * @type {WebGLExtensions}
  44194. */
  44195. this.extensions = backend.extensions;
  44196. }
  44197. /**
  44198. * Converts the given three.js constant into a WebGL constant.
  44199. * The method currently supports the conversion of texture formats
  44200. * and types.
  44201. *
  44202. * @param {number} p - The three.js constant.
  44203. * @param {string} [colorSpace=NoColorSpace] - The color space.
  44204. * @return {?number} The corresponding WebGL constant.
  44205. */
  44206. convert( p, colorSpace = NoColorSpace ) {
  44207. const { gl, extensions } = this;
  44208. let extension;
  44209. const transfer = ColorManagement.getTransfer( colorSpace );
  44210. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  44211. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  44212. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  44213. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  44214. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  44215. if ( p === ByteType ) return gl.BYTE;
  44216. if ( p === ShortType ) return gl.SHORT;
  44217. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  44218. if ( p === IntType ) return gl.INT;
  44219. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  44220. if ( p === FloatType ) return gl.FLOAT;
  44221. if ( p === HalfFloatType ) {
  44222. return gl.HALF_FLOAT;
  44223. }
  44224. if ( p === AlphaFormat ) return gl.ALPHA;
  44225. if ( p === RGBFormat ) return gl.RGB;
  44226. if ( p === RGBAFormat ) return gl.RGBA;
  44227. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  44228. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  44229. // WebGL2 formats.
  44230. if ( p === RedFormat ) return gl.RED;
  44231. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  44232. if ( p === RGFormat ) return gl.RG;
  44233. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  44234. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  44235. // S3TC
  44236. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  44237. if ( transfer === SRGBTransfer ) {
  44238. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  44239. if ( extension !== null ) {
  44240. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  44241. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  44242. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  44243. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  44244. } else {
  44245. return null;
  44246. }
  44247. } else {
  44248. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  44249. if ( extension !== null ) {
  44250. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  44251. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  44252. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  44253. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  44254. } else {
  44255. return null;
  44256. }
  44257. }
  44258. }
  44259. // PVRTC
  44260. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  44261. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  44262. if ( extension !== null ) {
  44263. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  44264. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  44265. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  44266. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  44267. } else {
  44268. return null;
  44269. }
  44270. }
  44271. // ETC
  44272. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  44273. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  44274. if ( extension !== null ) {
  44275. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  44276. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  44277. } else {
  44278. return null;
  44279. }
  44280. }
  44281. // ASTC
  44282. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  44283. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  44284. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  44285. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  44286. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  44287. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  44288. if ( extension !== null ) {
  44289. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  44290. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  44291. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  44292. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  44293. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  44294. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  44295. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  44296. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  44297. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  44298. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  44299. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  44300. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  44301. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  44302. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  44303. } else {
  44304. return null;
  44305. }
  44306. }
  44307. // BPTC
  44308. if ( p === RGBA_BPTC_Format ) {
  44309. extension = extensions.get( 'EXT_texture_compression_bptc' );
  44310. if ( extension !== null ) {
  44311. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  44312. } else {
  44313. return null;
  44314. }
  44315. }
  44316. // RGTC
  44317. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  44318. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  44319. if ( extension !== null ) {
  44320. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  44321. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  44322. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  44323. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  44324. } else {
  44325. return null;
  44326. }
  44327. }
  44328. //
  44329. if ( p === UnsignedInt248Type ) {
  44330. return gl.UNSIGNED_INT_24_8;
  44331. }
  44332. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  44333. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  44334. }
  44335. /**
  44336. * This method can be used to synchronize the CPU with the GPU by waiting until
  44337. * ongoing GPU commands have been completed.
  44338. *
  44339. * @private
  44340. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  44341. */
  44342. _clientWaitAsync() {
  44343. const { gl } = this;
  44344. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  44345. gl.flush();
  44346. return new Promise( ( resolve, reject ) => {
  44347. function test() {
  44348. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  44349. if ( res === gl.WAIT_FAILED ) {
  44350. gl.deleteSync( sync );
  44351. reject();
  44352. return;
  44353. }
  44354. if ( res === gl.TIMEOUT_EXPIRED ) {
  44355. requestAnimationFrame( test );
  44356. return;
  44357. }
  44358. gl.deleteSync( sync );
  44359. resolve();
  44360. }
  44361. test();
  44362. } );
  44363. }
  44364. }
  44365. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  44366. /**
  44367. * A WebGL 2 backend utility module for managing textures.
  44368. *
  44369. * @private
  44370. */
  44371. class WebGLTextureUtils {
  44372. /**
  44373. * Constructs a new utility object.
  44374. *
  44375. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44376. */
  44377. constructor( backend ) {
  44378. /**
  44379. * A reference to the WebGL 2 backend.
  44380. *
  44381. * @type {WebGLBackend}
  44382. */
  44383. this.backend = backend;
  44384. /**
  44385. * A reference to the rendering context.
  44386. *
  44387. * @type {WebGL2RenderingContext}
  44388. */
  44389. this.gl = backend.gl;
  44390. /**
  44391. * A reference to a backend module holding extension-related
  44392. * utility functions.
  44393. *
  44394. * @type {WebGLExtensions}
  44395. */
  44396. this.extensions = backend.extensions;
  44397. /**
  44398. * A dictionary for managing default textures. The key
  44399. * is the binding point (target), the value the WEbGL texture object.
  44400. *
  44401. * @type {Object<GLenum,WebGLTexture>}
  44402. */
  44403. this.defaultTextures = {};
  44404. /**
  44405. * A scratch framebuffer used for attaching the source texture in
  44406. * {@link copyTextureToTexture}.
  44407. *
  44408. * @private
  44409. * @type {?WebGLFramebuffer}
  44410. */
  44411. this._srcFramebuffer = null;
  44412. /**
  44413. * A scratch framebuffer used for attaching the destination texture in
  44414. * {@link copyTextureToTexture}.
  44415. *
  44416. * @private
  44417. * @type {?WebGLFramebuffer}
  44418. */
  44419. this._dstFramebuffer = null;
  44420. if ( initialized === false ) {
  44421. this._init();
  44422. initialized = true;
  44423. }
  44424. }
  44425. /**
  44426. * Inits the state of the utility.
  44427. *
  44428. * @private
  44429. */
  44430. _init() {
  44431. const gl = this.gl;
  44432. // Store only WebGL constants here.
  44433. wrappingToGL = {
  44434. [ RepeatWrapping ]: gl.REPEAT,
  44435. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  44436. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  44437. };
  44438. filterToGL = {
  44439. [ NearestFilter ]: gl.NEAREST,
  44440. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  44441. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  44442. [ LinearFilter ]: gl.LINEAR,
  44443. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  44444. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  44445. };
  44446. compareToGL = {
  44447. [ NeverCompare ]: gl.NEVER,
  44448. [ AlwaysCompare ]: gl.ALWAYS,
  44449. [ LessCompare ]: gl.LESS,
  44450. [ LessEqualCompare ]: gl.LEQUAL,
  44451. [ EqualCompare ]: gl.EQUAL,
  44452. [ GreaterEqualCompare ]: gl.GEQUAL,
  44453. [ GreaterCompare ]: gl.GREATER,
  44454. [ NotEqualCompare ]: gl.NOTEQUAL
  44455. };
  44456. }
  44457. /**
  44458. * Returns the native texture type for the given texture.
  44459. *
  44460. * @param {Texture} texture - The texture.
  44461. * @return {GLenum} The native texture type.
  44462. */
  44463. getGLTextureType( texture ) {
  44464. const { gl } = this;
  44465. let glTextureType;
  44466. if ( texture.isCubeTexture === true ) {
  44467. glTextureType = gl.TEXTURE_CUBE_MAP;
  44468. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44469. glTextureType = gl.TEXTURE_2D_ARRAY;
  44470. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  44471. glTextureType = gl.TEXTURE_3D;
  44472. } else {
  44473. glTextureType = gl.TEXTURE_2D;
  44474. }
  44475. return glTextureType;
  44476. }
  44477. /**
  44478. * Returns the native texture type for the given texture.
  44479. *
  44480. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  44481. * @param {GLenum} glFormat - The WebGL format.
  44482. * @param {GLenum} glType - The WebGL type.
  44483. * @param {string} colorSpace - The texture's color space.
  44484. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  44485. * @return {GLenum} The internal format.
  44486. */
  44487. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  44488. const { gl, extensions } = this;
  44489. if ( internalFormatName !== null ) {
  44490. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  44491. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  44492. }
  44493. let internalFormat = glFormat;
  44494. if ( glFormat === gl.RED ) {
  44495. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  44496. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  44497. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  44498. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  44499. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  44500. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  44501. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  44502. if ( glType === gl.INT ) internalFormat = gl.R32I;
  44503. }
  44504. if ( glFormat === gl.RED_INTEGER ) {
  44505. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  44506. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  44507. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  44508. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  44509. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  44510. if ( glType === gl.INT ) internalFormat = gl.R32I;
  44511. }
  44512. if ( glFormat === gl.RG ) {
  44513. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  44514. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  44515. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  44516. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  44517. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  44518. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  44519. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  44520. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  44521. }
  44522. if ( glFormat === gl.RG_INTEGER ) {
  44523. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  44524. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  44525. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  44526. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  44527. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  44528. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  44529. }
  44530. if ( glFormat === gl.RGB ) {
  44531. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  44532. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  44533. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  44534. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  44535. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  44536. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  44537. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  44538. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  44539. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  44540. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  44541. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  44542. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  44543. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  44544. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  44545. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  44546. }
  44547. if ( glFormat === gl.RGB_INTEGER ) {
  44548. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  44549. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  44550. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  44551. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  44552. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  44553. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  44554. }
  44555. if ( glFormat === gl.RGBA ) {
  44556. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  44557. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  44558. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  44559. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  44560. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  44561. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  44562. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  44563. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  44564. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  44565. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  44566. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  44567. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  44568. }
  44569. if ( glFormat === gl.RGBA_INTEGER ) {
  44570. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  44571. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  44572. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  44573. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  44574. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  44575. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  44576. }
  44577. if ( glFormat === gl.DEPTH_COMPONENT ) {
  44578. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  44579. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  44580. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  44581. }
  44582. if ( glFormat === gl.DEPTH_STENCIL ) {
  44583. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  44584. }
  44585. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  44586. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  44587. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  44588. extensions.get( 'EXT_color_buffer_float' );
  44589. }
  44590. return internalFormat;
  44591. }
  44592. /**
  44593. * Sets the texture parameters for the given texture.
  44594. *
  44595. * @param {GLenum} textureType - The texture type.
  44596. * @param {Texture} texture - The texture.
  44597. */
  44598. setTextureParameters( textureType, texture ) {
  44599. const { gl, extensions, backend } = this;
  44600. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  44601. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  44602. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  44603. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  44604. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  44605. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  44606. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  44607. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  44608. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  44609. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  44610. // WebGL 2 does not support wrapping for depth 2D array textures
  44611. if ( ! texture.isArrayTexture ) {
  44612. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  44613. }
  44614. }
  44615. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  44616. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  44617. // follow WebGPU backend mapping for texture filtering
  44618. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  44619. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  44620. if ( texture.compareFunction ) {
  44621. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  44622. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  44623. }
  44624. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44625. if ( texture.magFilter === NearestFilter ) return;
  44626. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  44627. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  44628. if ( texture.anisotropy > 1 ) {
  44629. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44630. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  44631. }
  44632. }
  44633. }
  44634. /**
  44635. * Creates a default texture for the given texture that can be used
  44636. * as a placeholder until the actual texture is ready for usage.
  44637. *
  44638. * @param {Texture} texture - The texture to create a default texture for.
  44639. */
  44640. createDefaultTexture( texture ) {
  44641. const { gl, backend, defaultTextures } = this;
  44642. const glTextureType = this.getGLTextureType( texture );
  44643. let textureGPU = defaultTextures[ glTextureType ];
  44644. if ( textureGPU === undefined ) {
  44645. textureGPU = gl.createTexture();
  44646. backend.state.bindTexture( glTextureType, textureGPU );
  44647. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  44648. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  44649. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  44650. defaultTextures[ glTextureType ] = textureGPU;
  44651. }
  44652. backend.set( texture, {
  44653. textureGPU,
  44654. glTextureType
  44655. } );
  44656. }
  44657. /**
  44658. * Defines a texture on the GPU for the given texture object.
  44659. *
  44660. * @param {Texture} texture - The texture.
  44661. * @param {Object} [options={}] - Optional configuration parameter.
  44662. * @return {undefined}
  44663. */
  44664. createTexture( texture, options ) {
  44665. const { gl, backend } = this;
  44666. const { levels, width, height, depth } = options;
  44667. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  44668. const glType = backend.utils.convert( texture.type );
  44669. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  44670. const textureGPU = gl.createTexture();
  44671. const glTextureType = this.getGLTextureType( texture );
  44672. backend.state.bindTexture( glTextureType, textureGPU );
  44673. this.setTextureParameters( glTextureType, texture );
  44674. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  44675. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  44676. } else if ( texture.isData3DTexture ) {
  44677. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  44678. } else if ( ! texture.isVideoTexture ) {
  44679. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  44680. }
  44681. backend.set( texture, {
  44682. textureGPU,
  44683. glTextureType,
  44684. glFormat,
  44685. glType,
  44686. glInternalFormat
  44687. } );
  44688. }
  44689. /**
  44690. * Uploads texture buffer data to the GPU memory.
  44691. *
  44692. * @param {WebGLBuffer} buffer - The buffer data.
  44693. * @param {Texture} texture - The texture,
  44694. */
  44695. copyBufferToTexture( buffer, texture ) {
  44696. const { gl, backend } = this;
  44697. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  44698. const { width, height } = texture.source.data;
  44699. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  44700. backend.state.bindTexture( glTextureType, textureGPU );
  44701. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  44702. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  44703. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  44704. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  44705. backend.state.unbindTexture();
  44706. // debug
  44707. // const framebuffer = gl.createFramebuffer();
  44708. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  44709. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  44710. // const readout = new Float32Array( width * height * 4 );
  44711. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  44712. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  44713. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  44714. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  44715. // log( readout );
  44716. }
  44717. /**
  44718. * Uploads the updated texture data to the GPU.
  44719. *
  44720. * @param {Texture} texture - The texture.
  44721. * @param {Object} [options={}] - Optional configuration parameter.
  44722. */
  44723. updateTexture( texture, options ) {
  44724. const { gl } = this;
  44725. const { width, height } = options;
  44726. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  44727. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  44728. return;
  44729. this.backend.state.bindTexture( glTextureType, textureGPU );
  44730. this.setTextureParameters( glTextureType, texture );
  44731. if ( texture.isCompressedTexture ) {
  44732. const mipmaps = texture.mipmaps;
  44733. const image = options.image;
  44734. for ( let i = 0; i < mipmaps.length; i ++ ) {
  44735. const mipmap = mipmaps[ i ];
  44736. if ( texture.isCompressedArrayTexture ) {
  44737. if ( texture.format !== gl.RGBA ) {
  44738. if ( glFormat !== null ) {
  44739. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  44740. } else {
  44741. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  44742. }
  44743. } else {
  44744. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  44745. }
  44746. } else {
  44747. if ( glFormat !== null ) {
  44748. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  44749. } else {
  44750. warn( 'Unsupported compressed texture format' );
  44751. }
  44752. }
  44753. }
  44754. } else if ( texture.isCubeTexture ) {
  44755. const images = options.images;
  44756. const mipmaps = texture.mipmaps;
  44757. for ( let i = 0; i < 6; i ++ ) {
  44758. const image = getImage( images[ i ] );
  44759. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  44760. for ( let j = 0; j < mipmaps.length; j ++ ) {
  44761. const mipmap = mipmaps[ j ];
  44762. const image = getImage( mipmap.images[ i ] );
  44763. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  44764. }
  44765. }
  44766. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  44767. const image = options.image;
  44768. if ( texture.layerUpdates.size > 0 ) {
  44769. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  44770. for ( const layerIndex of texture.layerUpdates ) {
  44771. const layerData = image.data.subarray(
  44772. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  44773. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  44774. );
  44775. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  44776. }
  44777. texture.clearLayerUpdates();
  44778. } else {
  44779. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  44780. }
  44781. } else if ( texture.isData3DTexture ) {
  44782. const image = options.image;
  44783. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  44784. } else if ( texture.isVideoTexture ) {
  44785. texture.update();
  44786. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  44787. } else {
  44788. const mipmaps = texture.mipmaps;
  44789. if ( mipmaps.length > 0 ) {
  44790. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  44791. const mipmap = mipmaps[ i ];
  44792. const image = getImage( mipmap );
  44793. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  44794. }
  44795. } else {
  44796. const image = getImage( options.image );
  44797. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  44798. }
  44799. }
  44800. }
  44801. /**
  44802. * Generates mipmaps for the given texture.
  44803. *
  44804. * @param {Texture} texture - The texture.
  44805. */
  44806. generateMipmaps( texture ) {
  44807. const { gl, backend } = this;
  44808. const { textureGPU, glTextureType } = backend.get( texture );
  44809. backend.state.bindTexture( glTextureType, textureGPU );
  44810. gl.generateMipmap( glTextureType );
  44811. }
  44812. /**
  44813. * Deallocates the render buffers of the given render target.
  44814. *
  44815. * @param {RenderTarget} renderTarget - The render target.
  44816. */
  44817. deallocateRenderBuffers( renderTarget ) {
  44818. const { gl, backend } = this;
  44819. // remove framebuffer reference
  44820. if ( renderTarget ) {
  44821. const renderContextData = backend.get( renderTarget );
  44822. renderContextData.renderBufferStorageSetup = undefined;
  44823. if ( renderContextData.framebuffers ) {
  44824. for ( const cacheKey in renderContextData.framebuffers ) {
  44825. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  44826. }
  44827. delete renderContextData.framebuffers;
  44828. }
  44829. if ( renderContextData.depthRenderbuffer ) {
  44830. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  44831. delete renderContextData.depthRenderbuffer;
  44832. }
  44833. if ( renderContextData.stencilRenderbuffer ) {
  44834. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  44835. delete renderContextData.stencilRenderbuffer;
  44836. }
  44837. if ( renderContextData.msaaFrameBuffer ) {
  44838. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  44839. delete renderContextData.msaaFrameBuffer;
  44840. }
  44841. if ( renderContextData.msaaRenderbuffers ) {
  44842. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  44843. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  44844. }
  44845. delete renderContextData.msaaRenderbuffers;
  44846. }
  44847. }
  44848. }
  44849. /**
  44850. * Destroys the GPU data for the given texture object.
  44851. *
  44852. * @param {Texture} texture - The texture.
  44853. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  44854. */
  44855. destroyTexture( texture, isDefaultTexture = false ) {
  44856. const { gl, backend } = this;
  44857. const { textureGPU, renderTarget } = backend.get( texture );
  44858. this.deallocateRenderBuffers( renderTarget );
  44859. if ( isDefaultTexture === false ) {
  44860. gl.deleteTexture( textureGPU );
  44861. }
  44862. backend.delete( texture );
  44863. }
  44864. /**
  44865. * Copies data of the given source texture to the given destination texture.
  44866. *
  44867. * @param {Texture} srcTexture - The source texture.
  44868. * @param {Texture} dstTexture - The destination texture.
  44869. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44870. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44871. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44872. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44873. */
  44874. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44875. const { gl, backend } = this;
  44876. const { state } = this.backend;
  44877. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  44878. state.bindTexture( glTextureType, dstTextureGPU );
  44879. // gather the necessary dimensions to copy
  44880. let width, height, depth, minX, minY, minZ;
  44881. let dstX, dstY, dstZ;
  44882. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  44883. if ( srcRegion !== null ) {
  44884. width = srcRegion.max.x - srcRegion.min.x;
  44885. height = srcRegion.max.y - srcRegion.min.y;
  44886. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  44887. minX = srcRegion.min.x;
  44888. minY = srcRegion.min.y;
  44889. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  44890. } else {
  44891. const levelScale = Math.pow( 2, - srcLevel );
  44892. width = Math.floor( image.width * levelScale );
  44893. height = Math.floor( image.height * levelScale );
  44894. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  44895. depth = image.depth;
  44896. } else if ( srcTexture.isData3DTexture ) {
  44897. depth = Math.floor( image.depth * levelScale );
  44898. } else {
  44899. depth = 1;
  44900. }
  44901. minX = 0;
  44902. minY = 0;
  44903. minZ = 0;
  44904. }
  44905. if ( dstPosition !== null ) {
  44906. dstX = dstPosition.x;
  44907. dstY = dstPosition.y;
  44908. dstZ = dstPosition.z;
  44909. } else {
  44910. dstX = 0;
  44911. dstY = 0;
  44912. dstZ = 0;
  44913. }
  44914. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  44915. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  44916. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  44917. // used for copying data from cpu
  44918. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  44919. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  44920. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  44921. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  44922. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  44923. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  44924. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  44925. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  44926. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  44927. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  44928. // set up the src texture
  44929. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture || dstTexture.isArrayTexture;
  44930. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  44931. if ( srcTexture.isDepthTexture ) {
  44932. const srcTextureData = backend.get( srcTexture );
  44933. const dstTextureData = backend.get( dstTexture );
  44934. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  44935. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  44936. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  44937. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  44938. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  44939. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  44940. for ( let i = 0; i < depth; i ++ ) {
  44941. // if the source or destination are a 3d target then a layer needs to be bound
  44942. if ( isSrc3D ) {
  44943. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  44944. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  44945. }
  44946. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  44947. }
  44948. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  44949. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  44950. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || backend.has( srcTexture ) ) {
  44951. // get the appropriate frame buffers
  44952. const srcTextureData = backend.get( srcTexture );
  44953. if ( this._srcFramebuffer === null ) this._srcFramebuffer = gl.createFramebuffer();
  44954. if ( this._dstFramebuffer === null ) this._dstFramebuffer = gl.createFramebuffer();
  44955. // bind the frame buffer targets
  44956. state.bindFramebuffer( gl.READ_FRAMEBUFFER, this._srcFramebuffer );
  44957. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, this._dstFramebuffer );
  44958. for ( let i = 0; i < depth; i ++ ) {
  44959. // assign the correct layers and mip maps to the frame buffers
  44960. if ( isSrc3D ) {
  44961. gl.framebufferTextureLayer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, srcTextureData.textureGPU, srcLevel, minZ + i );
  44962. } else {
  44963. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, srcTextureData.textureGPU, srcLevel );
  44964. }
  44965. if ( isDst3D ) {
  44966. gl.framebufferTextureLayer( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, dstTextureGPU, dstLevel, dstZ + i );
  44967. } else {
  44968. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, dstTextureGPU, dstLevel );
  44969. }
  44970. // copy the data using the fastest function that can achieve the copy
  44971. if ( srcLevel !== 0 ) {
  44972. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST );
  44973. } else if ( isDst3D ) {
  44974. gl.copyTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  44975. } else {
  44976. gl.copyTexSubImage2D( glTextureType, dstLevel, dstX, dstY, minX, minY, width, height );
  44977. }
  44978. }
  44979. // unbind read, draw buffers
  44980. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  44981. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  44982. } else {
  44983. if ( isDst3D ) {
  44984. // copy data into the 3d texture
  44985. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  44986. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  44987. } else if ( dstTexture.isCompressedArrayTexture ) {
  44988. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  44989. } else {
  44990. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  44991. }
  44992. } else {
  44993. // copy data into the 2d texture
  44994. if ( srcTexture.isDataTexture ) {
  44995. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  44996. } else if ( srcTexture.isCompressedTexture ) {
  44997. gl.compressedTexSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  44998. } else {
  44999. gl.texSubImage2D( gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  45000. }
  45001. }
  45002. }
  45003. // reset values
  45004. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  45005. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  45006. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  45007. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  45008. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  45009. // Generate mipmaps only when copying level 0
  45010. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  45011. gl.generateMipmap( glTextureType );
  45012. }
  45013. state.unbindTexture();
  45014. }
  45015. /**
  45016. * Copies the current bound framebuffer to the given texture.
  45017. *
  45018. * @param {Texture} texture - The destination texture.
  45019. * @param {RenderContext} renderContext - The render context.
  45020. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45021. */
  45022. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45023. const { gl } = this;
  45024. const { state } = this.backend;
  45025. const { textureGPU } = this.backend.get( texture );
  45026. const { x, y, z: width, w: height } = rectangle;
  45027. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  45028. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  45029. if ( requireDrawFrameBuffer ) {
  45030. const partial = ( x !== 0 || y !== 0 );
  45031. let mask;
  45032. let attachment;
  45033. if ( texture.isDepthTexture === true ) {
  45034. mask = gl.DEPTH_BUFFER_BIT;
  45035. attachment = gl.DEPTH_ATTACHMENT;
  45036. if ( renderContext.stencil ) {
  45037. mask |= gl.STENCIL_BUFFER_BIT;
  45038. }
  45039. } else {
  45040. mask = gl.COLOR_BUFFER_BIT;
  45041. attachment = gl.COLOR_ATTACHMENT0;
  45042. }
  45043. if ( partial ) {
  45044. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  45045. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  45046. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  45047. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  45048. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  45049. const flippedY = srcHeight - y - height;
  45050. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  45051. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  45052. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  45053. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  45054. state.unbindTexture();
  45055. } else {
  45056. const fb = gl.createFramebuffer();
  45057. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  45058. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  45059. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  45060. gl.deleteFramebuffer( fb );
  45061. }
  45062. } else {
  45063. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  45064. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  45065. state.unbindTexture();
  45066. }
  45067. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  45068. this.backend._setFramebuffer( renderContext );
  45069. }
  45070. /**
  45071. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  45072. *
  45073. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  45074. * @param {RenderContext} renderContext - The render context.
  45075. * @param {number} samples - The MSAA sample count.
  45076. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  45077. */
  45078. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  45079. const { gl } = this;
  45080. const renderTarget = renderContext.renderTarget;
  45081. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  45082. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  45083. if ( depthBuffer && ! stencilBuffer ) {
  45084. let glInternalFormat = gl.DEPTH_COMPONENT24;
  45085. if ( useMultisampledRTT === true ) {
  45086. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  45087. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  45088. } else if ( samples > 0 ) {
  45089. if ( depthTexture && depthTexture.isDepthTexture ) {
  45090. if ( depthTexture.type === gl.FLOAT ) {
  45091. glInternalFormat = gl.DEPTH_COMPONENT32F;
  45092. }
  45093. }
  45094. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  45095. } else {
  45096. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  45097. }
  45098. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  45099. } else if ( depthBuffer && stencilBuffer ) {
  45100. if ( samples > 0 ) {
  45101. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  45102. } else {
  45103. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  45104. }
  45105. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  45106. }
  45107. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  45108. }
  45109. /**
  45110. * Returns texture data as a typed array.
  45111. *
  45112. * @async
  45113. * @param {Texture} texture - The texture to copy.
  45114. * @param {number} x - The x coordinate of the copy origin.
  45115. * @param {number} y - The y coordinate of the copy origin.
  45116. * @param {number} width - The width of the copy.
  45117. * @param {number} height - The height of the copy.
  45118. * @param {number} faceIndex - The face index.
  45119. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45120. */
  45121. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45122. const { backend, gl } = this;
  45123. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  45124. const fb = gl.createFramebuffer();
  45125. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  45126. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  45127. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  45128. const typedArrayType = this._getTypedArrayType( glType );
  45129. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  45130. const elementCount = width * height;
  45131. const byteLength = elementCount * bytesPerTexel;
  45132. const buffer = gl.createBuffer();
  45133. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  45134. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  45135. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  45136. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  45137. await backend.utils._clientWaitAsync();
  45138. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  45139. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  45140. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  45141. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  45142. gl.deleteFramebuffer( fb );
  45143. return dstBuffer;
  45144. }
  45145. /**
  45146. * Returns the corresponding typed array type for the given WebGL data type.
  45147. *
  45148. * @private
  45149. * @param {GLenum} glType - The WebGL data type.
  45150. * @return {TypedArray.constructor} The typed array type.
  45151. */
  45152. _getTypedArrayType( glType ) {
  45153. const { gl } = this;
  45154. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  45155. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  45156. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  45157. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  45158. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  45159. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  45160. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  45161. if ( glType === gl.FLOAT ) return Float32Array;
  45162. throw new Error( `Unsupported WebGL type: ${glType}` );
  45163. }
  45164. /**
  45165. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  45166. *
  45167. * @private
  45168. * @param {GLenum} glType - The WebGL data type.
  45169. * @param {GLenum} glFormat - The WebGL texture format.
  45170. * @return {number} The bytes-per-texel.
  45171. */
  45172. _getBytesPerTexel( glType, glFormat ) {
  45173. const { gl } = this;
  45174. let bytesPerComponent = 0;
  45175. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  45176. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  45177. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  45178. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  45179. glType === gl.UNSIGNED_SHORT ||
  45180. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  45181. if ( glType === gl.UNSIGNED_INT ||
  45182. glType === gl.FLOAT ) bytesPerComponent = 4;
  45183. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  45184. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  45185. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  45186. }
  45187. /**
  45188. * Frees the internal resources.
  45189. */
  45190. dispose() {
  45191. const { gl } = this;
  45192. if ( this._srcFramebuffer !== null ) gl.deleteFramebuffer( this._srcFramebuffer );
  45193. if ( this._dstFramebuffer !== null ) gl.deleteFramebuffer( this._dstFramebuffer );
  45194. }
  45195. }
  45196. function getImage( source ) {
  45197. if ( source.isDataTexture ) {
  45198. return source.image.data;
  45199. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  45200. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  45201. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  45202. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  45203. return source;
  45204. }
  45205. return source.data;
  45206. }
  45207. /**
  45208. * A WebGL 2 backend utility module for managing extensions.
  45209. *
  45210. * @private
  45211. */
  45212. class WebGLExtensions {
  45213. /**
  45214. * Constructs a new utility object.
  45215. *
  45216. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45217. */
  45218. constructor( backend ) {
  45219. /**
  45220. * A reference to the WebGL 2 backend.
  45221. *
  45222. * @type {WebGLBackend}
  45223. */
  45224. this.backend = backend;
  45225. /**
  45226. * A reference to the rendering context.
  45227. *
  45228. * @type {WebGL2RenderingContext}
  45229. */
  45230. this.gl = this.backend.gl;
  45231. /**
  45232. * A list with all the supported WebGL extensions.
  45233. *
  45234. * @type {Array<string>}
  45235. */
  45236. this.availableExtensions = this.gl.getSupportedExtensions();
  45237. /**
  45238. * A dictionary with requested WebGL extensions.
  45239. * The key is the name of the extension, the value
  45240. * the requested extension object.
  45241. *
  45242. * @type {Object<string,Object>}
  45243. */
  45244. this.extensions = {};
  45245. }
  45246. /**
  45247. * Returns the extension object for the given extension name.
  45248. *
  45249. * @param {string} name - The extension name.
  45250. * @return {Object} The extension object.
  45251. */
  45252. get( name ) {
  45253. let extension = this.extensions[ name ];
  45254. if ( extension === undefined ) {
  45255. extension = this.gl.getExtension( name );
  45256. this.extensions[ name ] = extension;
  45257. }
  45258. return extension;
  45259. }
  45260. /**
  45261. * Returns `true` if the requested extension is available.
  45262. *
  45263. * @param {string} name - The extension name.
  45264. * @return {boolean} Whether the given extension is available or not.
  45265. */
  45266. has( name ) {
  45267. return this.availableExtensions.includes( name );
  45268. }
  45269. }
  45270. /**
  45271. * A WebGL 2 backend utility module for managing the device's capabilities.
  45272. *
  45273. * @private
  45274. */
  45275. class WebGLCapabilities {
  45276. /**
  45277. * Constructs a new utility object.
  45278. *
  45279. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45280. */
  45281. constructor( backend ) {
  45282. /**
  45283. * A reference to the WebGL 2 backend.
  45284. *
  45285. * @type {WebGLBackend}
  45286. */
  45287. this.backend = backend;
  45288. /**
  45289. * This value holds the cached max anisotropy value.
  45290. *
  45291. * @type {?number}
  45292. * @default null
  45293. */
  45294. this.maxAnisotropy = null;
  45295. }
  45296. /**
  45297. * Returns the maximum anisotropy texture filtering value. This value
  45298. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  45299. * WebGL extension.
  45300. *
  45301. * @return {number} The maximum anisotropy texture filtering value.
  45302. */
  45303. getMaxAnisotropy() {
  45304. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  45305. const gl = this.backend.gl;
  45306. const extensions = this.backend.extensions;
  45307. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  45308. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  45309. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  45310. } else {
  45311. this.maxAnisotropy = 0;
  45312. }
  45313. return this.maxAnisotropy;
  45314. }
  45315. }
  45316. const GLFeatureName = {
  45317. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  45318. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  45319. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  45320. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  45321. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  45322. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  45323. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  45324. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  45325. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  45326. 'OVR_multiview2': 'OVR_multiview2'
  45327. };
  45328. class WebGLBufferRenderer {
  45329. constructor( backend ) {
  45330. this.gl = backend.gl;
  45331. this.extensions = backend.extensions;
  45332. this.info = backend.renderer.info;
  45333. this.mode = null;
  45334. this.index = 0;
  45335. this.type = null;
  45336. this.object = null;
  45337. }
  45338. render( start, count ) {
  45339. const { gl, mode, object, type, info, index } = this;
  45340. if ( index !== 0 ) {
  45341. gl.drawElements( mode, count, type, start );
  45342. } else {
  45343. gl.drawArrays( mode, start, count );
  45344. }
  45345. info.update( object, count, 1 );
  45346. }
  45347. renderInstances( start, count, primcount ) {
  45348. const { gl, mode, type, index, object, info } = this;
  45349. if ( primcount === 0 ) return;
  45350. if ( index !== 0 ) {
  45351. gl.drawElementsInstanced( mode, count, type, start, primcount );
  45352. } else {
  45353. gl.drawArraysInstanced( mode, start, count, primcount );
  45354. }
  45355. info.update( object, count, primcount );
  45356. }
  45357. renderMultiDraw( starts, counts, drawCount ) {
  45358. const { extensions, mode, object, info } = this;
  45359. if ( drawCount === 0 ) return;
  45360. const extension = extensions.get( 'WEBGL_multi_draw' );
  45361. if ( extension === null ) {
  45362. for ( let i = 0; i < drawCount; i ++ ) {
  45363. this.render( starts[ i ], counts[ i ] );
  45364. }
  45365. } else {
  45366. if ( this.index !== 0 ) {
  45367. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  45368. } else {
  45369. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  45370. }
  45371. let elementCount = 0;
  45372. for ( let i = 0; i < drawCount; i ++ ) {
  45373. elementCount += counts[ i ];
  45374. }
  45375. info.update( object, elementCount, 1 );
  45376. }
  45377. }
  45378. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45379. const { extensions, mode, object, info } = this;
  45380. if ( drawCount === 0 ) return;
  45381. const extension = extensions.get( 'WEBGL_multi_draw' );
  45382. if ( extension === null ) {
  45383. for ( let i = 0; i < drawCount; i ++ ) {
  45384. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  45385. }
  45386. } else {
  45387. if ( this.index !== 0 ) {
  45388. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  45389. } else {
  45390. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  45391. }
  45392. let elementCount = 0;
  45393. for ( let i = 0; i < drawCount; i ++ ) {
  45394. elementCount += counts[ i ] * primcount[ i ];
  45395. }
  45396. info.update( object, elementCount, 1 );
  45397. }
  45398. }
  45399. //
  45400. }
  45401. /**
  45402. * Abstract base class of a timestamp query pool.
  45403. *
  45404. * @abstract
  45405. */
  45406. class TimestampQueryPool {
  45407. /**
  45408. * Creates a new timestamp query pool.
  45409. *
  45410. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  45411. */
  45412. constructor( maxQueries = 256 ) {
  45413. /**
  45414. * Whether to track timestamps or not.
  45415. *
  45416. * @type {boolean}
  45417. * @default true
  45418. */
  45419. this.trackTimestamp = true;
  45420. /**
  45421. * Maximum number of queries this pool can hold.
  45422. *
  45423. * @type {number}
  45424. * @default 256
  45425. */
  45426. this.maxQueries = maxQueries;
  45427. /**
  45428. * How many queries allocated so far.
  45429. *
  45430. * @type {number}
  45431. * @default 0
  45432. */
  45433. this.currentQueryIndex = 0;
  45434. /**
  45435. * Tracks offsets for different contexts.
  45436. *
  45437. * @type {Map<string, number>}
  45438. */
  45439. this.queryOffsets = new Map();
  45440. /**
  45441. * Whether the pool has been disposed or not.
  45442. *
  45443. * @type {boolean}
  45444. * @default false
  45445. */
  45446. this.isDisposed = false;
  45447. /**
  45448. * TODO
  45449. *
  45450. * @type {number}
  45451. * @default 0
  45452. */
  45453. this.lastValue = 0;
  45454. /**
  45455. * TODO
  45456. *
  45457. * @type {boolean}
  45458. * @default false
  45459. */
  45460. this.pendingResolve = false;
  45461. }
  45462. /**
  45463. * Allocate queries for a specific uid.
  45464. *
  45465. * @abstract
  45466. * @param {string} uid - A unique identifier for the render context.
  45467. * @returns {?number}
  45468. */
  45469. allocateQueriesForContext( /* uid */ ) {}
  45470. /**
  45471. * Resolve all timestamps and return data (or process them).
  45472. *
  45473. * @abstract
  45474. * @async
  45475. * @returns {Promise<number>|number} The resolved timestamp value.
  45476. */
  45477. async resolveQueriesAsync() {}
  45478. /**
  45479. * Dispose of the query pool.
  45480. *
  45481. * @abstract
  45482. */
  45483. dispose() {}
  45484. }
  45485. /**
  45486. * Manages a pool of WebGL timestamp queries for performance measurement.
  45487. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  45488. *
  45489. * @augments TimestampQueryPool
  45490. */
  45491. class WebGLTimestampQueryPool extends TimestampQueryPool {
  45492. /**
  45493. * Creates a new WebGL timestamp query pool.
  45494. *
  45495. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  45496. * @param {string} type - The type identifier for this query pool.
  45497. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  45498. */
  45499. constructor( gl, type, maxQueries = 2048 ) {
  45500. super( maxQueries );
  45501. this.gl = gl;
  45502. this.type = type;
  45503. // Check for timer query extensions
  45504. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  45505. gl.getExtension( 'EXT_disjoint_timer_query' );
  45506. if ( ! this.ext ) {
  45507. warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  45508. this.trackTimestamp = false;
  45509. return;
  45510. }
  45511. // Create query objects
  45512. this.queries = [];
  45513. for ( let i = 0; i < this.maxQueries; i ++ ) {
  45514. this.queries.push( gl.createQuery() );
  45515. }
  45516. this.activeQuery = null;
  45517. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  45518. }
  45519. /**
  45520. * Allocates a pair of queries for a given render context.
  45521. *
  45522. * @param {string} uid - A unique identifier for the render context.
  45523. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  45524. */
  45525. allocateQueriesForContext( uid ) {
  45526. if ( ! this.trackTimestamp ) return null;
  45527. // Check if we have enough space for a new query pair
  45528. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  45529. 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() } ).` );
  45530. return null;
  45531. }
  45532. const baseOffset = this.currentQueryIndex;
  45533. this.currentQueryIndex += 2;
  45534. // Initialize query states
  45535. this.queryStates.set( baseOffset, 'inactive' );
  45536. this.queryOffsets.set( uid, baseOffset );
  45537. return baseOffset;
  45538. }
  45539. /**
  45540. * Begins a timestamp query for the specified render context.
  45541. *
  45542. * @param {string} uid - A unique identifier for the render context.
  45543. */
  45544. beginQuery( uid ) {
  45545. if ( ! this.trackTimestamp || this.isDisposed ) {
  45546. return;
  45547. }
  45548. const baseOffset = this.queryOffsets.get( uid );
  45549. if ( baseOffset == null ) {
  45550. return;
  45551. }
  45552. // Don't start a new query if there's an active one
  45553. if ( this.activeQuery !== null ) {
  45554. return;
  45555. }
  45556. const query = this.queries[ baseOffset ];
  45557. if ( ! query ) {
  45558. return;
  45559. }
  45560. try {
  45561. // Only begin if query is inactive
  45562. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  45563. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  45564. this.activeQuery = baseOffset;
  45565. this.queryStates.set( baseOffset, 'started' );
  45566. }
  45567. } catch ( error ) {
  45568. error( 'Error in beginQuery:', error );
  45569. this.activeQuery = null;
  45570. this.queryStates.set( baseOffset, 'inactive' );
  45571. }
  45572. }
  45573. /**
  45574. * Ends the active timestamp query for the specified render context.
  45575. *
  45576. * @param {string} uid - A unique identifier for the render context.
  45577. */
  45578. endQuery( uid ) {
  45579. if ( ! this.trackTimestamp || this.isDisposed ) {
  45580. return;
  45581. }
  45582. const baseOffset = this.queryOffsets.get( uid );
  45583. if ( baseOffset == null ) {
  45584. return;
  45585. }
  45586. // Only end if this is the active query
  45587. if ( this.activeQuery !== baseOffset ) {
  45588. return;
  45589. }
  45590. try {
  45591. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  45592. this.queryStates.set( baseOffset, 'ended' );
  45593. this.activeQuery = null;
  45594. } catch ( error ) {
  45595. error( 'Error in endQuery:', error );
  45596. // Reset state on error
  45597. this.queryStates.set( baseOffset, 'inactive' );
  45598. this.activeQuery = null;
  45599. }
  45600. }
  45601. /**
  45602. * Asynchronously resolves all completed queries and returns the total duration.
  45603. *
  45604. * @async
  45605. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  45606. */
  45607. async resolveQueriesAsync() {
  45608. if ( ! this.trackTimestamp || this.pendingResolve ) {
  45609. return this.lastValue;
  45610. }
  45611. this.pendingResolve = true;
  45612. try {
  45613. // Wait for all ended queries to complete
  45614. const resolvePromises = [];
  45615. for ( const [ baseOffset, state ] of this.queryStates ) {
  45616. if ( state === 'ended' ) {
  45617. const query = this.queries[ baseOffset ];
  45618. resolvePromises.push( this.resolveQuery( query ) );
  45619. }
  45620. }
  45621. if ( resolvePromises.length === 0 ) {
  45622. return this.lastValue;
  45623. }
  45624. const results = await Promise.all( resolvePromises );
  45625. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  45626. // Store the last valid result
  45627. this.lastValue = totalDuration;
  45628. // Reset states
  45629. this.currentQueryIndex = 0;
  45630. this.queryOffsets.clear();
  45631. this.queryStates.clear();
  45632. this.activeQuery = null;
  45633. return totalDuration;
  45634. } catch ( error ) {
  45635. error( 'Error resolving queries:', error );
  45636. return this.lastValue;
  45637. } finally {
  45638. this.pendingResolve = false;
  45639. }
  45640. }
  45641. /**
  45642. * Resolves a single query, checking for completion and disjoint operation.
  45643. *
  45644. * @async
  45645. * @param {WebGLQuery} query - The query object to resolve.
  45646. * @returns {Promise<number>} The elapsed time in milliseconds.
  45647. */
  45648. async resolveQuery( query ) {
  45649. return new Promise( ( resolve ) => {
  45650. if ( this.isDisposed ) {
  45651. resolve( this.lastValue );
  45652. return;
  45653. }
  45654. let timeoutId;
  45655. let isResolved = false;
  45656. const cleanup = () => {
  45657. if ( timeoutId ) {
  45658. clearTimeout( timeoutId );
  45659. timeoutId = null;
  45660. }
  45661. };
  45662. const finalizeResolution = ( value ) => {
  45663. if ( ! isResolved ) {
  45664. isResolved = true;
  45665. cleanup();
  45666. resolve( value );
  45667. }
  45668. };
  45669. const checkQuery = () => {
  45670. if ( this.isDisposed ) {
  45671. finalizeResolution( this.lastValue );
  45672. return;
  45673. }
  45674. try {
  45675. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  45676. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  45677. if ( disjoint ) {
  45678. finalizeResolution( this.lastValue );
  45679. return;
  45680. }
  45681. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  45682. if ( ! available ) {
  45683. timeoutId = setTimeout( checkQuery, 1 );
  45684. return;
  45685. }
  45686. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  45687. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  45688. } catch ( error ) {
  45689. error( 'Error checking query:', error );
  45690. resolve( this.lastValue );
  45691. }
  45692. };
  45693. checkQuery();
  45694. } );
  45695. }
  45696. /**
  45697. * Releases all resources held by this query pool.
  45698. * This includes deleting all query objects and clearing internal state.
  45699. */
  45700. dispose() {
  45701. if ( this.isDisposed ) {
  45702. return;
  45703. }
  45704. this.isDisposed = true;
  45705. if ( ! this.trackTimestamp ) return;
  45706. for ( const query of this.queries ) {
  45707. this.gl.deleteQuery( query );
  45708. }
  45709. this.queries = [];
  45710. this.queryStates.clear();
  45711. this.queryOffsets.clear();
  45712. this.lastValue = 0;
  45713. this.activeQuery = null;
  45714. }
  45715. }
  45716. /**
  45717. * A backend implementation targeting WebGL 2.
  45718. *
  45719. * @private
  45720. * @augments Backend
  45721. */
  45722. class WebGLBackend extends Backend {
  45723. /**
  45724. * WebGLBackend options.
  45725. *
  45726. * @typedef {Object} WebGLBackend~Options
  45727. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  45728. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  45729. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  45730. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  45731. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  45732. * @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.
  45733. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  45734. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  45735. */
  45736. /**
  45737. * Constructs a new WebGPU backend.
  45738. *
  45739. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  45740. */
  45741. constructor( parameters = {} ) {
  45742. super( parameters );
  45743. /**
  45744. * This flag can be used for type testing.
  45745. *
  45746. * @type {boolean}
  45747. * @readonly
  45748. * @default true
  45749. */
  45750. this.isWebGLBackend = true;
  45751. /**
  45752. * A reference to a backend module holding shader attribute-related
  45753. * utility functions.
  45754. *
  45755. * @type {?WebGLAttributeUtils}
  45756. * @default null
  45757. */
  45758. this.attributeUtils = null;
  45759. /**
  45760. * A reference to a backend module holding extension-related
  45761. * utility functions.
  45762. *
  45763. * @type {?WebGLExtensions}
  45764. * @default null
  45765. */
  45766. this.extensions = null;
  45767. /**
  45768. * A reference to a backend module holding capability-related
  45769. * utility functions.
  45770. *
  45771. * @type {?WebGLCapabilities}
  45772. * @default null
  45773. */
  45774. this.capabilities = null;
  45775. /**
  45776. * A reference to a backend module holding texture-related
  45777. * utility functions.
  45778. *
  45779. * @type {?WebGLTextureUtils}
  45780. * @default null
  45781. */
  45782. this.textureUtils = null;
  45783. /**
  45784. * A reference to a backend module holding renderer-related
  45785. * utility functions.
  45786. *
  45787. * @type {?WebGLBufferRenderer}
  45788. * @default null
  45789. */
  45790. this.bufferRenderer = null;
  45791. /**
  45792. * A reference to the rendering context.
  45793. *
  45794. * @type {?WebGL2RenderingContext}
  45795. * @default null
  45796. */
  45797. this.gl = null;
  45798. /**
  45799. * A reference to a backend module holding state-related
  45800. * utility functions.
  45801. *
  45802. * @type {?WebGLState}
  45803. * @default null
  45804. */
  45805. this.state = null;
  45806. /**
  45807. * A reference to a backend module holding common
  45808. * utility functions.
  45809. *
  45810. * @type {?WebGLUtils}
  45811. * @default null
  45812. */
  45813. this.utils = null;
  45814. /**
  45815. * Dictionary for caching VAOs.
  45816. *
  45817. * @type {Object<string,WebGLVertexArrayObject>}
  45818. */
  45819. this.vaoCache = {};
  45820. /**
  45821. * Dictionary for caching transform feedback objects.
  45822. *
  45823. * @type {Object<string,WebGLTransformFeedback>}
  45824. */
  45825. this.transformFeedbackCache = {};
  45826. /**
  45827. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  45828. * Only relevant when using compute shaders.
  45829. *
  45830. * @type {boolean}
  45831. * @default false
  45832. */
  45833. this.discard = false;
  45834. /**
  45835. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  45836. * device does not support the extension.
  45837. *
  45838. * @type {?EXTDisjointTimerQueryWebGL2}
  45839. * @default null
  45840. */
  45841. this.disjoint = null;
  45842. /**
  45843. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  45844. * device does not support the extension.
  45845. *
  45846. * @type {?KHRParallelShaderCompile}
  45847. * @default null
  45848. */
  45849. this.parallel = null;
  45850. /**
  45851. * A reference to the current render context.
  45852. *
  45853. * @private
  45854. * @type {RenderContext}
  45855. * @default null
  45856. */
  45857. this._currentContext = null;
  45858. /**
  45859. * A unique collection of bindings.
  45860. *
  45861. * @private
  45862. * @type {WeakSet<Array<BindGroup>>}
  45863. */
  45864. this._knownBindings = new WeakSet();
  45865. /**
  45866. * Whether the device supports framebuffers invalidation or not.
  45867. *
  45868. * @private
  45869. * @type {boolean}
  45870. */
  45871. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  45872. /**
  45873. * The target framebuffer when rendering with
  45874. * the WebXR device API.
  45875. *
  45876. * @private
  45877. * @type {?WebGLFramebuffer}
  45878. * @default null
  45879. */
  45880. this._xrFramebuffer = null;
  45881. }
  45882. /**
  45883. * Initializes the backend so it is ready for usage.
  45884. *
  45885. * @param {Renderer} renderer - The renderer.
  45886. */
  45887. init( renderer ) {
  45888. super.init( renderer );
  45889. //
  45890. const parameters = this.parameters;
  45891. const contextAttributes = {
  45892. antialias: renderer.samples > 0,
  45893. alpha: true, // always true for performance reasons
  45894. depth: renderer.depth,
  45895. stencil: renderer.stencil
  45896. };
  45897. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  45898. function onContextLost( event ) {
  45899. event.preventDefault();
  45900. const contextLossInfo = {
  45901. api: 'WebGL',
  45902. message: event.statusMessage || 'Unknown reason',
  45903. reason: null,
  45904. originalEvent: event
  45905. };
  45906. renderer.onDeviceLost( contextLossInfo );
  45907. }
  45908. this._onContextLost = onContextLost;
  45909. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  45910. this.gl = glContext;
  45911. this.extensions = new WebGLExtensions( this );
  45912. this.capabilities = new WebGLCapabilities( this );
  45913. this.attributeUtils = new WebGLAttributeUtils( this );
  45914. this.textureUtils = new WebGLTextureUtils( this );
  45915. this.bufferRenderer = new WebGLBufferRenderer( this );
  45916. this.state = new WebGLState( this );
  45917. this.utils = new WebGLUtils( this );
  45918. this.extensions.get( 'EXT_color_buffer_float' );
  45919. this.extensions.get( 'WEBGL_clip_cull_distance' );
  45920. this.extensions.get( 'OES_texture_float_linear' );
  45921. this.extensions.get( 'EXT_color_buffer_half_float' );
  45922. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  45923. this.extensions.get( 'WEBGL_render_shared_exponent' );
  45924. this.extensions.get( 'WEBGL_multi_draw' );
  45925. this.extensions.get( 'OVR_multiview2' );
  45926. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  45927. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  45928. }
  45929. /**
  45930. * The coordinate system of the backend.
  45931. *
  45932. * @type {number}
  45933. * @readonly
  45934. */
  45935. get coordinateSystem() {
  45936. return WebGLCoordinateSystem;
  45937. }
  45938. /**
  45939. * This method performs a readback operation by moving buffer data from
  45940. * a storage buffer attribute from the GPU to the CPU.
  45941. *
  45942. * @async
  45943. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45944. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45945. */
  45946. async getArrayBufferAsync( attribute ) {
  45947. return await this.attributeUtils.getArrayBufferAsync( attribute );
  45948. }
  45949. /**
  45950. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  45951. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  45952. *
  45953. * @async
  45954. * @return {Promise} A Promise that resolves when synchronization has been finished.
  45955. */
  45956. async waitForGPU() {
  45957. await this.utils._clientWaitAsync();
  45958. }
  45959. /**
  45960. * Ensures the backend is XR compatible.
  45961. *
  45962. * @async
  45963. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  45964. */
  45965. async makeXRCompatible() {
  45966. const attributes = this.gl.getContextAttributes();
  45967. if ( attributes.xrCompatible !== true ) {
  45968. await this.gl.makeXRCompatible();
  45969. }
  45970. }
  45971. /**
  45972. * Sets the XR rendering destination.
  45973. *
  45974. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  45975. */
  45976. setXRTarget( xrFramebuffer ) {
  45977. this._xrFramebuffer = xrFramebuffer;
  45978. }
  45979. /**
  45980. * Configures the given XR render target with external textures.
  45981. *
  45982. * This method is only relevant when using the WebXR Layers API.
  45983. *
  45984. * @param {XRRenderTarget} renderTarget - The XR render target.
  45985. * @param {WebGLTexture} colorTexture - A native color texture.
  45986. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  45987. */
  45988. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  45989. const gl = this.gl;
  45990. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  45991. if ( depthTexture !== null ) {
  45992. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  45993. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  45994. // The multisample_render_to_texture extension doesn't work properly if there
  45995. // are midframe flushes and an external depth texture.
  45996. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  45997. warn( 'WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  45998. }
  45999. renderTarget._autoAllocateDepthBuffer = false;
  46000. }
  46001. }
  46002. /**
  46003. * Inits a time stamp query for the given render context.
  46004. *
  46005. * @param {string} type - The type of the timestamp query.
  46006. * @param {string} uid - A unique identifier for the timestamp query.
  46007. */
  46008. initTimestampQuery( type, uid ) {
  46009. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  46010. if ( ! this.timestampQueryPool[ type ] ) {
  46011. // TODO: Variable maxQueries?
  46012. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  46013. }
  46014. const timestampQueryPool = this.timestampQueryPool[ type ];
  46015. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  46016. if ( baseOffset !== null ) {
  46017. timestampQueryPool.beginQuery( uid );
  46018. }
  46019. }
  46020. // timestamp utils
  46021. /**
  46022. * Prepares the timestamp buffer.
  46023. *
  46024. * @param {string} type - The type of the timestamp query.
  46025. * @param {string} uid - A unique identifier for the timestamp query.
  46026. */
  46027. prepareTimestampBuffer( type, uid ) {
  46028. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  46029. const timestampQueryPool = this.timestampQueryPool[ type ];
  46030. timestampQueryPool.endQuery( uid );
  46031. }
  46032. /**
  46033. * Returns the backend's rendering context.
  46034. *
  46035. * @return {WebGL2RenderingContext} The rendering context.
  46036. */
  46037. getContext() {
  46038. return this.gl;
  46039. }
  46040. /**
  46041. * This method is executed at the beginning of a render call and prepares
  46042. * the WebGL state for upcoming render calls
  46043. *
  46044. * @param {RenderContext} renderContext - The render context.
  46045. */
  46046. beginRender( renderContext ) {
  46047. const { state } = this;
  46048. const renderContextData = this.get( renderContext );
  46049. //
  46050. renderContextData.frameCalls = this.renderer.info.render.frameCalls;
  46051. //
  46052. if ( renderContext.viewport ) {
  46053. this.updateViewport( renderContext );
  46054. } else {
  46055. const { width, height } = this.getDrawingBufferSize();
  46056. state.viewport( 0, 0, width, height );
  46057. }
  46058. if ( renderContext.scissor ) {
  46059. const { x, y, width, height } = renderContext.scissorValue;
  46060. state.scissor( x, renderContext.height - height - y, width, height );
  46061. }
  46062. //
  46063. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  46064. renderContextData.previousContext = this._currentContext;
  46065. this._currentContext = renderContext;
  46066. this._setFramebuffer( renderContext );
  46067. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  46068. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46069. if ( occlusionQueryCount > 0 ) {
  46070. // Get a reference to the array of objects with queries. The renderContextData property
  46071. // can be changed by another render pass before the async reading of all previous queries complete
  46072. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  46073. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  46074. renderContextData.lastOcclusionObject = null;
  46075. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  46076. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  46077. renderContextData.occlusionQueryIndex = 0;
  46078. }
  46079. }
  46080. /**
  46081. * This method is executed at the end of a render call and finalizes work
  46082. * after draw calls.
  46083. *
  46084. * @param {RenderContext} renderContext - The render context.
  46085. */
  46086. finishRender( renderContext ) {
  46087. const { gl, state } = this;
  46088. const renderContextData = this.get( renderContext );
  46089. const previousContext = renderContextData.previousContext;
  46090. state.resetVertexState();
  46091. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46092. if ( occlusionQueryCount > 0 ) {
  46093. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  46094. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  46095. }
  46096. this.resolveOccludedAsync( renderContext );
  46097. }
  46098. const textures = renderContext.textures;
  46099. if ( textures !== null ) {
  46100. for ( let i = 0; i < textures.length; i ++ ) {
  46101. const texture = textures[ i ];
  46102. if ( texture.generateMipmaps ) {
  46103. this.generateMipmaps( texture );
  46104. }
  46105. }
  46106. }
  46107. this._currentContext = previousContext;
  46108. this._resolveRenderTarget( renderContext );
  46109. if ( previousContext !== null ) {
  46110. this._setFramebuffer( previousContext );
  46111. if ( previousContext.viewport ) {
  46112. this.updateViewport( previousContext );
  46113. } else {
  46114. const { width, height } = this.getDrawingBufferSize();
  46115. state.viewport( 0, 0, width, height );
  46116. }
  46117. }
  46118. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  46119. }
  46120. /**
  46121. * This method processes the result of occlusion queries and writes it
  46122. * into render context data.
  46123. *
  46124. * @async
  46125. * @param {RenderContext} renderContext - The render context.
  46126. */
  46127. resolveOccludedAsync( renderContext ) {
  46128. const renderContextData = this.get( renderContext );
  46129. // handle occlusion query results
  46130. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  46131. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  46132. const occluded = new WeakSet();
  46133. const { gl } = this;
  46134. renderContextData.currentOcclusionQueryObjects = null;
  46135. renderContextData.currentOcclusionQueries = null;
  46136. const check = () => {
  46137. let completed = 0;
  46138. // check all queries and requeue as appropriate
  46139. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  46140. const query = currentOcclusionQueries[ i ];
  46141. if ( query === null ) continue;
  46142. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  46143. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  46144. currentOcclusionQueries[ i ] = null;
  46145. gl.deleteQuery( query );
  46146. completed ++;
  46147. }
  46148. }
  46149. if ( completed < currentOcclusionQueries.length ) {
  46150. requestAnimationFrame( check );
  46151. } else {
  46152. renderContextData.occluded = occluded;
  46153. }
  46154. };
  46155. check();
  46156. }
  46157. }
  46158. /**
  46159. * Returns `true` if the given 3D object is fully occluded by other
  46160. * 3D objects in the scene.
  46161. *
  46162. * @param {RenderContext} renderContext - The render context.
  46163. * @param {Object3D} object - The 3D object to test.
  46164. * @return {boolean} Whether the 3D object is fully occluded or not.
  46165. */
  46166. isOccluded( renderContext, object ) {
  46167. const renderContextData = this.get( renderContext );
  46168. return renderContextData.occluded && renderContextData.occluded.has( object );
  46169. }
  46170. /**
  46171. * Updates the viewport with the values from the given render context.
  46172. *
  46173. * @param {RenderContext} renderContext - The render context.
  46174. */
  46175. updateViewport( renderContext ) {
  46176. const { state } = this;
  46177. const { x, y, width, height } = renderContext.viewportValue;
  46178. state.viewport( x, renderContext.height - height - y, width, height );
  46179. }
  46180. /**
  46181. * Defines the scissor test.
  46182. *
  46183. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46184. */
  46185. setScissorTest( boolean ) {
  46186. const state = this.state;
  46187. state.setScissorTest( boolean );
  46188. }
  46189. /**
  46190. * Returns the clear color and alpha into a single
  46191. * color object.
  46192. *
  46193. * @return {Color4} The clear color.
  46194. */
  46195. getClearColor() {
  46196. const clearColor = super.getClearColor();
  46197. // Since the canvas is always created with alpha: true,
  46198. // WebGL must always premultiply the clear color.
  46199. clearColor.r *= clearColor.a;
  46200. clearColor.g *= clearColor.a;
  46201. clearColor.b *= clearColor.a;
  46202. return clearColor;
  46203. }
  46204. /**
  46205. * Performs a clear operation.
  46206. *
  46207. * @param {boolean} color - Whether the color buffer should be cleared or not.
  46208. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  46209. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  46210. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  46211. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  46212. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  46213. * or not. Only relevant for explicit clears.
  46214. */
  46215. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  46216. const { gl, renderer } = this;
  46217. if ( descriptor === null ) {
  46218. const clearColor = this.getClearColor();
  46219. descriptor = {
  46220. textures: null,
  46221. clearColorValue: clearColor
  46222. };
  46223. }
  46224. //
  46225. let clear = 0;
  46226. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  46227. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  46228. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  46229. if ( clear !== 0 ) {
  46230. let clearColor;
  46231. if ( descriptor.clearColorValue ) {
  46232. clearColor = descriptor.clearColorValue;
  46233. } else {
  46234. clearColor = this.getClearColor();
  46235. }
  46236. const clearDepth = renderer.getClearDepth();
  46237. const clearStencil = renderer.getClearStencil();
  46238. if ( depth ) this.state.setDepthMask( true );
  46239. if ( descriptor.textures === null ) {
  46240. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  46241. gl.clear( clear );
  46242. } else {
  46243. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  46244. if ( color ) {
  46245. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  46246. if ( i === 0 ) {
  46247. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  46248. } else {
  46249. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  46250. }
  46251. }
  46252. }
  46253. if ( depth && stencil ) {
  46254. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  46255. } else if ( depth ) {
  46256. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  46257. } else if ( stencil ) {
  46258. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  46259. }
  46260. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  46261. }
  46262. }
  46263. }
  46264. /**
  46265. * This method is executed at the beginning of a compute call and
  46266. * prepares the state for upcoming compute tasks.
  46267. *
  46268. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46269. */
  46270. beginCompute( computeGroup ) {
  46271. const { state, gl } = this;
  46272. const computeGroupData = this.get( computeGroup );
  46273. //
  46274. computeGroupData.frameCalls = this.renderer.info.compute.frameCalls;
  46275. //
  46276. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  46277. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  46278. }
  46279. /**
  46280. * Executes a compute command for the given compute node.
  46281. *
  46282. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  46283. * @param {Node} computeNode - The compute node.
  46284. * @param {Array<BindGroup>} bindings - The bindings.
  46285. * @param {ComputePipeline} pipeline - The compute pipeline.
  46286. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  46287. */
  46288. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  46289. const { state, gl } = this;
  46290. if ( this.discard === false ) {
  46291. // required here to handle async behaviour of render.compute()
  46292. gl.enable( gl.RASTERIZER_DISCARD );
  46293. this.discard = true;
  46294. }
  46295. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  46296. const vaoKey = this._getVaoKey( attributes );
  46297. const vaoGPU = this.vaoCache[ vaoKey ];
  46298. if ( vaoGPU === undefined ) {
  46299. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  46300. } else {
  46301. state.setVertexState( vaoGPU );
  46302. }
  46303. state.useProgram( programGPU );
  46304. this._bindUniforms( bindings );
  46305. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  46306. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  46307. gl.beginTransformFeedback( gl.POINTS );
  46308. count = ( count !== null ) ? count : computeNode.count;
  46309. if ( Array.isArray( count ) ) {
  46310. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  46311. count = count[ 0 ];
  46312. }
  46313. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  46314. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  46315. } else {
  46316. gl.drawArrays( gl.POINTS, 0, count );
  46317. }
  46318. gl.endTransformFeedback();
  46319. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  46320. // switch active buffers
  46321. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46322. const dualAttributeData = transformBuffers[ i ];
  46323. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  46324. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  46325. }
  46326. dualAttributeData.switchBuffers();
  46327. }
  46328. }
  46329. /**
  46330. * This method is executed at the end of a compute call and
  46331. * finalizes work after compute tasks.
  46332. *
  46333. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46334. */
  46335. finishCompute( computeGroup ) {
  46336. const gl = this.gl;
  46337. this.discard = false;
  46338. gl.disable( gl.RASTERIZER_DISCARD );
  46339. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  46340. if ( this._currentContext ) {
  46341. this._setFramebuffer( this._currentContext );
  46342. }
  46343. }
  46344. /**
  46345. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  46346. *
  46347. * @param {RenderContext} renderContext - The render context.
  46348. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  46349. *
  46350. * @private
  46351. */
  46352. _isRenderCameraDepthArray( renderContext ) {
  46353. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  46354. }
  46355. /**
  46356. * Executes a draw command for the given render object.
  46357. *
  46358. * @param {RenderObject} renderObject - The render object to draw.
  46359. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  46360. */
  46361. draw( renderObject/*, info*/ ) {
  46362. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  46363. const { programGPU } = this.get( pipeline );
  46364. const { gl, state } = this;
  46365. const contextData = this.get( context );
  46366. const drawParams = renderObject.getDrawParameters();
  46367. if ( drawParams === null ) return;
  46368. //
  46369. this._bindUniforms( renderObject.getBindings() );
  46370. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  46371. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  46372. state.useProgram( programGPU );
  46373. // vertex state
  46374. const attributes = renderObject.getAttributes();
  46375. const attributesData = this.get( attributes );
  46376. let vaoGPU = attributesData.vaoGPU;
  46377. if ( vaoGPU === undefined ) {
  46378. const vaoKey = this._getVaoKey( attributes );
  46379. vaoGPU = this.vaoCache[ vaoKey ];
  46380. if ( vaoGPU === undefined ) {
  46381. vaoGPU = this._createVao( attributes );
  46382. this.vaoCache[ vaoKey ] = vaoGPU;
  46383. attributesData.vaoGPU = vaoGPU;
  46384. }
  46385. }
  46386. const index = renderObject.getIndex();
  46387. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  46388. state.setVertexState( vaoGPU, indexGPU );
  46389. //
  46390. const lastObject = contextData.lastOcclusionObject;
  46391. if ( lastObject !== object && lastObject !== undefined ) {
  46392. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  46393. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  46394. contextData.occlusionQueryIndex ++;
  46395. }
  46396. if ( object.occlusionTest === true ) {
  46397. const query = gl.createQuery();
  46398. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  46399. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  46400. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  46401. }
  46402. contextData.lastOcclusionObject = object;
  46403. }
  46404. //
  46405. const renderer = this.bufferRenderer;
  46406. if ( object.isPoints ) renderer.mode = gl.POINTS;
  46407. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  46408. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  46409. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  46410. else {
  46411. if ( material.wireframe === true ) {
  46412. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  46413. renderer.mode = gl.LINES;
  46414. } else {
  46415. renderer.mode = gl.TRIANGLES;
  46416. }
  46417. }
  46418. //
  46419. const { vertexCount, instanceCount } = drawParams;
  46420. let { firstVertex } = drawParams;
  46421. renderer.object = object;
  46422. if ( index !== null ) {
  46423. firstVertex *= index.array.BYTES_PER_ELEMENT;
  46424. const indexData = this.get( index );
  46425. renderer.index = index.count;
  46426. renderer.type = indexData.type;
  46427. } else {
  46428. renderer.index = 0;
  46429. }
  46430. const draw = () => {
  46431. if ( object.isBatchedMesh ) {
  46432. if ( object._multiDrawInstances !== null ) {
  46433. // @deprecated, r174
  46434. warnOnce( 'WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  46435. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  46436. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  46437. warnOnce( 'WebGLRenderer: WEBGL_multi_draw not supported.' );
  46438. } else {
  46439. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  46440. }
  46441. } else if ( instanceCount > 1 ) {
  46442. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  46443. } else {
  46444. renderer.render( firstVertex, vertexCount );
  46445. }
  46446. };
  46447. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  46448. const cameraData = this.get( renderObject.camera );
  46449. const cameras = renderObject.camera.cameras;
  46450. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  46451. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  46452. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  46453. const indexesGPU = [];
  46454. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46455. const bufferGPU = gl.createBuffer();
  46456. data[ 0 ] = i;
  46457. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46458. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  46459. indexesGPU.push( bufferGPU );
  46460. }
  46461. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  46462. }
  46463. const cameraIndexData = this.get( cameraIndex );
  46464. const pixelRatio = this.renderer.getPixelRatio();
  46465. const renderTarget = this._currentContext.renderTarget;
  46466. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  46467. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  46468. if ( isRenderCameraDepthArray ) {
  46469. // Clear the depth texture
  46470. const textureData = this.get( renderTarget.depthTexture );
  46471. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  46472. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  46473. const { stencilBuffer } = renderTarget;
  46474. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46475. this.renderer._activeCubeFace = i;
  46476. this._currentContext.activeCubeFace = i;
  46477. this._setFramebuffer( this._currentContext );
  46478. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  46479. }
  46480. this.renderer._activeCubeFace = prevActiveCubeFace;
  46481. this._currentContext.activeCubeFace = prevActiveCubeFace;
  46482. }
  46483. }
  46484. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46485. const subCamera = cameras[ i ];
  46486. if ( object.layers.test( subCamera.layers ) ) {
  46487. if ( isRenderCameraDepthArray ) {
  46488. // Update the active layer
  46489. this.renderer._activeCubeFace = i;
  46490. this._currentContext.activeCubeFace = i;
  46491. this._setFramebuffer( this._currentContext );
  46492. }
  46493. const vp = subCamera.viewport;
  46494. if ( vp !== undefined ) {
  46495. const x = vp.x * pixelRatio;
  46496. const y = vp.y * pixelRatio;
  46497. const width = vp.width * pixelRatio;
  46498. const height = vp.height * pixelRatio;
  46499. state.viewport(
  46500. Math.floor( x ),
  46501. Math.floor( renderObject.context.height - height - y ),
  46502. Math.floor( width ),
  46503. Math.floor( height )
  46504. );
  46505. }
  46506. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  46507. draw();
  46508. }
  46509. this._currentContext.activeCubeFace = prevActiveCubeFace;
  46510. this.renderer._activeCubeFace = prevActiveCubeFace;
  46511. }
  46512. } else {
  46513. draw();
  46514. }
  46515. }
  46516. /**
  46517. * Explain why always null is returned.
  46518. *
  46519. * @param {RenderObject} renderObject - The render object.
  46520. * @return {boolean} Whether the render pipeline requires an update or not.
  46521. */
  46522. needsRenderUpdate( /*renderObject*/ ) {
  46523. return false;
  46524. }
  46525. /**
  46526. * Explain why no cache key is computed.
  46527. *
  46528. * @param {RenderObject} renderObject - The render object.
  46529. * @return {string} The cache key.
  46530. */
  46531. getRenderCacheKey( /*renderObject*/ ) {
  46532. return '';
  46533. }
  46534. // textures
  46535. /**
  46536. * Creates a default texture for the given texture that can be used
  46537. * as a placeholder until the actual texture is ready for usage.
  46538. *
  46539. * @param {Texture} texture - The texture to create a default texture for.
  46540. */
  46541. createDefaultTexture( texture ) {
  46542. this.textureUtils.createDefaultTexture( texture );
  46543. }
  46544. /**
  46545. * Defines a texture on the GPU for the given texture object.
  46546. *
  46547. * @param {Texture} texture - The texture.
  46548. * @param {Object} [options={}] - Optional configuration parameter.
  46549. */
  46550. createTexture( texture, options ) {
  46551. this.textureUtils.createTexture( texture, options );
  46552. }
  46553. /**
  46554. * Uploads the updated texture data to the GPU.
  46555. *
  46556. * @param {Texture} texture - The texture.
  46557. * @param {Object} [options={}] - Optional configuration parameter.
  46558. */
  46559. updateTexture( texture, options ) {
  46560. this.textureUtils.updateTexture( texture, options );
  46561. }
  46562. /**
  46563. * Generates mipmaps for the given texture.
  46564. *
  46565. * @param {Texture} texture - The texture.
  46566. */
  46567. generateMipmaps( texture ) {
  46568. this.textureUtils.generateMipmaps( texture );
  46569. }
  46570. /**
  46571. * Destroys the GPU data for the given texture object.
  46572. *
  46573. * @param {Texture} texture - The texture.
  46574. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  46575. */
  46576. destroyTexture( texture, isDefaultTexture = false ) {
  46577. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  46578. }
  46579. /**
  46580. * Returns texture data as a typed array.
  46581. *
  46582. * @async
  46583. * @param {Texture} texture - The texture to copy.
  46584. * @param {number} x - The x coordinate of the copy origin.
  46585. * @param {number} y - The y coordinate of the copy origin.
  46586. * @param {number} width - The width of the copy.
  46587. * @param {number} height - The height of the copy.
  46588. * @param {number} faceIndex - The face index.
  46589. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46590. */
  46591. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46592. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  46593. }
  46594. /**
  46595. * This method does nothing since WebGL 2 has no concept of samplers.
  46596. *
  46597. * @param {Texture} texture - The texture to create the sampler for.
  46598. */
  46599. createSampler( /*texture*/ ) {
  46600. //warn( 'Abstract class.' );
  46601. }
  46602. /**
  46603. * This method does nothing since WebGL 2 has no concept of samplers.
  46604. *
  46605. * @param {Texture} texture - The texture to destroy the sampler for.
  46606. */
  46607. destroySampler( /*texture*/ ) {}
  46608. // node builder
  46609. /**
  46610. * Returns a node builder for the given render object.
  46611. *
  46612. * @param {RenderObject} object - The render object.
  46613. * @param {Renderer} renderer - The renderer.
  46614. * @return {GLSLNodeBuilder} The node builder.
  46615. */
  46616. createNodeBuilder( object, renderer ) {
  46617. return new GLSLNodeBuilder( object, renderer );
  46618. }
  46619. // program
  46620. /**
  46621. * Creates a shader program from the given programmable stage.
  46622. *
  46623. * @param {ProgrammableStage} program - The programmable stage.
  46624. */
  46625. createProgram( program ) {
  46626. const gl = this.gl;
  46627. const { stage, code } = program;
  46628. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  46629. gl.shaderSource( shader, code );
  46630. gl.compileShader( shader );
  46631. this.set( program, {
  46632. shaderGPU: shader
  46633. } );
  46634. }
  46635. /**
  46636. * Destroys the shader program of the given programmable stage.
  46637. *
  46638. * @param {ProgrammableStage} program - The programmable stage.
  46639. */
  46640. destroyProgram( program ) {
  46641. this.delete( program );
  46642. }
  46643. /**
  46644. * Creates a render pipeline for the given render object.
  46645. *
  46646. * @param {RenderObject} renderObject - The render object.
  46647. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46648. */
  46649. createRenderPipeline( renderObject, promises ) {
  46650. const gl = this.gl;
  46651. const pipeline = renderObject.pipeline;
  46652. // Program
  46653. const { fragmentProgram, vertexProgram } = pipeline;
  46654. const programGPU = gl.createProgram();
  46655. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  46656. const vertexShader = this.get( vertexProgram ).shaderGPU;
  46657. gl.attachShader( programGPU, fragmentShader );
  46658. gl.attachShader( programGPU, vertexShader );
  46659. gl.linkProgram( programGPU );
  46660. this.set( pipeline, {
  46661. programGPU,
  46662. fragmentShader,
  46663. vertexShader
  46664. } );
  46665. if ( promises !== null && this.parallel ) {
  46666. const p = new Promise( ( resolve /*, reject*/ ) => {
  46667. const parallel = this.parallel;
  46668. const checkStatus = () => {
  46669. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  46670. this._completeCompile( renderObject, pipeline );
  46671. resolve();
  46672. } else {
  46673. requestAnimationFrame( checkStatus );
  46674. }
  46675. };
  46676. checkStatus();
  46677. } );
  46678. promises.push( p );
  46679. return;
  46680. }
  46681. this._completeCompile( renderObject, pipeline );
  46682. }
  46683. /**
  46684. * Formats the source code of error messages.
  46685. *
  46686. * @private
  46687. * @param {string} string - The code.
  46688. * @param {number} errorLine - The error line.
  46689. * @return {string} The formatted code.
  46690. */
  46691. _handleSource( string, errorLine ) {
  46692. const lines = string.split( '\n' );
  46693. const lines2 = [];
  46694. const from = Math.max( errorLine - 6, 0 );
  46695. const to = Math.min( errorLine + 6, lines.length );
  46696. for ( let i = from; i < to; i ++ ) {
  46697. const line = i + 1;
  46698. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46699. }
  46700. return lines2.join( '\n' );
  46701. }
  46702. /**
  46703. * Gets the shader compilation errors from the info log.
  46704. *
  46705. * @private
  46706. * @param {WebGL2RenderingContext} gl - The rendering context.
  46707. * @param {WebGLShader} shader - The WebGL shader object.
  46708. * @param {string} type - The shader type.
  46709. * @return {string} The shader errors.
  46710. */
  46711. _getShaderErrors( gl, shader, type ) {
  46712. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46713. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46714. const errors = shaderInfoLog.trim();
  46715. if ( status && errors === '' ) return '';
  46716. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46717. if ( errorMatches ) {
  46718. const errorLine = parseInt( errorMatches[ 1 ] );
  46719. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  46720. } else {
  46721. return errors;
  46722. }
  46723. }
  46724. /**
  46725. * Logs shader compilation errors.
  46726. *
  46727. * @private
  46728. * @param {WebGLProgram} programGPU - The WebGL program.
  46729. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  46730. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  46731. */
  46732. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  46733. if ( this.renderer.debug.checkShaderErrors ) {
  46734. const gl = this.gl;
  46735. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  46736. const programLog = programInfoLog.trim();
  46737. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46738. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  46739. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  46740. } else {
  46741. // default error reporting
  46742. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  46743. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  46744. error(
  46745. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46746. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  46747. 'Program Info Log: ' + programLog + '\n' +
  46748. vertexErrors + '\n' +
  46749. fragmentErrors
  46750. );
  46751. }
  46752. } else if ( programLog !== '' ) {
  46753. warn( 'WebGLProgram: Program Info Log:', programLog );
  46754. }
  46755. }
  46756. }
  46757. /**
  46758. * Completes the shader program setup for the given render object.
  46759. *
  46760. * @private
  46761. * @param {RenderObject} renderObject - The render object.
  46762. * @param {RenderPipeline} pipeline - The render pipeline.
  46763. */
  46764. _completeCompile( renderObject, pipeline ) {
  46765. const { state, gl } = this;
  46766. const pipelineData = this.get( pipeline );
  46767. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  46768. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46769. this._logProgramError( programGPU, fragmentShader, vertexShader );
  46770. }
  46771. state.useProgram( programGPU );
  46772. // Bindings
  46773. const bindings = renderObject.getBindings();
  46774. this._setupBindings( bindings, programGPU );
  46775. //
  46776. this.set( pipeline, {
  46777. programGPU
  46778. } );
  46779. }
  46780. /**
  46781. * Creates a compute pipeline for the given compute node.
  46782. *
  46783. * @param {ComputePipeline} computePipeline - The compute pipeline.
  46784. * @param {Array<BindGroup>} bindings - The bindings.
  46785. */
  46786. createComputePipeline( computePipeline, bindings ) {
  46787. const { state, gl } = this;
  46788. // Program
  46789. const fragmentProgram = {
  46790. stage: 'fragment',
  46791. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  46792. };
  46793. this.createProgram( fragmentProgram );
  46794. const { computeProgram } = computePipeline;
  46795. const programGPU = gl.createProgram();
  46796. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  46797. const vertexShader = this.get( computeProgram ).shaderGPU;
  46798. const transforms = computeProgram.transforms;
  46799. const transformVaryingNames = [];
  46800. const transformAttributeNodes = [];
  46801. for ( let i = 0; i < transforms.length; i ++ ) {
  46802. const transform = transforms[ i ];
  46803. transformVaryingNames.push( transform.varyingName );
  46804. transformAttributeNodes.push( transform.attributeNode );
  46805. }
  46806. gl.attachShader( programGPU, fragmentShader );
  46807. gl.attachShader( programGPU, vertexShader );
  46808. gl.transformFeedbackVaryings(
  46809. programGPU,
  46810. transformVaryingNames,
  46811. gl.SEPARATE_ATTRIBS
  46812. );
  46813. gl.linkProgram( programGPU );
  46814. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46815. this._logProgramError( programGPU, fragmentShader, vertexShader );
  46816. }
  46817. state.useProgram( programGPU );
  46818. // Bindings
  46819. this._setupBindings( bindings, programGPU );
  46820. const attributeNodes = computeProgram.attributes;
  46821. const attributes = [];
  46822. const transformBuffers = [];
  46823. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  46824. const attribute = attributeNodes[ i ].node.attribute;
  46825. attributes.push( attribute );
  46826. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46827. }
  46828. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  46829. const attribute = transformAttributeNodes[ i ].attribute;
  46830. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46831. const attributeData = this.get( attribute );
  46832. transformBuffers.push( attributeData );
  46833. }
  46834. //
  46835. this.set( computePipeline, {
  46836. programGPU,
  46837. transformBuffers,
  46838. attributes
  46839. } );
  46840. }
  46841. /**
  46842. * Creates bindings from the given bind group definition.
  46843. *
  46844. * @param {BindGroup} bindGroup - The bind group.
  46845. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46846. * @param {number} cacheIndex - The cache index.
  46847. * @param {number} version - The version.
  46848. */
  46849. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  46850. if ( this._knownBindings.has( bindings ) === false ) {
  46851. this._knownBindings.add( bindings );
  46852. let uniformBuffers = 0;
  46853. let textures = 0;
  46854. for ( const bindGroup of bindings ) {
  46855. this.set( bindGroup, {
  46856. textures: textures,
  46857. uniformBuffers: uniformBuffers
  46858. } );
  46859. for ( const binding of bindGroup.bindings ) {
  46860. if ( binding.isUniformBuffer ) uniformBuffers ++;
  46861. if ( binding.isSampledTexture ) textures ++;
  46862. }
  46863. }
  46864. }
  46865. this.updateBindings( bindGroup, bindings );
  46866. }
  46867. /**
  46868. * Updates the given bind group definition.
  46869. *
  46870. * @param {BindGroup} bindGroup - The bind group.
  46871. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46872. * @param {number} cacheIndex - The cache index.
  46873. * @param {number} version - The version.
  46874. */
  46875. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  46876. const { gl } = this;
  46877. const bindGroupData = this.get( bindGroup );
  46878. let i = bindGroupData.uniformBuffers;
  46879. let t = bindGroupData.textures;
  46880. for ( const binding of bindGroup.bindings ) {
  46881. const map = this.get( binding );
  46882. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46883. const data = binding.buffer;
  46884. let { bufferGPU } = this.get( data );
  46885. if ( bufferGPU === undefined ) {
  46886. // create
  46887. bufferGPU = gl.createBuffer();
  46888. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46889. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  46890. this.set( data, { bufferGPU } );
  46891. } else {
  46892. // update
  46893. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46894. gl.bufferSubData( gl.UNIFORM_BUFFER, 0, data );
  46895. }
  46896. map.index = i ++;
  46897. map.bufferGPU = bufferGPU;
  46898. this.set( binding, map );
  46899. } else if ( binding.isSampledTexture ) {
  46900. const { textureGPU, glTextureType } = this.get( binding.texture );
  46901. map.index = t ++;
  46902. map.textureGPU = textureGPU;
  46903. map.glTextureType = glTextureType;
  46904. this.set( binding, map );
  46905. }
  46906. }
  46907. }
  46908. /**
  46909. * Updates a buffer binding.
  46910. *
  46911. * @param {Buffer} binding - The buffer binding to update.
  46912. */
  46913. updateBinding( binding ) {
  46914. const gl = this.gl;
  46915. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46916. const bindingData = this.get( binding );
  46917. const bufferGPU = bindingData.bufferGPU;
  46918. const data = binding.buffer;
  46919. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46920. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  46921. }
  46922. }
  46923. // attributes
  46924. /**
  46925. * Creates the GPU buffer of an indexed shader attribute.
  46926. *
  46927. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  46928. */
  46929. createIndexAttribute( attribute ) {
  46930. const gl = this.gl;
  46931. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  46932. }
  46933. /**
  46934. * Creates the GPU buffer of a shader attribute.
  46935. *
  46936. * @param {BufferAttribute} attribute - The buffer attribute.
  46937. */
  46938. createAttribute( attribute ) {
  46939. if ( this.has( attribute ) ) return;
  46940. const gl = this.gl;
  46941. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46942. }
  46943. /**
  46944. * Creates the GPU buffer of a storage attribute.
  46945. *
  46946. * @param {BufferAttribute} attribute - The buffer attribute.
  46947. */
  46948. createStorageAttribute( attribute ) {
  46949. if ( this.has( attribute ) ) return;
  46950. const gl = this.gl;
  46951. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46952. }
  46953. /**
  46954. * Updates the GPU buffer of a shader attribute.
  46955. *
  46956. * @param {BufferAttribute} attribute - The buffer attribute to update.
  46957. */
  46958. updateAttribute( attribute ) {
  46959. this.attributeUtils.updateAttribute( attribute );
  46960. }
  46961. /**
  46962. * Destroys the GPU buffer of a shader attribute.
  46963. *
  46964. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  46965. */
  46966. destroyAttribute( attribute ) {
  46967. this.attributeUtils.destroyAttribute( attribute );
  46968. }
  46969. /**
  46970. * Checks if the given feature is supported by the backend.
  46971. *
  46972. * @param {string} name - The feature's name.
  46973. * @return {boolean} Whether the feature is supported or not.
  46974. */
  46975. hasFeature( name ) {
  46976. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  46977. const extensions = this.extensions;
  46978. for ( let i = 0; i < keysMatching.length; i ++ ) {
  46979. if ( extensions.has( keysMatching[ i ] ) ) return true;
  46980. }
  46981. return false;
  46982. }
  46983. /**
  46984. * Returns the maximum anisotropy texture filtering value.
  46985. *
  46986. * @return {number} The maximum anisotropy texture filtering value.
  46987. */
  46988. getMaxAnisotropy() {
  46989. return this.capabilities.getMaxAnisotropy();
  46990. }
  46991. /**
  46992. * Copies data of the given source texture to the given destination texture.
  46993. *
  46994. * @param {Texture} srcTexture - The source texture.
  46995. * @param {Texture} dstTexture - The destination texture.
  46996. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  46997. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  46998. * @param {number} [srcLevel=0] - The source mip level to copy from.
  46999. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  47000. */
  47001. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  47002. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  47003. }
  47004. /**
  47005. * Copies the current bound framebuffer to the given texture.
  47006. *
  47007. * @param {Texture} texture - The destination texture.
  47008. * @param {RenderContext} renderContext - The render context.
  47009. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47010. */
  47011. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47012. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  47013. }
  47014. /**
  47015. * Configures the active framebuffer from the given render context.
  47016. *
  47017. * @private
  47018. * @param {RenderContext} descriptor - The render context.
  47019. */
  47020. _setFramebuffer( descriptor ) {
  47021. const { gl, state } = this;
  47022. let currentFrameBuffer = null;
  47023. if ( descriptor.textures !== null ) {
  47024. const renderTarget = descriptor.renderTarget;
  47025. const renderTargetContextData = this.get( renderTarget );
  47026. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  47027. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  47028. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  47029. const isRenderTargetArray = renderTarget.depth > 1;
  47030. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  47031. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  47032. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  47033. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  47034. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  47035. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  47036. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  47037. const cacheKey = getCacheKey( descriptor );
  47038. let fb;
  47039. if ( isCube ) {
  47040. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  47041. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  47042. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  47043. fb = this._xrFramebuffer;
  47044. } else {
  47045. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  47046. fb = renderTargetContextData.framebuffers[ cacheKey ];
  47047. }
  47048. if ( fb === undefined ) {
  47049. fb = gl.createFramebuffer();
  47050. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  47051. const textures = descriptor.textures;
  47052. const depthInvalidationArray = [];
  47053. if ( isCube ) {
  47054. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  47055. const { textureGPU } = this.get( textures[ 0 ] );
  47056. const cubeFace = this.renderer._activeCubeFace;
  47057. const mipLevel = this.renderer._activeMipmapLevel;
  47058. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  47059. } else {
  47060. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  47061. for ( let i = 0; i < textures.length; i ++ ) {
  47062. const texture = textures[ i ];
  47063. const textureData = this.get( texture );
  47064. textureData.renderTarget = descriptor.renderTarget;
  47065. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  47066. const attachment = gl.COLOR_ATTACHMENT0 + i;
  47067. if ( renderTarget.multiview ) {
  47068. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  47069. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  47070. const layer = this.renderer._activeCubeFace;
  47071. const mipLevel = this.renderer._activeMipmapLevel;
  47072. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  47073. } else {
  47074. if ( useMultisampledRTT ) {
  47075. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  47076. } else {
  47077. const mipLevel = this.renderer._activeMipmapLevel;
  47078. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  47079. }
  47080. }
  47081. }
  47082. }
  47083. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  47084. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  47085. const renderbuffer = gl.createRenderbuffer();
  47086. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  47087. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  47088. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  47089. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47090. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  47091. } else {
  47092. if ( descriptor.depthTexture !== null ) {
  47093. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  47094. const textureData = this.get( descriptor.depthTexture );
  47095. textureData.renderTarget = descriptor.renderTarget;
  47096. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  47097. if ( renderTarget.multiview ) {
  47098. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  47099. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  47100. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  47101. } else {
  47102. if ( descriptor.depthTexture.isArrayTexture ) {
  47103. const layer = this.renderer._activeCubeFace;
  47104. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  47105. } else {
  47106. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  47107. }
  47108. }
  47109. }
  47110. }
  47111. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  47112. } else {
  47113. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  47114. if ( isRenderCameraDepthArray ) {
  47115. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  47116. const layer = this.renderer._activeCubeFace;
  47117. const depthData = this.get( descriptor.depthTexture );
  47118. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  47119. gl.framebufferTextureLayer(
  47120. gl.FRAMEBUFFER,
  47121. depthStyle,
  47122. depthData.textureGPU,
  47123. 0,
  47124. layer
  47125. );
  47126. }
  47127. // rebind external XR textures
  47128. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  47129. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  47130. // rebind color
  47131. const textureData = this.get( descriptor.textures[ 0 ] );
  47132. if ( renderTarget.multiview ) {
  47133. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  47134. } else if ( useMultisampledRTT ) {
  47135. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  47136. } else {
  47137. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  47138. }
  47139. // rebind depth
  47140. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  47141. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  47142. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  47143. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  47144. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  47145. } else {
  47146. const textureData = this.get( descriptor.depthTexture );
  47147. if ( renderTarget.multiview ) {
  47148. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  47149. } else if ( useMultisampledRTT ) {
  47150. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  47151. } else {
  47152. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  47153. }
  47154. }
  47155. }
  47156. }
  47157. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  47158. if ( msaaFb === undefined ) {
  47159. const invalidationArray = [];
  47160. msaaFb = gl.createFramebuffer();
  47161. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  47162. const msaaRenderbuffers = [];
  47163. const textures = descriptor.textures;
  47164. for ( let i = 0; i < textures.length; i ++ ) {
  47165. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  47166. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47167. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  47168. const texture = descriptor.textures[ i ];
  47169. const textureData = this.get( texture );
  47170. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  47171. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47172. }
  47173. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  47174. renderTargetContextData.msaaFrameBuffer = msaaFb;
  47175. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  47176. if ( depthBuffer && depthRenderbuffer === undefined ) {
  47177. depthRenderbuffer = gl.createRenderbuffer();
  47178. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  47179. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  47180. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  47181. invalidationArray.push( depthStyle );
  47182. }
  47183. renderTargetContextData.invalidationArray = invalidationArray;
  47184. }
  47185. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47186. } else {
  47187. currentFrameBuffer = fb;
  47188. }
  47189. state.drawBuffers( descriptor, fb );
  47190. }
  47191. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  47192. }
  47193. /**
  47194. * Computes the VAO key for the given index and attributes.
  47195. *
  47196. * @private
  47197. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  47198. * @return {string} The VAO key.
  47199. */
  47200. _getVaoKey( attributes ) {
  47201. let key = '';
  47202. for ( let i = 0; i < attributes.length; i ++ ) {
  47203. const attributeData = this.get( attributes[ i ] );
  47204. key += ':' + attributeData.id;
  47205. }
  47206. return key;
  47207. }
  47208. /**
  47209. * Creates a VAO from the index and attributes.
  47210. *
  47211. * @private
  47212. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  47213. * @return {Object} The VAO data.
  47214. */
  47215. _createVao( attributes ) {
  47216. const { gl } = this;
  47217. const vaoGPU = gl.createVertexArray();
  47218. gl.bindVertexArray( vaoGPU );
  47219. for ( let i = 0; i < attributes.length; i ++ ) {
  47220. const attribute = attributes[ i ];
  47221. const attributeData = this.get( attribute );
  47222. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  47223. gl.enableVertexAttribArray( i );
  47224. let stride, offset;
  47225. if ( attribute.isInterleavedBufferAttribute === true ) {
  47226. stride = attribute.data.stride * attributeData.bytesPerElement;
  47227. offset = attribute.offset * attributeData.bytesPerElement;
  47228. } else {
  47229. stride = 0;
  47230. offset = 0;
  47231. }
  47232. if ( attributeData.isInteger ) {
  47233. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  47234. } else {
  47235. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  47236. }
  47237. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  47238. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  47239. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  47240. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  47241. }
  47242. }
  47243. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  47244. return vaoGPU;
  47245. }
  47246. /**
  47247. * Creates a transform feedback from the given transform buffers.
  47248. *
  47249. * @private
  47250. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  47251. * @return {WebGLTransformFeedback} The transform feedback.
  47252. */
  47253. _getTransformFeedback( transformBuffers ) {
  47254. let key = '';
  47255. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47256. key += ':' + transformBuffers[ i ].id;
  47257. }
  47258. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  47259. if ( transformFeedbackGPU !== undefined ) {
  47260. return transformFeedbackGPU;
  47261. }
  47262. const { gl } = this;
  47263. transformFeedbackGPU = gl.createTransformFeedback();
  47264. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  47265. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47266. const attributeData = transformBuffers[ i ];
  47267. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  47268. }
  47269. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  47270. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  47271. return transformFeedbackGPU;
  47272. }
  47273. /**
  47274. * Setups the given bindings.
  47275. *
  47276. * @private
  47277. * @param {Array<BindGroup>} bindings - The bindings.
  47278. * @param {WebGLProgram} programGPU - The WebGL program.
  47279. */
  47280. _setupBindings( bindings, programGPU ) {
  47281. const gl = this.gl;
  47282. for ( const bindGroup of bindings ) {
  47283. for ( const binding of bindGroup.bindings ) {
  47284. const bindingData = this.get( binding );
  47285. const index = bindingData.index;
  47286. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47287. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  47288. gl.uniformBlockBinding( programGPU, location, index );
  47289. } else if ( binding.isSampledTexture ) {
  47290. const location = gl.getUniformLocation( programGPU, binding.name );
  47291. gl.uniform1i( location, index );
  47292. }
  47293. }
  47294. }
  47295. }
  47296. /**
  47297. * Binds the given uniforms.
  47298. *
  47299. * @private
  47300. * @param {Array<BindGroup>} bindings - The bindings.
  47301. */
  47302. _bindUniforms( bindings ) {
  47303. const { gl, state } = this;
  47304. for ( const bindGroup of bindings ) {
  47305. for ( const binding of bindGroup.bindings ) {
  47306. const bindingData = this.get( binding );
  47307. const index = bindingData.index;
  47308. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47309. // TODO USE bindBufferRange to group multiple uniform buffers
  47310. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  47311. } else if ( binding.isSampledTexture ) {
  47312. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  47313. }
  47314. }
  47315. }
  47316. }
  47317. /**
  47318. * The method ensures multisampled render targets are resolved.
  47319. *
  47320. * @private
  47321. * @param {RenderContext} renderContext - The render context.
  47322. */
  47323. _resolveRenderTarget( renderContext ) {
  47324. const { gl, state } = this;
  47325. const renderTarget = renderContext.renderTarget;
  47326. if ( renderContext.textures !== null && renderTarget ) {
  47327. const renderTargetContextData = this.get( renderTarget );
  47328. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  47329. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47330. let mask = gl.COLOR_BUFFER_BIT;
  47331. if ( renderTarget.resolveDepthBuffer ) {
  47332. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  47333. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  47334. }
  47335. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47336. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  47337. const textures = renderContext.textures;
  47338. const isMRT = textures.length > 1;
  47339. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  47340. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47341. if ( isMRT ) {
  47342. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  47343. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  47344. for ( let i = 0; i < textures.length; i ++ ) {
  47345. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  47346. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  47347. }
  47348. }
  47349. for ( let i = 0; i < textures.length; i ++ ) {
  47350. if ( isMRT ) {
  47351. // configure attachment for resolve
  47352. const { textureGPU } = this.get( textures[ i ] );
  47353. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47354. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  47355. }
  47356. if ( renderContext.scissor ) {
  47357. const { x, y, width, height } = renderContext.scissorValue;
  47358. const viewY = renderContext.height - height - y;
  47359. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  47360. } else {
  47361. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  47362. }
  47363. }
  47364. if ( isMRT ) {
  47365. // restore attachments
  47366. for ( let i = 0; i < textures.length; i ++ ) {
  47367. const { textureGPU } = this.get( textures[ i ] );
  47368. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47369. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  47370. }
  47371. }
  47372. if ( this._supportsInvalidateFramebuffer === true ) {
  47373. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  47374. }
  47375. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  47376. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47377. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47378. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  47379. }
  47380. }
  47381. }
  47382. /**
  47383. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  47384. * should be used when MSAA is enabled.
  47385. *
  47386. * @private
  47387. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  47388. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  47389. */
  47390. _useMultisampledExtension( renderTarget ) {
  47391. if ( renderTarget.multiview === true ) {
  47392. return true;
  47393. }
  47394. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  47395. }
  47396. /**
  47397. * Frees internal resources.
  47398. */
  47399. dispose() {
  47400. if ( this.textureUtils !== null ) this.textureUtils.dispose();
  47401. const extension = this.extensions.get( 'WEBGL_lose_context' );
  47402. if ( extension ) extension.loseContext();
  47403. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  47404. }
  47405. }
  47406. const GPUPrimitiveTopology = {
  47407. PointList: 'point-list',
  47408. LineList: 'line-list',
  47409. LineStrip: 'line-strip',
  47410. TriangleList: 'triangle-list',
  47411. TriangleStrip: 'triangle-strip',
  47412. };
  47413. const GPUCompareFunction = {
  47414. Never: 'never',
  47415. Less: 'less',
  47416. Equal: 'equal',
  47417. LessEqual: 'less-equal',
  47418. Greater: 'greater',
  47419. NotEqual: 'not-equal',
  47420. GreaterEqual: 'greater-equal',
  47421. Always: 'always'
  47422. };
  47423. const GPUStoreOp = {
  47424. Store: 'store'};
  47425. const GPULoadOp = {
  47426. Load: 'load',
  47427. Clear: 'clear'
  47428. };
  47429. const GPUFrontFace = {
  47430. CCW: 'ccw',
  47431. CW: 'cw'
  47432. };
  47433. const GPUCullMode = {
  47434. None: 'none',
  47435. Back: 'back'
  47436. };
  47437. const GPUIndexFormat = {
  47438. Uint16: 'uint16',
  47439. Uint32: 'uint32'
  47440. };
  47441. const GPUTextureFormat = {
  47442. // 8-bit formats
  47443. R8Unorm: 'r8unorm',
  47444. R8Snorm: 'r8snorm',
  47445. R8Uint: 'r8uint',
  47446. R8Sint: 'r8sint',
  47447. // 16-bit formats
  47448. R16Uint: 'r16uint',
  47449. R16Sint: 'r16sint',
  47450. R16Float: 'r16float',
  47451. RG8Unorm: 'rg8unorm',
  47452. RG8Snorm: 'rg8snorm',
  47453. RG8Uint: 'rg8uint',
  47454. RG8Sint: 'rg8sint',
  47455. // 32-bit formats
  47456. R32Uint: 'r32uint',
  47457. R32Sint: 'r32sint',
  47458. R32Float: 'r32float',
  47459. RG16Uint: 'rg16uint',
  47460. RG16Sint: 'rg16sint',
  47461. RG16Float: 'rg16float',
  47462. RGBA8Unorm: 'rgba8unorm',
  47463. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  47464. RGBA8Snorm: 'rgba8snorm',
  47465. RGBA8Uint: 'rgba8uint',
  47466. RGBA8Sint: 'rgba8sint',
  47467. BGRA8Unorm: 'bgra8unorm',
  47468. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  47469. // Packed 32-bit formats
  47470. RGB9E5UFloat: 'rgb9e5ufloat',
  47471. RGB10A2Unorm: 'rgb10a2unorm',
  47472. RG11B10UFloat: 'rg11b10ufloat',
  47473. // 64-bit formats
  47474. RG32Uint: 'rg32uint',
  47475. RG32Sint: 'rg32sint',
  47476. RG32Float: 'rg32float',
  47477. RGBA16Uint: 'rgba16uint',
  47478. RGBA16Sint: 'rgba16sint',
  47479. RGBA16Float: 'rgba16float',
  47480. // 128-bit formats
  47481. RGBA32Uint: 'rgba32uint',
  47482. RGBA32Sint: 'rgba32sint',
  47483. RGBA32Float: 'rgba32float',
  47484. Depth16Unorm: 'depth16unorm',
  47485. Depth24Plus: 'depth24plus',
  47486. Depth24PlusStencil8: 'depth24plus-stencil8',
  47487. Depth32Float: 'depth32float',
  47488. // 'depth32float-stencil8' extension
  47489. Depth32FloatStencil8: 'depth32float-stencil8',
  47490. // BC compressed formats usable if 'texture-compression-bc' is both
  47491. // supported by the device/user agent and enabled in requestDevice.
  47492. BC1RGBAUnorm: 'bc1-rgba-unorm',
  47493. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  47494. BC2RGBAUnorm: 'bc2-rgba-unorm',
  47495. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  47496. BC3RGBAUnorm: 'bc3-rgba-unorm',
  47497. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  47498. BC4RUnorm: 'bc4-r-unorm',
  47499. BC4RSnorm: 'bc4-r-snorm',
  47500. BC5RGUnorm: 'bc5-rg-unorm',
  47501. BC5RGSnorm: 'bc5-rg-snorm',
  47502. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  47503. BC6HRGBFloat: 'bc6h-rgb-float',
  47504. BC7RGBAUnorm: 'bc7-rgba-unorm',
  47505. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  47506. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  47507. // supported by the device/user agent and enabled in requestDevice.
  47508. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  47509. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  47510. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  47511. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  47512. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  47513. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  47514. EACR11Unorm: 'eac-r11unorm',
  47515. EACR11Snorm: 'eac-r11snorm',
  47516. EACRG11Unorm: 'eac-rg11unorm',
  47517. EACRG11Snorm: 'eac-rg11snorm',
  47518. // ASTC compressed formats usable if 'texture-compression-astc' is both
  47519. // supported by the device/user agent and enabled in requestDevice.
  47520. ASTC4x4Unorm: 'astc-4x4-unorm',
  47521. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  47522. ASTC5x4Unorm: 'astc-5x4-unorm',
  47523. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  47524. ASTC5x5Unorm: 'astc-5x5-unorm',
  47525. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  47526. ASTC6x5Unorm: 'astc-6x5-unorm',
  47527. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  47528. ASTC6x6Unorm: 'astc-6x6-unorm',
  47529. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  47530. ASTC8x5Unorm: 'astc-8x5-unorm',
  47531. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  47532. ASTC8x6Unorm: 'astc-8x6-unorm',
  47533. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  47534. ASTC8x8Unorm: 'astc-8x8-unorm',
  47535. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  47536. ASTC10x5Unorm: 'astc-10x5-unorm',
  47537. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  47538. ASTC10x6Unorm: 'astc-10x6-unorm',
  47539. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  47540. ASTC10x8Unorm: 'astc-10x8-unorm',
  47541. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  47542. ASTC10x10Unorm: 'astc-10x10-unorm',
  47543. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  47544. ASTC12x10Unorm: 'astc-12x10-unorm',
  47545. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  47546. ASTC12x12Unorm: 'astc-12x12-unorm',
  47547. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  47548. };
  47549. const GPUAddressMode = {
  47550. ClampToEdge: 'clamp-to-edge',
  47551. Repeat: 'repeat',
  47552. MirrorRepeat: 'mirror-repeat'
  47553. };
  47554. const GPUFilterMode = {
  47555. Linear: 'linear',
  47556. Nearest: 'nearest'
  47557. };
  47558. const GPUBlendFactor = {
  47559. Zero: 'zero',
  47560. One: 'one',
  47561. Src: 'src',
  47562. OneMinusSrc: 'one-minus-src',
  47563. SrcAlpha: 'src-alpha',
  47564. OneMinusSrcAlpha: 'one-minus-src-alpha',
  47565. Dst: 'dst',
  47566. OneMinusDst: 'one-minus-dst',
  47567. DstAlpha: 'dst-alpha',
  47568. OneMinusDstAlpha: 'one-minus-dst-alpha',
  47569. SrcAlphaSaturated: 'src-alpha-saturated',
  47570. Constant: 'constant',
  47571. OneMinusConstant: 'one-minus-constant'
  47572. };
  47573. const GPUBlendOperation = {
  47574. Add: 'add',
  47575. Subtract: 'subtract',
  47576. ReverseSubtract: 'reverse-subtract',
  47577. Min: 'min',
  47578. Max: 'max'
  47579. };
  47580. const GPUColorWriteFlags = {
  47581. None: 0,
  47582. All: 0xF
  47583. };
  47584. const GPUStencilOperation = {
  47585. Keep: 'keep',
  47586. Zero: 'zero',
  47587. Replace: 'replace',
  47588. Invert: 'invert',
  47589. IncrementClamp: 'increment-clamp',
  47590. DecrementClamp: 'decrement-clamp',
  47591. IncrementWrap: 'increment-wrap',
  47592. DecrementWrap: 'decrement-wrap'
  47593. };
  47594. const GPUBufferBindingType = {
  47595. Storage: 'storage',
  47596. ReadOnlyStorage: 'read-only-storage'
  47597. };
  47598. const GPUStorageTextureAccess = {
  47599. WriteOnly: 'write-only',
  47600. ReadOnly: 'read-only',
  47601. ReadWrite: 'read-write',
  47602. };
  47603. const GPUSamplerBindingType = {
  47604. NonFiltering: 'non-filtering',
  47605. Comparison: 'comparison'
  47606. };
  47607. const GPUTextureSampleType = {
  47608. Float: 'float',
  47609. UnfilterableFloat: 'unfilterable-float',
  47610. Depth: 'depth',
  47611. SInt: 'sint',
  47612. UInt: 'uint'
  47613. };
  47614. const GPUTextureDimension = {
  47615. TwoD: '2d',
  47616. ThreeD: '3d'
  47617. };
  47618. const GPUTextureViewDimension = {
  47619. TwoD: '2d',
  47620. TwoDArray: '2d-array',
  47621. Cube: 'cube',
  47622. ThreeD: '3d'
  47623. };
  47624. const GPUTextureAspect = {
  47625. All: 'all'};
  47626. const GPUInputStepMode = {
  47627. Vertex: 'vertex',
  47628. Instance: 'instance'
  47629. };
  47630. const GPUFeatureName = {
  47631. CoreFeaturesAndLimits: 'core-features-and-limits',
  47632. DepthClipControl: 'depth-clip-control',
  47633. Depth32FloatStencil8: 'depth32float-stencil8',
  47634. TextureCompressionBC: 'texture-compression-bc',
  47635. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  47636. TextureCompressionETC2: 'texture-compression-etc2',
  47637. TextureCompressionASTC: 'texture-compression-astc',
  47638. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  47639. TimestampQuery: 'timestamp-query',
  47640. IndirectFirstInstance: 'indirect-first-instance',
  47641. ShaderF16: 'shader-f16',
  47642. RG11B10UFloat: 'rg11b10ufloat-renderable',
  47643. BGRA8UNormStorage: 'bgra8unorm-storage',
  47644. Float32Filterable: 'float32-filterable',
  47645. Float32Blendable: 'float32-blendable',
  47646. ClipDistances: 'clip-distances',
  47647. DualSourceBlending: 'dual-source-blending',
  47648. Subgroups: 'subgroups',
  47649. TextureFormatsTier1: 'texture-formats-tier1',
  47650. TextureFormatsTier2: 'texture-formats-tier2'
  47651. };
  47652. /**
  47653. * A special form of sampler binding type.
  47654. * It's texture value is managed by a node object.
  47655. *
  47656. * @private
  47657. * @augments Sampler
  47658. */
  47659. class NodeSampler extends Sampler {
  47660. /**
  47661. * Constructs a new node-based sampler.
  47662. *
  47663. * @param {string} name - The samplers's name.
  47664. * @param {TextureNode} textureNode - The texture node.
  47665. * @param {UniformGroupNode} groupNode - The uniform group node.
  47666. */
  47667. constructor( name, textureNode, groupNode ) {
  47668. super( name, textureNode ? textureNode.value : null );
  47669. /**
  47670. * The texture node.
  47671. *
  47672. * @type {TextureNode}
  47673. */
  47674. this.textureNode = textureNode;
  47675. /**
  47676. * The uniform group node.
  47677. *
  47678. * @type {UniformGroupNode}
  47679. */
  47680. this.groupNode = groupNode;
  47681. }
  47682. /**
  47683. * Updates the texture value of this sampler.
  47684. */
  47685. update() {
  47686. this.texture = this.textureNode.value;
  47687. }
  47688. }
  47689. /**
  47690. * Represents a storage buffer binding type.
  47691. *
  47692. * @private
  47693. * @augments Buffer
  47694. */
  47695. class StorageBuffer extends Buffer {
  47696. /**
  47697. * Constructs a new uniform buffer.
  47698. *
  47699. * @param {string} name - The buffer's name.
  47700. * @param {BufferAttribute} attribute - The buffer attribute.
  47701. */
  47702. constructor( name, attribute ) {
  47703. super( name, attribute ? attribute.array : null );
  47704. /**
  47705. * This flag can be used for type testing.
  47706. *
  47707. * @type {BufferAttribute}
  47708. */
  47709. this.attribute = attribute;
  47710. /**
  47711. * This flag can be used for type testing.
  47712. *
  47713. * @type {boolean}
  47714. * @readonly
  47715. * @default true
  47716. */
  47717. this.isStorageBuffer = true;
  47718. }
  47719. }
  47720. let _id = 0;
  47721. /**
  47722. * A special form of storage buffer binding type.
  47723. * It's buffer value is managed by a node object.
  47724. *
  47725. * @private
  47726. * @augments StorageBuffer
  47727. */
  47728. class NodeStorageBuffer extends StorageBuffer {
  47729. /**
  47730. * Constructs a new node-based storage buffer.
  47731. *
  47732. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  47733. * @param {UniformGroupNode} groupNode - The uniform group node.
  47734. */
  47735. constructor( nodeUniform, groupNode ) {
  47736. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  47737. /**
  47738. * The node uniform.
  47739. *
  47740. * @type {StorageBufferNode}
  47741. */
  47742. this.nodeUniform = nodeUniform;
  47743. /**
  47744. * The access type.
  47745. *
  47746. * @type {string}
  47747. */
  47748. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  47749. /**
  47750. * The uniform group node.
  47751. *
  47752. * @type {UniformGroupNode}
  47753. */
  47754. this.groupNode = groupNode;
  47755. }
  47756. /**
  47757. * The storage buffer.
  47758. *
  47759. * @type {BufferAttribute}
  47760. */
  47761. get buffer() {
  47762. return this.nodeUniform.value;
  47763. }
  47764. }
  47765. /**
  47766. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  47767. *
  47768. * @private
  47769. */
  47770. class WebGPUTexturePassUtils extends DataMap {
  47771. /**
  47772. * Constructs a new utility object.
  47773. *
  47774. * @param {GPUDevice} device - The WebGPU device.
  47775. */
  47776. constructor( device ) {
  47777. super();
  47778. /**
  47779. * The WebGPU device.
  47780. *
  47781. * @type {GPUDevice}
  47782. */
  47783. this.device = device;
  47784. const mipmapVertexSource = `
  47785. struct VarysStruct {
  47786. @builtin( position ) Position: vec4<f32>,
  47787. @location( 0 ) vTex : vec2<f32>
  47788. };
  47789. @vertex
  47790. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  47791. var Varys : VarysStruct;
  47792. var pos = array< vec2<f32>, 4 >(
  47793. vec2<f32>( -1.0, 1.0 ),
  47794. vec2<f32>( 1.0, 1.0 ),
  47795. vec2<f32>( -1.0, -1.0 ),
  47796. vec2<f32>( 1.0, -1.0 )
  47797. );
  47798. var tex = array< vec2<f32>, 4 >(
  47799. vec2<f32>( 0.0, 0.0 ),
  47800. vec2<f32>( 1.0, 0.0 ),
  47801. vec2<f32>( 0.0, 1.0 ),
  47802. vec2<f32>( 1.0, 1.0 )
  47803. );
  47804. Varys.vTex = tex[ vertexIndex ];
  47805. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  47806. return Varys;
  47807. }
  47808. `;
  47809. const mipmapFragmentSource = `
  47810. @group( 0 ) @binding( 0 )
  47811. var imgSampler : sampler;
  47812. @group( 0 ) @binding( 1 )
  47813. var img : texture_2d<f32>;
  47814. @fragment
  47815. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  47816. return textureSample( img, imgSampler, vTex );
  47817. }
  47818. `;
  47819. const flipYFragmentSource = `
  47820. @group( 0 ) @binding( 0 )
  47821. var imgSampler : sampler;
  47822. @group( 0 ) @binding( 1 )
  47823. var img : texture_2d<f32>;
  47824. @fragment
  47825. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  47826. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  47827. }
  47828. `;
  47829. /**
  47830. * The mipmap GPU sampler.
  47831. *
  47832. * @type {GPUSampler}
  47833. */
  47834. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  47835. /**
  47836. * The flipY GPU sampler.
  47837. *
  47838. * @type {GPUSampler}
  47839. */
  47840. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  47841. /**
  47842. * A cache for GPU render pipelines used for copy/transfer passes.
  47843. * Every texture format requires a unique pipeline.
  47844. *
  47845. * @type {Object<string,GPURenderPipeline>}
  47846. */
  47847. this.transferPipelines = {};
  47848. /**
  47849. * A cache for GPU render pipelines used for flipY passes.
  47850. * Every texture format requires a unique pipeline.
  47851. *
  47852. * @type {Object<string,GPURenderPipeline>}
  47853. */
  47854. this.flipYPipelines = {};
  47855. /**
  47856. * The mipmap vertex shader module.
  47857. *
  47858. * @type {GPUShaderModule}
  47859. */
  47860. this.mipmapVertexShaderModule = device.createShaderModule( {
  47861. label: 'mipmapVertex',
  47862. code: mipmapVertexSource
  47863. } );
  47864. /**
  47865. * The mipmap fragment shader module.
  47866. *
  47867. * @type {GPUShaderModule}
  47868. */
  47869. this.mipmapFragmentShaderModule = device.createShaderModule( {
  47870. label: 'mipmapFragment',
  47871. code: mipmapFragmentSource
  47872. } );
  47873. /**
  47874. * The flipY fragment shader module.
  47875. *
  47876. * @type {GPUShaderModule}
  47877. */
  47878. this.flipYFragmentShaderModule = device.createShaderModule( {
  47879. label: 'flipYFragment',
  47880. code: flipYFragmentSource
  47881. } );
  47882. }
  47883. /**
  47884. * Returns a render pipeline for the internal copy render pass. The pass
  47885. * requires a unique render pipeline for each texture format.
  47886. *
  47887. * @param {string} format - The GPU texture format
  47888. * @return {GPURenderPipeline} The GPU render pipeline.
  47889. */
  47890. getTransferPipeline( format ) {
  47891. let pipeline = this.transferPipelines[ format ];
  47892. if ( pipeline === undefined ) {
  47893. pipeline = this.device.createRenderPipeline( {
  47894. label: `mipmap-${ format }`,
  47895. vertex: {
  47896. module: this.mipmapVertexShaderModule,
  47897. entryPoint: 'main'
  47898. },
  47899. fragment: {
  47900. module: this.mipmapFragmentShaderModule,
  47901. entryPoint: 'main',
  47902. targets: [ { format } ]
  47903. },
  47904. primitive: {
  47905. topology: GPUPrimitiveTopology.TriangleStrip,
  47906. stripIndexFormat: GPUIndexFormat.Uint32
  47907. },
  47908. layout: 'auto'
  47909. } );
  47910. this.transferPipelines[ format ] = pipeline;
  47911. }
  47912. return pipeline;
  47913. }
  47914. /**
  47915. * Returns a render pipeline for the flipY render pass. The pass
  47916. * requires a unique render pipeline for each texture format.
  47917. *
  47918. * @param {string} format - The GPU texture format
  47919. * @return {GPURenderPipeline} The GPU render pipeline.
  47920. */
  47921. getFlipYPipeline( format ) {
  47922. let pipeline = this.flipYPipelines[ format ];
  47923. if ( pipeline === undefined ) {
  47924. pipeline = this.device.createRenderPipeline( {
  47925. label: `flipY-${ format }`,
  47926. vertex: {
  47927. module: this.mipmapVertexShaderModule,
  47928. entryPoint: 'main'
  47929. },
  47930. fragment: {
  47931. module: this.flipYFragmentShaderModule,
  47932. entryPoint: 'main',
  47933. targets: [ { format } ]
  47934. },
  47935. primitive: {
  47936. topology: GPUPrimitiveTopology.TriangleStrip,
  47937. stripIndexFormat: GPUIndexFormat.Uint32
  47938. },
  47939. layout: 'auto'
  47940. } );
  47941. this.flipYPipelines[ format ] = pipeline;
  47942. }
  47943. return pipeline;
  47944. }
  47945. /**
  47946. * Flip the contents of the given GPU texture along its vertical axis.
  47947. *
  47948. * @param {GPUTexture} textureGPU - The GPU texture object.
  47949. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47950. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  47951. */
  47952. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  47953. const format = textureGPUDescriptor.format;
  47954. const { width, height } = textureGPUDescriptor.size;
  47955. const transferPipeline = this.getTransferPipeline( format );
  47956. const flipYPipeline = this.getFlipYPipeline( format );
  47957. const tempTexture = this.device.createTexture( {
  47958. size: { width, height, depthOrArrayLayers: 1 },
  47959. format,
  47960. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  47961. } );
  47962. const srcView = textureGPU.createView( {
  47963. baseMipLevel: 0,
  47964. mipLevelCount: 1,
  47965. dimension: GPUTextureViewDimension.TwoD,
  47966. baseArrayLayer
  47967. } );
  47968. const dstView = tempTexture.createView( {
  47969. baseMipLevel: 0,
  47970. mipLevelCount: 1,
  47971. dimension: GPUTextureViewDimension.TwoD,
  47972. baseArrayLayer: 0
  47973. } );
  47974. const commandEncoder = this.device.createCommandEncoder( {} );
  47975. const pass = ( pipeline, sourceView, destinationView ) => {
  47976. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  47977. const bindGroup = this.device.createBindGroup( {
  47978. layout: bindGroupLayout,
  47979. entries: [ {
  47980. binding: 0,
  47981. resource: this.flipYSampler
  47982. }, {
  47983. binding: 1,
  47984. resource: sourceView
  47985. } ]
  47986. } );
  47987. const passEncoder = commandEncoder.beginRenderPass( {
  47988. colorAttachments: [ {
  47989. view: destinationView,
  47990. loadOp: GPULoadOp.Clear,
  47991. storeOp: GPUStoreOp.Store,
  47992. clearValue: [ 0, 0, 0, 0 ]
  47993. } ]
  47994. } );
  47995. passEncoder.setPipeline( pipeline );
  47996. passEncoder.setBindGroup( 0, bindGroup );
  47997. passEncoder.draw( 4, 1, 0, 0 );
  47998. passEncoder.end();
  47999. };
  48000. pass( transferPipeline, srcView, dstView );
  48001. pass( flipYPipeline, dstView, srcView );
  48002. this.device.queue.submit( [ commandEncoder.finish() ] );
  48003. tempTexture.destroy();
  48004. }
  48005. /**
  48006. * Generates mipmaps for the given GPU texture.
  48007. *
  48008. * @param {GPUTexture} textureGPU - The GPU texture object.
  48009. * @param {Object} textureGPUDescriptor - The texture descriptor.
  48010. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  48011. */
  48012. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  48013. const textureData = this.get( textureGPU );
  48014. if ( textureData.useCount === undefined ) {
  48015. textureData.useCount = 0;
  48016. textureData.layers = [];
  48017. }
  48018. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  48019. const commandEncoder = this.device.createCommandEncoder( {} );
  48020. this._mipmapRunBundles( commandEncoder, passes );
  48021. this.device.queue.submit( [ commandEncoder.finish() ] );
  48022. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  48023. textureData.useCount ++;
  48024. }
  48025. /**
  48026. * Since multiple copy render passes are required to generate mipmaps, the passes
  48027. * are managed as render bundles to improve performance.
  48028. *
  48029. * @param {GPUTexture} textureGPU - The GPU texture object.
  48030. * @param {Object} textureGPUDescriptor - The texture descriptor.
  48031. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  48032. * @return {Array<Object>} An array of render bundles.
  48033. */
  48034. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  48035. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  48036. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  48037. let srcView = textureGPU.createView( {
  48038. baseMipLevel: 0,
  48039. mipLevelCount: 1,
  48040. dimension: GPUTextureViewDimension.TwoD,
  48041. baseArrayLayer
  48042. } );
  48043. const passes = [];
  48044. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  48045. const bindGroup = this.device.createBindGroup( {
  48046. layout: bindGroupLayout,
  48047. entries: [ {
  48048. binding: 0,
  48049. resource: this.mipmapSampler
  48050. }, {
  48051. binding: 1,
  48052. resource: srcView
  48053. } ]
  48054. } );
  48055. const dstView = textureGPU.createView( {
  48056. baseMipLevel: i,
  48057. mipLevelCount: 1,
  48058. dimension: GPUTextureViewDimension.TwoD,
  48059. baseArrayLayer
  48060. } );
  48061. const passDescriptor = {
  48062. colorAttachments: [ {
  48063. view: dstView,
  48064. loadOp: GPULoadOp.Clear,
  48065. storeOp: GPUStoreOp.Store,
  48066. clearValue: [ 0, 0, 0, 0 ]
  48067. } ]
  48068. };
  48069. const passEncoder = this.device.createRenderBundleEncoder( {
  48070. colorFormats: [ textureGPUDescriptor.format ]
  48071. } );
  48072. passEncoder.setPipeline( pipeline );
  48073. passEncoder.setBindGroup( 0, bindGroup );
  48074. passEncoder.draw( 4, 1, 0, 0 );
  48075. passes.push( {
  48076. renderBundles: [ passEncoder.finish() ],
  48077. passDescriptor
  48078. } );
  48079. srcView = dstView;
  48080. }
  48081. return passes;
  48082. }
  48083. /**
  48084. * Executes the render bundles.
  48085. *
  48086. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  48087. * @param {Array<Object>} passes - An array of render bundles.
  48088. */
  48089. _mipmapRunBundles( commandEncoder, passes ) {
  48090. const levels = passes.length;
  48091. for ( let i = 0; i < levels; i ++ ) {
  48092. const pass = passes[ i ];
  48093. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  48094. passEncoder.executeBundles( pass.renderBundles );
  48095. passEncoder.end();
  48096. }
  48097. }
  48098. }
  48099. const _compareToWebGPU = {
  48100. [ NeverCompare ]: 'never',
  48101. [ LessCompare ]: 'less',
  48102. [ EqualCompare ]: 'equal',
  48103. [ LessEqualCompare ]: 'less-equal',
  48104. [ GreaterCompare ]: 'greater',
  48105. [ GreaterEqualCompare ]: 'greater-equal',
  48106. [ AlwaysCompare ]: 'always',
  48107. [ NotEqualCompare ]: 'not-equal'
  48108. };
  48109. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  48110. /**
  48111. * A WebGPU backend utility module for managing textures.
  48112. *
  48113. * @private
  48114. */
  48115. class WebGPUTextureUtils {
  48116. /**
  48117. * Constructs a new utility object.
  48118. *
  48119. * @param {WebGPUBackend} backend - The WebGPU backend.
  48120. */
  48121. constructor( backend ) {
  48122. /**
  48123. * A reference to the WebGPU backend.
  48124. *
  48125. * @type {WebGPUBackend}
  48126. */
  48127. this.backend = backend;
  48128. /**
  48129. * A reference to the pass utils.
  48130. *
  48131. * @type {?WebGPUTexturePassUtils}
  48132. * @default null
  48133. */
  48134. this._passUtils = null;
  48135. /**
  48136. * A dictionary for managing default textures. The key
  48137. * is the texture format, the value the texture object.
  48138. *
  48139. * @type {Object<string,Texture>}
  48140. */
  48141. this.defaultTexture = {};
  48142. /**
  48143. * A dictionary for managing default cube textures. The key
  48144. * is the texture format, the value the texture object.
  48145. *
  48146. * @type {Object<string,CubeTexture>}
  48147. */
  48148. this.defaultCubeTexture = {};
  48149. /**
  48150. * A default video frame.
  48151. *
  48152. * @type {?VideoFrame}
  48153. * @default null
  48154. */
  48155. this.defaultVideoFrame = null;
  48156. /**
  48157. * Represents the color attachment of the default framebuffer.
  48158. *
  48159. * @type {?GPUTexture}
  48160. * @default null
  48161. */
  48162. this.colorBuffer = null;
  48163. /**
  48164. * Represents the depth attachment of the default framebuffer.
  48165. *
  48166. * @type {DepthTexture}
  48167. */
  48168. this.depthTexture = new DepthTexture();
  48169. this.depthTexture.name = 'depthBuffer';
  48170. }
  48171. /**
  48172. * Creates a GPU sampler for the given texture.
  48173. *
  48174. * @param {Texture} texture - The texture to create the sampler for.
  48175. */
  48176. createSampler( texture ) {
  48177. const backend = this.backend;
  48178. const device = backend.device;
  48179. const textureGPU = backend.get( texture );
  48180. const samplerDescriptorGPU = {
  48181. addressModeU: this._convertAddressMode( texture.wrapS ),
  48182. addressModeV: this._convertAddressMode( texture.wrapT ),
  48183. addressModeW: this._convertAddressMode( texture.wrapR ),
  48184. magFilter: this._convertFilterMode( texture.magFilter ),
  48185. minFilter: this._convertFilterMode( texture.minFilter ),
  48186. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  48187. maxAnisotropy: 1
  48188. };
  48189. // anisotropy can only be used when all filter modes are set to linear.
  48190. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  48191. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  48192. }
  48193. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  48194. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  48195. }
  48196. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  48197. }
  48198. /**
  48199. * Creates a default texture for the given texture that can be used
  48200. * as a placeholder until the actual texture is ready for usage.
  48201. *
  48202. * @param {Texture} texture - The texture to create a default texture for.
  48203. */
  48204. createDefaultTexture( texture ) {
  48205. let textureGPU;
  48206. const format = getFormat( texture );
  48207. if ( texture.isCubeTexture ) {
  48208. textureGPU = this._getDefaultCubeTextureGPU( format );
  48209. } else {
  48210. textureGPU = this._getDefaultTextureGPU( format );
  48211. }
  48212. this.backend.get( texture ).texture = textureGPU;
  48213. }
  48214. /**
  48215. * Defines a texture on the GPU for the given texture object.
  48216. *
  48217. * @param {Texture} texture - The texture.
  48218. * @param {Object} [options={}] - Optional configuration parameter.
  48219. */
  48220. createTexture( texture, options = {} ) {
  48221. const backend = this.backend;
  48222. const textureData = backend.get( texture );
  48223. if ( textureData.initialized ) {
  48224. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  48225. }
  48226. if ( texture.isExternalTexture ) {
  48227. textureData.texture = texture.sourceTexture;
  48228. textureData.initialized = true;
  48229. return;
  48230. }
  48231. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  48232. if ( options.levels === undefined ) options.levels = 1;
  48233. if ( options.depth === undefined ) options.depth = 1;
  48234. const { width, height, depth, levels } = options;
  48235. if ( texture.isFramebufferTexture ) {
  48236. if ( options.renderTarget ) {
  48237. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  48238. } else {
  48239. options.format = this.backend.utils.getPreferredCanvasFormat();
  48240. }
  48241. }
  48242. const dimension = this._getDimension( texture );
  48243. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  48244. textureData.format = format;
  48245. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  48246. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  48247. if ( texture.isStorageTexture === true ) {
  48248. usage |= GPUTextureUsage.STORAGE_BINDING;
  48249. }
  48250. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  48251. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  48252. }
  48253. const textureDescriptorGPU = {
  48254. label: texture.name,
  48255. size: {
  48256. width: width,
  48257. height: height,
  48258. depthOrArrayLayers: depth,
  48259. },
  48260. mipLevelCount: levels,
  48261. sampleCount: primarySamples,
  48262. dimension: dimension,
  48263. format: format,
  48264. usage: usage
  48265. };
  48266. // texture creation
  48267. if ( format === undefined ) {
  48268. warn( 'WebGPURenderer: Texture format not supported.' );
  48269. this.createDefaultTexture( texture );
  48270. return;
  48271. }
  48272. if ( texture.isCubeTexture ) {
  48273. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  48274. }
  48275. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  48276. if ( isMSAA ) {
  48277. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  48278. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  48279. msaaTextureDescriptorGPU.sampleCount = samples;
  48280. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  48281. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  48282. }
  48283. textureData.initialized = true;
  48284. textureData.textureDescriptorGPU = textureDescriptorGPU;
  48285. }
  48286. /**
  48287. * Destroys the GPU data for the given texture object.
  48288. *
  48289. * @param {Texture} texture - The texture.
  48290. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  48291. */
  48292. destroyTexture( texture, isDefaultTexture = false ) {
  48293. const backend = this.backend;
  48294. const textureData = backend.get( texture );
  48295. if ( textureData.texture !== undefined && isDefaultTexture === false ) textureData.texture.destroy();
  48296. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  48297. backend.delete( texture );
  48298. }
  48299. /**
  48300. * Destroys the GPU sampler for the given texture.
  48301. *
  48302. * @param {Texture} texture - The texture to destroy the sampler for.
  48303. */
  48304. destroySampler( texture ) {
  48305. const backend = this.backend;
  48306. const textureData = backend.get( texture );
  48307. delete textureData.sampler;
  48308. }
  48309. /**
  48310. * Generates mipmaps for the given texture.
  48311. *
  48312. * @param {Texture} texture - The texture.
  48313. */
  48314. generateMipmaps( texture ) {
  48315. const textureData = this.backend.get( texture );
  48316. if ( texture.isCubeTexture ) {
  48317. for ( let i = 0; i < 6; i ++ ) {
  48318. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  48319. }
  48320. } else {
  48321. const depth = texture.image.depth || 1;
  48322. for ( let i = 0; i < depth; i ++ ) {
  48323. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  48324. }
  48325. }
  48326. }
  48327. /**
  48328. * Returns the color buffer representing the color
  48329. * attachment of the default framebuffer.
  48330. *
  48331. * @return {GPUTexture} The color buffer.
  48332. */
  48333. getColorBuffer() {
  48334. if ( this.colorBuffer ) this.colorBuffer.destroy();
  48335. const backend = this.backend;
  48336. const { width, height } = backend.getDrawingBufferSize();
  48337. this.colorBuffer = backend.device.createTexture( {
  48338. label: 'colorBuffer',
  48339. size: {
  48340. width: width,
  48341. height: height,
  48342. depthOrArrayLayers: 1
  48343. },
  48344. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  48345. format: backend.utils.getPreferredCanvasFormat(),
  48346. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  48347. } );
  48348. return this.colorBuffer;
  48349. }
  48350. /**
  48351. * Returns the depth buffer representing the depth
  48352. * attachment of the default framebuffer.
  48353. *
  48354. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  48355. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  48356. * @return {GPUTexture} The depth buffer.
  48357. */
  48358. getDepthBuffer( depth = true, stencil = false ) {
  48359. const backend = this.backend;
  48360. const { width, height } = backend.getDrawingBufferSize();
  48361. const depthTexture = this.depthTexture;
  48362. const depthTextureGPU = backend.get( depthTexture ).texture;
  48363. let format, type;
  48364. if ( stencil ) {
  48365. format = DepthStencilFormat;
  48366. type = UnsignedInt248Type;
  48367. } else if ( depth ) {
  48368. format = DepthFormat;
  48369. type = UnsignedIntType;
  48370. }
  48371. if ( depthTextureGPU !== undefined ) {
  48372. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  48373. return depthTextureGPU;
  48374. }
  48375. this.destroyTexture( depthTexture );
  48376. }
  48377. depthTexture.name = 'depthBuffer';
  48378. depthTexture.format = format;
  48379. depthTexture.type = type;
  48380. depthTexture.image.width = width;
  48381. depthTexture.image.height = height;
  48382. this.createTexture( depthTexture, { width, height } );
  48383. return backend.get( depthTexture ).texture;
  48384. }
  48385. /**
  48386. * Uploads the updated texture data to the GPU.
  48387. *
  48388. * @param {Texture} texture - The texture.
  48389. * @param {Object} [options={}] - Optional configuration parameter.
  48390. */
  48391. updateTexture( texture, options ) {
  48392. const textureData = this.backend.get( texture );
  48393. const mipmaps = texture.mipmaps;
  48394. const { textureDescriptorGPU } = textureData;
  48395. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  48396. return;
  48397. // transfer texture data
  48398. if ( texture.isDataTexture ) {
  48399. if ( mipmaps.length > 0 ) {
  48400. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48401. const mipmap = mipmaps[ i ];
  48402. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  48403. }
  48404. } else {
  48405. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  48406. }
  48407. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  48408. for ( let i = 0; i < options.image.depth; i ++ ) {
  48409. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  48410. }
  48411. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  48412. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  48413. } else if ( texture.isCubeTexture ) {
  48414. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  48415. } else {
  48416. if ( mipmaps.length > 0 ) {
  48417. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48418. const mipmap = mipmaps[ i ];
  48419. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  48420. }
  48421. } else {
  48422. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  48423. }
  48424. }
  48425. //
  48426. textureData.version = texture.version;
  48427. }
  48428. /**
  48429. * Returns texture data as a typed array.
  48430. *
  48431. * @async
  48432. * @param {Texture} texture - The texture to copy.
  48433. * @param {number} x - The x coordinate of the copy origin.
  48434. * @param {number} y - The y coordinate of the copy origin.
  48435. * @param {number} width - The width of the copy.
  48436. * @param {number} height - The height of the copy.
  48437. * @param {number} faceIndex - The face index.
  48438. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  48439. */
  48440. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  48441. const device = this.backend.device;
  48442. const textureData = this.backend.get( texture );
  48443. const textureGPU = textureData.texture;
  48444. const format = textureData.textureDescriptorGPU.format;
  48445. const bytesPerTexel = this._getBytesPerTexel( format );
  48446. let bytesPerRow = width * bytesPerTexel;
  48447. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  48448. const readBuffer = device.createBuffer(
  48449. {
  48450. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  48451. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48452. }
  48453. );
  48454. const encoder = device.createCommandEncoder();
  48455. encoder.copyTextureToBuffer(
  48456. {
  48457. texture: textureGPU,
  48458. origin: { x, y, z: faceIndex },
  48459. },
  48460. {
  48461. buffer: readBuffer,
  48462. bytesPerRow: bytesPerRow
  48463. },
  48464. {
  48465. width: width,
  48466. height: height
  48467. }
  48468. );
  48469. const typedArrayType = this._getTypedArrayType( format );
  48470. device.queue.submit( [ encoder.finish() ] );
  48471. await readBuffer.mapAsync( GPUMapMode.READ );
  48472. const buffer = readBuffer.getMappedRange();
  48473. return new typedArrayType( buffer );
  48474. }
  48475. /**
  48476. * Returns the default GPU texture for the given format.
  48477. *
  48478. * @private
  48479. * @param {string} format - The GPU format.
  48480. * @return {GPUTexture} The GPU texture.
  48481. */
  48482. _getDefaultTextureGPU( format ) {
  48483. let defaultTexture = this.defaultTexture[ format ];
  48484. if ( defaultTexture === undefined ) {
  48485. const texture = new Texture();
  48486. texture.minFilter = NearestFilter;
  48487. texture.magFilter = NearestFilter;
  48488. this.createTexture( texture, { width: 1, height: 1, format } );
  48489. this.defaultTexture[ format ] = defaultTexture = texture;
  48490. }
  48491. return this.backend.get( defaultTexture ).texture;
  48492. }
  48493. /**
  48494. * Returns the default GPU cube texture for the given format.
  48495. *
  48496. * @private
  48497. * @param {string} format - The GPU format.
  48498. * @return {GPUTexture} The GPU texture.
  48499. */
  48500. _getDefaultCubeTextureGPU( format ) {
  48501. let defaultCubeTexture = this.defaultTexture[ format ];
  48502. if ( defaultCubeTexture === undefined ) {
  48503. const texture = new CubeTexture();
  48504. texture.minFilter = NearestFilter;
  48505. texture.magFilter = NearestFilter;
  48506. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  48507. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  48508. }
  48509. return this.backend.get( defaultCubeTexture ).texture;
  48510. }
  48511. /**
  48512. * Uploads cube texture image data to the GPU memory.
  48513. *
  48514. * @private
  48515. * @param {CubeTexture} texture - The cube texture.
  48516. * @param {GPUTexture} textureGPU - The GPU texture.
  48517. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48518. */
  48519. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  48520. const images = texture.images;
  48521. const mipmaps = texture.mipmaps;
  48522. for ( let i = 0; i < 6; i ++ ) {
  48523. const image = images[ i ];
  48524. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  48525. if ( image.isDataTexture ) {
  48526. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  48527. } else {
  48528. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  48529. }
  48530. for ( let j = 0; j < mipmaps.length; j ++ ) {
  48531. const mipmap = mipmaps[ j ];
  48532. const image = mipmap.images[ i ];
  48533. if ( image.isDataTexture ) {
  48534. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  48535. } else {
  48536. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  48537. }
  48538. }
  48539. }
  48540. }
  48541. /**
  48542. * Uploads texture image data to the GPU memory.
  48543. *
  48544. * @private
  48545. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  48546. * @param {GPUTexture} textureGPU - The GPU texture.
  48547. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48548. * @param {number} originDepth - The origin depth.
  48549. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  48550. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  48551. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  48552. */
  48553. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  48554. const device = this.backend.device;
  48555. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  48556. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  48557. device.queue.copyExternalImageToTexture(
  48558. {
  48559. source: image,
  48560. flipY: flipY
  48561. }, {
  48562. texture: textureGPU,
  48563. mipLevel: mipLevel,
  48564. origin: { x: 0, y: 0, z: originDepth },
  48565. premultipliedAlpha: premultiplyAlpha
  48566. }, {
  48567. width: width,
  48568. height: height,
  48569. depthOrArrayLayers: 1
  48570. }
  48571. );
  48572. }
  48573. /**
  48574. * Returns the pass utils singleton.
  48575. *
  48576. * @private
  48577. * @return {WebGPUTexturePassUtils} The utils instance.
  48578. */
  48579. _getPassUtils() {
  48580. let passUtils = this._passUtils;
  48581. if ( passUtils === null ) {
  48582. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  48583. }
  48584. return passUtils;
  48585. }
  48586. /**
  48587. * Generates mipmaps for the given GPU texture.
  48588. *
  48589. * @private
  48590. * @param {GPUTexture} textureGPU - The GPU texture object.
  48591. * @param {Object} textureDescriptorGPU - The texture descriptor.
  48592. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  48593. */
  48594. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  48595. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  48596. }
  48597. /**
  48598. * Flip the contents of the given GPU texture along its vertical axis.
  48599. *
  48600. * @private
  48601. * @param {GPUTexture} textureGPU - The GPU texture object.
  48602. * @param {Object} textureDescriptorGPU - The texture descriptor.
  48603. * @param {number} [originDepth=0] - The origin depth.
  48604. */
  48605. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  48606. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  48607. }
  48608. /**
  48609. * Uploads texture buffer data to the GPU memory.
  48610. *
  48611. * @private
  48612. * @param {Object} image - An object defining the image buffer data.
  48613. * @param {GPUTexture} textureGPU - The GPU texture.
  48614. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48615. * @param {number} originDepth - The origin depth.
  48616. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  48617. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  48618. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  48619. */
  48620. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  48621. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  48622. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  48623. const device = this.backend.device;
  48624. const data = image.data;
  48625. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  48626. const bytesPerRow = image.width * bytesPerTexel;
  48627. device.queue.writeTexture(
  48628. {
  48629. texture: textureGPU,
  48630. mipLevel: mipLevel,
  48631. origin: { x: 0, y: 0, z: originDepth }
  48632. },
  48633. data,
  48634. {
  48635. offset: image.width * image.height * bytesPerTexel * depth,
  48636. bytesPerRow
  48637. },
  48638. {
  48639. width: image.width,
  48640. height: image.height,
  48641. depthOrArrayLayers: 1
  48642. } );
  48643. if ( flipY === true ) {
  48644. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  48645. }
  48646. }
  48647. /**
  48648. * Uploads compressed texture data to the GPU memory.
  48649. *
  48650. * @private
  48651. * @param {Array<Object>} mipmaps - An array with mipmap data.
  48652. * @param {GPUTexture} textureGPU - The GPU texture.
  48653. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48654. */
  48655. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  48656. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  48657. const device = this.backend.device;
  48658. const blockData = this._getBlockData( textureDescriptorGPU.format );
  48659. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  48660. for ( let i = 0; i < mipmaps.length; i ++ ) {
  48661. const mipmap = mipmaps[ i ];
  48662. const width = mipmap.width;
  48663. const height = mipmap.height;
  48664. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  48665. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  48666. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  48667. for ( let j = 0; j < depth; j ++ ) {
  48668. device.queue.writeTexture(
  48669. {
  48670. texture: textureGPU,
  48671. mipLevel: i,
  48672. origin: { x: 0, y: 0, z: j }
  48673. },
  48674. mipmap.data,
  48675. {
  48676. offset: j * bytesPerImage,
  48677. bytesPerRow,
  48678. rowsPerImage: Math.ceil( height / blockData.height )
  48679. },
  48680. {
  48681. width: Math.ceil( width / blockData.width ) * blockData.width,
  48682. height: Math.ceil( height / blockData.height ) * blockData.height,
  48683. depthOrArrayLayers: 1
  48684. }
  48685. );
  48686. }
  48687. }
  48688. }
  48689. /**
  48690. * This method is only relevant for compressed texture formats. It returns a block
  48691. * data descriptor for the given GPU compressed texture format.
  48692. *
  48693. * @private
  48694. * @param {string} format - The GPU compressed texture format.
  48695. * @return {Object} The block data descriptor.
  48696. */
  48697. _getBlockData( format ) {
  48698. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  48699. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  48700. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  48701. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  48702. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  48703. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  48704. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  48705. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  48706. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  48707. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  48708. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  48709. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  48710. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  48711. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  48712. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  48713. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  48714. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  48715. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  48716. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  48717. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  48718. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  48719. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  48720. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  48721. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  48722. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  48723. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  48724. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  48725. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  48726. }
  48727. /**
  48728. * Converts the three.js uv wrapping constants to GPU address mode constants.
  48729. *
  48730. * @private
  48731. * @param {number} value - The three.js constant defining a uv wrapping mode.
  48732. * @return {string} The GPU address mode.
  48733. */
  48734. _convertAddressMode( value ) {
  48735. let addressMode = GPUAddressMode.ClampToEdge;
  48736. if ( value === RepeatWrapping ) {
  48737. addressMode = GPUAddressMode.Repeat;
  48738. } else if ( value === MirroredRepeatWrapping ) {
  48739. addressMode = GPUAddressMode.MirrorRepeat;
  48740. }
  48741. return addressMode;
  48742. }
  48743. /**
  48744. * Converts the three.js filter constants to GPU filter constants.
  48745. *
  48746. * @private
  48747. * @param {number} value - The three.js constant defining a filter mode.
  48748. * @return {string} The GPU filter mode.
  48749. */
  48750. _convertFilterMode( value ) {
  48751. let filterMode = GPUFilterMode.Linear;
  48752. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  48753. filterMode = GPUFilterMode.Nearest;
  48754. }
  48755. return filterMode;
  48756. }
  48757. /**
  48758. * Returns the bytes-per-texel value for the given GPU texture format.
  48759. *
  48760. * @private
  48761. * @param {string} format - The GPU texture format.
  48762. * @return {number} The bytes-per-texel.
  48763. */
  48764. _getBytesPerTexel( format ) {
  48765. // 8-bit formats
  48766. if ( format === GPUTextureFormat.R8Unorm ||
  48767. format === GPUTextureFormat.R8Snorm ||
  48768. format === GPUTextureFormat.R8Uint ||
  48769. format === GPUTextureFormat.R8Sint ) return 1;
  48770. // 16-bit formats
  48771. if ( format === GPUTextureFormat.R16Uint ||
  48772. format === GPUTextureFormat.R16Sint ||
  48773. format === GPUTextureFormat.R16Float ||
  48774. format === GPUTextureFormat.RG8Unorm ||
  48775. format === GPUTextureFormat.RG8Snorm ||
  48776. format === GPUTextureFormat.RG8Uint ||
  48777. format === GPUTextureFormat.RG8Sint ) return 2;
  48778. // 32-bit formats
  48779. if ( format === GPUTextureFormat.R32Uint ||
  48780. format === GPUTextureFormat.R32Sint ||
  48781. format === GPUTextureFormat.R32Float ||
  48782. format === GPUTextureFormat.RG16Uint ||
  48783. format === GPUTextureFormat.RG16Sint ||
  48784. format === GPUTextureFormat.RG16Float ||
  48785. format === GPUTextureFormat.RGBA8Unorm ||
  48786. format === GPUTextureFormat.RGBA8UnormSRGB ||
  48787. format === GPUTextureFormat.RGBA8Snorm ||
  48788. format === GPUTextureFormat.RGBA8Uint ||
  48789. format === GPUTextureFormat.RGBA8Sint ||
  48790. format === GPUTextureFormat.BGRA8Unorm ||
  48791. format === GPUTextureFormat.BGRA8UnormSRGB ||
  48792. // Packed 32-bit formats
  48793. format === GPUTextureFormat.RGB9E5UFloat ||
  48794. format === GPUTextureFormat.RGB10A2Unorm ||
  48795. format === GPUTextureFormat.RG11B10UFloat ||
  48796. format === GPUTextureFormat.Depth32Float ||
  48797. format === GPUTextureFormat.Depth24Plus ||
  48798. format === GPUTextureFormat.Depth24PlusStencil8 ||
  48799. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  48800. // 64-bit formats
  48801. if ( format === GPUTextureFormat.RG32Uint ||
  48802. format === GPUTextureFormat.RG32Sint ||
  48803. format === GPUTextureFormat.RG32Float ||
  48804. format === GPUTextureFormat.RGBA16Uint ||
  48805. format === GPUTextureFormat.RGBA16Sint ||
  48806. format === GPUTextureFormat.RGBA16Float ) return 8;
  48807. // 128-bit formats
  48808. if ( format === GPUTextureFormat.RGBA32Uint ||
  48809. format === GPUTextureFormat.RGBA32Sint ||
  48810. format === GPUTextureFormat.RGBA32Float ) return 16;
  48811. }
  48812. /**
  48813. * Returns the corresponding typed array type for the given GPU texture format.
  48814. *
  48815. * @private
  48816. * @param {string} format - The GPU texture format.
  48817. * @return {TypedArray.constructor} The typed array type.
  48818. */
  48819. _getTypedArrayType( format ) {
  48820. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  48821. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  48822. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  48823. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  48824. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  48825. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  48826. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  48827. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  48828. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  48829. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  48830. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  48831. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  48832. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  48833. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  48834. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  48835. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  48836. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  48837. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  48838. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  48839. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  48840. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  48841. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  48842. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  48843. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  48844. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  48845. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  48846. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  48847. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  48848. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  48849. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  48850. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  48851. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  48852. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  48853. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  48854. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  48855. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  48856. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  48857. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  48858. }
  48859. /**
  48860. * Returns the GPU dimensions for the given texture.
  48861. *
  48862. * @private
  48863. * @param {Texture} texture - The texture.
  48864. * @return {string} The GPU dimension.
  48865. */
  48866. _getDimension( texture ) {
  48867. let dimension;
  48868. if ( texture.is3DTexture || texture.isData3DTexture ) {
  48869. dimension = GPUTextureDimension.ThreeD;
  48870. } else {
  48871. dimension = GPUTextureDimension.TwoD;
  48872. }
  48873. return dimension;
  48874. }
  48875. }
  48876. /**
  48877. * Returns the GPU format for the given texture.
  48878. *
  48879. * @param {Texture} texture - The texture.
  48880. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  48881. * It is not necessary to apply the device for most formats.
  48882. * @return {string} The GPU format.
  48883. */
  48884. function getFormat( texture, device = null ) {
  48885. const format = texture.format;
  48886. const type = texture.type;
  48887. const colorSpace = texture.colorSpace;
  48888. const transfer = ColorManagement.getTransfer( colorSpace );
  48889. let formatGPU;
  48890. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  48891. switch ( format ) {
  48892. case RGB_S3TC_DXT1_Format:
  48893. case RGBA_S3TC_DXT1_Format:
  48894. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  48895. break;
  48896. case RGBA_S3TC_DXT3_Format:
  48897. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  48898. break;
  48899. case RGBA_S3TC_DXT5_Format:
  48900. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  48901. break;
  48902. case RED_RGTC1_Format:
  48903. formatGPU = GPUTextureFormat.BC4RUnorm;
  48904. break;
  48905. case SIGNED_RED_RGTC1_Format:
  48906. formatGPU = GPUTextureFormat.BC4RSnorm;
  48907. break;
  48908. case RED_GREEN_RGTC2_Format:
  48909. formatGPU = GPUTextureFormat.BC5RGUnorm;
  48910. break;
  48911. case SIGNED_RED_GREEN_RGTC2_Format:
  48912. formatGPU = GPUTextureFormat.BC5RGSnorm;
  48913. break;
  48914. case RGBA_BPTC_Format:
  48915. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  48916. break;
  48917. case RGB_ETC2_Format:
  48918. case RGB_ETC1_Format:
  48919. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  48920. break;
  48921. case RGBA_ETC2_EAC_Format:
  48922. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  48923. break;
  48924. case RGBA_ASTC_4x4_Format:
  48925. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  48926. break;
  48927. case RGBA_ASTC_5x4_Format:
  48928. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  48929. break;
  48930. case RGBA_ASTC_5x5_Format:
  48931. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  48932. break;
  48933. case RGBA_ASTC_6x5_Format:
  48934. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  48935. break;
  48936. case RGBA_ASTC_6x6_Format:
  48937. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  48938. break;
  48939. case RGBA_ASTC_8x5_Format:
  48940. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  48941. break;
  48942. case RGBA_ASTC_8x6_Format:
  48943. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  48944. break;
  48945. case RGBA_ASTC_8x8_Format:
  48946. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  48947. break;
  48948. case RGBA_ASTC_10x5_Format:
  48949. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  48950. break;
  48951. case RGBA_ASTC_10x6_Format:
  48952. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  48953. break;
  48954. case RGBA_ASTC_10x8_Format:
  48955. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  48956. break;
  48957. case RGBA_ASTC_10x10_Format:
  48958. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  48959. break;
  48960. case RGBA_ASTC_12x10_Format:
  48961. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  48962. break;
  48963. case RGBA_ASTC_12x12_Format:
  48964. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  48965. break;
  48966. case RGBAFormat:
  48967. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  48968. break;
  48969. default:
  48970. error( 'WebGPURenderer: Unsupported texture format.', format );
  48971. }
  48972. } else {
  48973. switch ( format ) {
  48974. case RGBAFormat:
  48975. switch ( type ) {
  48976. case ByteType:
  48977. formatGPU = GPUTextureFormat.RGBA8Snorm;
  48978. break;
  48979. case ShortType:
  48980. formatGPU = GPUTextureFormat.RGBA16Sint;
  48981. break;
  48982. case UnsignedShortType:
  48983. formatGPU = GPUTextureFormat.RGBA16Uint;
  48984. break;
  48985. case UnsignedIntType:
  48986. formatGPU = GPUTextureFormat.RGBA32Uint;
  48987. break;
  48988. case IntType:
  48989. formatGPU = GPUTextureFormat.RGBA32Sint;
  48990. break;
  48991. case UnsignedByteType:
  48992. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  48993. break;
  48994. case HalfFloatType:
  48995. formatGPU = GPUTextureFormat.RGBA16Float;
  48996. break;
  48997. case FloatType:
  48998. formatGPU = GPUTextureFormat.RGBA32Float;
  48999. break;
  49000. default:
  49001. error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  49002. }
  49003. break;
  49004. case RGBFormat:
  49005. switch ( type ) {
  49006. case UnsignedInt5999Type:
  49007. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  49008. break;
  49009. case UnsignedInt101111Type:
  49010. formatGPU = GPUTextureFormat.RG11B10UFloat;
  49011. break;
  49012. default:
  49013. error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  49014. }
  49015. break;
  49016. case RedFormat:
  49017. switch ( type ) {
  49018. case ByteType:
  49019. formatGPU = GPUTextureFormat.R8Snorm;
  49020. break;
  49021. case ShortType:
  49022. formatGPU = GPUTextureFormat.R16Sint;
  49023. break;
  49024. case UnsignedShortType:
  49025. formatGPU = GPUTextureFormat.R16Uint;
  49026. break;
  49027. case UnsignedIntType:
  49028. formatGPU = GPUTextureFormat.R32Uint;
  49029. break;
  49030. case IntType:
  49031. formatGPU = GPUTextureFormat.R32Sint;
  49032. break;
  49033. case UnsignedByteType:
  49034. formatGPU = GPUTextureFormat.R8Unorm;
  49035. break;
  49036. case HalfFloatType:
  49037. formatGPU = GPUTextureFormat.R16Float;
  49038. break;
  49039. case FloatType:
  49040. formatGPU = GPUTextureFormat.R32Float;
  49041. break;
  49042. default:
  49043. error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  49044. }
  49045. break;
  49046. case RGFormat:
  49047. switch ( type ) {
  49048. case ByteType:
  49049. formatGPU = GPUTextureFormat.RG8Snorm;
  49050. break;
  49051. case ShortType:
  49052. formatGPU = GPUTextureFormat.RG16Sint;
  49053. break;
  49054. case UnsignedShortType:
  49055. formatGPU = GPUTextureFormat.RG16Uint;
  49056. break;
  49057. case UnsignedIntType:
  49058. formatGPU = GPUTextureFormat.RG32Uint;
  49059. break;
  49060. case IntType:
  49061. formatGPU = GPUTextureFormat.RG32Sint;
  49062. break;
  49063. case UnsignedByteType:
  49064. formatGPU = GPUTextureFormat.RG8Unorm;
  49065. break;
  49066. case HalfFloatType:
  49067. formatGPU = GPUTextureFormat.RG16Float;
  49068. break;
  49069. case FloatType:
  49070. formatGPU = GPUTextureFormat.RG32Float;
  49071. break;
  49072. default:
  49073. error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  49074. }
  49075. break;
  49076. case DepthFormat:
  49077. switch ( type ) {
  49078. case UnsignedShortType:
  49079. formatGPU = GPUTextureFormat.Depth16Unorm;
  49080. break;
  49081. case UnsignedIntType:
  49082. formatGPU = GPUTextureFormat.Depth24Plus;
  49083. break;
  49084. case FloatType:
  49085. formatGPU = GPUTextureFormat.Depth32Float;
  49086. break;
  49087. default:
  49088. error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  49089. }
  49090. break;
  49091. case DepthStencilFormat:
  49092. switch ( type ) {
  49093. case UnsignedInt248Type:
  49094. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  49095. break;
  49096. case FloatType:
  49097. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  49098. error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  49099. }
  49100. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  49101. break;
  49102. default:
  49103. error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  49104. }
  49105. break;
  49106. case RedIntegerFormat:
  49107. switch ( type ) {
  49108. case IntType:
  49109. formatGPU = GPUTextureFormat.R32Sint;
  49110. break;
  49111. case UnsignedIntType:
  49112. formatGPU = GPUTextureFormat.R32Uint;
  49113. break;
  49114. default:
  49115. error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  49116. }
  49117. break;
  49118. case RGIntegerFormat:
  49119. switch ( type ) {
  49120. case IntType:
  49121. formatGPU = GPUTextureFormat.RG32Sint;
  49122. break;
  49123. case UnsignedIntType:
  49124. formatGPU = GPUTextureFormat.RG32Uint;
  49125. break;
  49126. default:
  49127. error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  49128. }
  49129. break;
  49130. case RGBAIntegerFormat:
  49131. switch ( type ) {
  49132. case IntType:
  49133. formatGPU = GPUTextureFormat.RGBA32Sint;
  49134. break;
  49135. case UnsignedIntType:
  49136. formatGPU = GPUTextureFormat.RGBA32Uint;
  49137. break;
  49138. default:
  49139. error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  49140. }
  49141. break;
  49142. default:
  49143. error( 'WebGPURenderer: Unsupported texture format.', format );
  49144. }
  49145. }
  49146. return formatGPU;
  49147. }
  49148. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  49149. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  49150. const wgslTypeLib$1 = {
  49151. 'f32': 'float',
  49152. 'i32': 'int',
  49153. 'u32': 'uint',
  49154. 'bool': 'bool',
  49155. 'vec2<f32>': 'vec2',
  49156. 'vec2<i32>': 'ivec2',
  49157. 'vec2<u32>': 'uvec2',
  49158. 'vec2<bool>': 'bvec2',
  49159. 'vec2f': 'vec2',
  49160. 'vec2i': 'ivec2',
  49161. 'vec2u': 'uvec2',
  49162. 'vec2b': 'bvec2',
  49163. 'vec3<f32>': 'vec3',
  49164. 'vec3<i32>': 'ivec3',
  49165. 'vec3<u32>': 'uvec3',
  49166. 'vec3<bool>': 'bvec3',
  49167. 'vec3f': 'vec3',
  49168. 'vec3i': 'ivec3',
  49169. 'vec3u': 'uvec3',
  49170. 'vec3b': 'bvec3',
  49171. 'vec4<f32>': 'vec4',
  49172. 'vec4<i32>': 'ivec4',
  49173. 'vec4<u32>': 'uvec4',
  49174. 'vec4<bool>': 'bvec4',
  49175. 'vec4f': 'vec4',
  49176. 'vec4i': 'ivec4',
  49177. 'vec4u': 'uvec4',
  49178. 'vec4b': 'bvec4',
  49179. 'mat2x2<f32>': 'mat2',
  49180. 'mat2x2f': 'mat2',
  49181. 'mat3x3<f32>': 'mat3',
  49182. 'mat3x3f': 'mat3',
  49183. 'mat4x4<f32>': 'mat4',
  49184. 'mat4x4f': 'mat4',
  49185. 'sampler': 'sampler',
  49186. 'texture_1d': 'texture',
  49187. 'texture_2d': 'texture',
  49188. 'texture_2d_array': 'texture',
  49189. 'texture_multisampled_2d': 'cubeTexture',
  49190. 'texture_depth_2d': 'depthTexture',
  49191. 'texture_depth_2d_array': 'depthTexture',
  49192. 'texture_depth_multisampled_2d': 'depthTexture',
  49193. 'texture_depth_cube': 'depthTexture',
  49194. 'texture_depth_cube_array': 'depthTexture',
  49195. 'texture_3d': 'texture3D',
  49196. 'texture_cube': 'cubeTexture',
  49197. 'texture_cube_array': 'cubeTexture',
  49198. 'texture_storage_1d': 'storageTexture',
  49199. 'texture_storage_2d': 'storageTexture',
  49200. 'texture_storage_2d_array': 'storageTexture',
  49201. 'texture_storage_3d': 'storageTexture'
  49202. };
  49203. const parse = ( source ) => {
  49204. source = source.trim();
  49205. const declaration = source.match( declarationRegexp );
  49206. if ( declaration !== null && declaration.length === 4 ) {
  49207. const inputsCode = declaration[ 2 ];
  49208. const propsMatches = [];
  49209. let match = null;
  49210. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  49211. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  49212. }
  49213. // Process matches to correctly pair names and types
  49214. const inputs = [];
  49215. for ( let i = 0; i < propsMatches.length; i ++ ) {
  49216. const { name, type } = propsMatches[ i ];
  49217. let resolvedType = type;
  49218. if ( resolvedType.startsWith( 'ptr' ) ) {
  49219. resolvedType = 'pointer';
  49220. } else {
  49221. if ( resolvedType.startsWith( 'texture' ) ) {
  49222. resolvedType = type.split( '<' )[ 0 ];
  49223. }
  49224. resolvedType = wgslTypeLib$1[ resolvedType ];
  49225. }
  49226. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  49227. }
  49228. const blockCode = source.substring( declaration[ 0 ].length );
  49229. const outputType = declaration[ 3 ] || 'void';
  49230. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  49231. const type = wgslTypeLib$1[ outputType ] || outputType;
  49232. return {
  49233. type,
  49234. inputs,
  49235. name,
  49236. inputsCode,
  49237. blockCode,
  49238. outputType
  49239. };
  49240. } else {
  49241. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  49242. }
  49243. };
  49244. /**
  49245. * This class represents a WSL node function.
  49246. *
  49247. * @augments NodeFunction
  49248. */
  49249. class WGSLNodeFunction extends NodeFunction {
  49250. /**
  49251. * Constructs a new WGSL node function.
  49252. *
  49253. * @param {string} source - The WGSL source.
  49254. */
  49255. constructor( source ) {
  49256. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  49257. super( type, inputs, name );
  49258. this.inputsCode = inputsCode;
  49259. this.blockCode = blockCode;
  49260. this.outputType = outputType;
  49261. }
  49262. /**
  49263. * This method returns the WGSL code of the node function.
  49264. *
  49265. * @param {string} [name=this.name] - The function's name.
  49266. * @return {string} The shader code.
  49267. */
  49268. getCode( name = this.name ) {
  49269. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  49270. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  49271. }
  49272. }
  49273. /**
  49274. * A WGSL node parser.
  49275. *
  49276. * @augments NodeParser
  49277. */
  49278. class WGSLNodeParser extends NodeParser {
  49279. /**
  49280. * The method parses the given WGSL code an returns a node function.
  49281. *
  49282. * @param {string} source - The WGSL code.
  49283. * @return {WGSLNodeFunction} A node function.
  49284. */
  49285. parseFunction( source ) {
  49286. return new WGSLNodeFunction( source );
  49287. }
  49288. }
  49289. // GPUShaderStage is not defined in browsers not supporting WebGPU
  49290. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  49291. const accessNames = {
  49292. [ NodeAccess.READ_ONLY ]: 'read',
  49293. [ NodeAccess.WRITE_ONLY ]: 'write',
  49294. [ NodeAccess.READ_WRITE ]: 'read_write'
  49295. };
  49296. const wrapNames = {
  49297. [ RepeatWrapping ]: 'repeat',
  49298. [ ClampToEdgeWrapping ]: 'clamp',
  49299. [ MirroredRepeatWrapping ]: 'mirror'
  49300. };
  49301. const gpuShaderStageLib = {
  49302. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  49303. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  49304. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  49305. };
  49306. const supports = {
  49307. instance: true,
  49308. swizzleAssign: false,
  49309. storageBuffer: true
  49310. };
  49311. const wgslFnOpLib = {
  49312. '^^': 'tsl_xor'
  49313. };
  49314. const wgslTypeLib = {
  49315. float: 'f32',
  49316. int: 'i32',
  49317. uint: 'u32',
  49318. bool: 'bool',
  49319. color: 'vec3<f32>',
  49320. vec2: 'vec2<f32>',
  49321. ivec2: 'vec2<i32>',
  49322. uvec2: 'vec2<u32>',
  49323. bvec2: 'vec2<bool>',
  49324. vec3: 'vec3<f32>',
  49325. ivec3: 'vec3<i32>',
  49326. uvec3: 'vec3<u32>',
  49327. bvec3: 'vec3<bool>',
  49328. vec4: 'vec4<f32>',
  49329. ivec4: 'vec4<i32>',
  49330. uvec4: 'vec4<u32>',
  49331. bvec4: 'vec4<bool>',
  49332. mat2: 'mat2x2<f32>',
  49333. mat3: 'mat3x3<f32>',
  49334. mat4: 'mat4x4<f32>'
  49335. };
  49336. const wgslCodeCache = {};
  49337. const wgslPolyfill = {
  49338. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  49339. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  49340. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  49341. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  49342. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  49343. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  49344. 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 ); }' ),
  49345. 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 ); }' ),
  49346. 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 ); }' ),
  49347. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  49348. 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 ); }' ),
  49349. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  49350. biquadraticTexture: new CodeNode( /* wgsl */`
  49351. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  49352. let res = vec2f( iRes );
  49353. let uvScaled = coord * res;
  49354. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  49355. // https://www.shadertoy.com/view/WtyXRy
  49356. let uv = uvWrapping - 0.5;
  49357. let iuv = floor( uv );
  49358. let f = fract( uv );
  49359. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  49360. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  49361. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  49362. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  49363. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  49364. }
  49365. ` )
  49366. };
  49367. const wgslMethods = {
  49368. dFdx: 'dpdx',
  49369. dFdy: '- dpdy',
  49370. mod_float: 'tsl_mod_float',
  49371. mod_vec2: 'tsl_mod_vec2',
  49372. mod_vec3: 'tsl_mod_vec3',
  49373. mod_vec4: 'tsl_mod_vec4',
  49374. equals_bool: 'tsl_equals_bool',
  49375. equals_bvec2: 'tsl_equals_bvec2',
  49376. equals_bvec3: 'tsl_equals_bvec3',
  49377. equals_bvec4: 'tsl_equals_bvec4',
  49378. inversesqrt: 'inverseSqrt',
  49379. bitcast: 'bitcast<f32>'
  49380. };
  49381. //
  49382. let diagnostics = '';
  49383. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  49384. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  49385. }
  49386. /**
  49387. * A node builder targeting WGSL.
  49388. *
  49389. * This module generates WGSL shader code from node materials and also
  49390. * generates the respective bindings and vertex buffer definitions. These
  49391. * data are later used by the renderer to create render and compute pipelines
  49392. * for render objects.
  49393. *
  49394. * @augments NodeBuilder
  49395. */
  49396. class WGSLNodeBuilder extends NodeBuilder {
  49397. /**
  49398. * Constructs a new WGSL node builder renderer.
  49399. *
  49400. * @param {Object3D} object - The 3D object.
  49401. * @param {Renderer} renderer - The renderer.
  49402. */
  49403. constructor( object, renderer ) {
  49404. super( object, renderer, new WGSLNodeParser() );
  49405. /**
  49406. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  49407. * another dictionary which manages UBOs per group ('render','frame','object').
  49408. *
  49409. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  49410. */
  49411. this.uniformGroups = {};
  49412. /**
  49413. * A dictionary that holds for each shader stage a Map of builtins.
  49414. *
  49415. * @type {Object<string,Map<string,Object>>}
  49416. */
  49417. this.builtins = {};
  49418. /**
  49419. * A dictionary that holds for each shader stage a Set of directives.
  49420. *
  49421. * @type {Object<string,Set<string>>}
  49422. */
  49423. this.directives = {};
  49424. /**
  49425. * A map for managing scope arrays. Only relevant for when using
  49426. * {@link WorkgroupInfoNode} in context of compute shaders.
  49427. *
  49428. * @type {Map<string,Object>}
  49429. */
  49430. this.scopedArrays = new Map();
  49431. }
  49432. /**
  49433. * Generates the WGSL snippet for sampled textures.
  49434. *
  49435. * @private
  49436. * @param {Texture} texture - The texture.
  49437. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49438. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49439. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49440. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49441. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49442. * @return {string} The WGSL snippet.
  49443. */
  49444. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49445. if ( shaderStage === 'fragment' ) {
  49446. if ( depthSnippet ) {
  49447. if ( offsetSnippet ) {
  49448. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  49449. }
  49450. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  49451. } else {
  49452. if ( offsetSnippet ) {
  49453. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  49454. }
  49455. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  49456. }
  49457. } else {
  49458. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  49459. }
  49460. }
  49461. /**
  49462. * Generates the WGSL snippet when sampling textures with explicit mip level.
  49463. *
  49464. * @private
  49465. * @param {Texture} texture - The texture.
  49466. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49467. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49468. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49469. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49470. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49471. * @return {string} The WGSL snippet.
  49472. */
  49473. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  49474. if ( this.isUnfilterable( texture ) === false ) {
  49475. if ( offsetSnippet ) {
  49476. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  49477. }
  49478. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  49479. } else if ( this.isFilteredTexture( texture ) ) {
  49480. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  49481. } else {
  49482. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  49483. }
  49484. }
  49485. /**
  49486. * Generates a wrap function used in context of textures.
  49487. *
  49488. * @param {Texture} texture - The texture to generate the function for.
  49489. * @return {string} The name of the generated function.
  49490. */
  49491. generateWrapFunction( texture ) {
  49492. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  49493. let nodeCode = wgslCodeCache[ functionName ];
  49494. if ( nodeCode === undefined ) {
  49495. const includes = [];
  49496. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  49497. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  49498. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  49499. const addWrapSnippet = ( wrap, axis ) => {
  49500. if ( wrap === RepeatWrapping ) {
  49501. includes.push( wgslPolyfill.repeatWrapping_float );
  49502. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  49503. } else if ( wrap === ClampToEdgeWrapping ) {
  49504. includes.push( wgslPolyfill.clampWrapping_float );
  49505. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  49506. } else if ( wrap === MirroredRepeatWrapping ) {
  49507. includes.push( wgslPolyfill.mirrorWrapping_float );
  49508. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  49509. } else {
  49510. code += `\t\tcoord.${ axis }`;
  49511. warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  49512. }
  49513. };
  49514. addWrapSnippet( texture.wrapS, 'x' );
  49515. code += ',\n';
  49516. addWrapSnippet( texture.wrapT, 'y' );
  49517. if ( texture.isData3DTexture ) {
  49518. code += ',\n';
  49519. addWrapSnippet( texture.wrapR, 'z' );
  49520. }
  49521. code += '\n\t);\n\n}\n';
  49522. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  49523. }
  49524. nodeCode.build( this );
  49525. return functionName;
  49526. }
  49527. /**
  49528. * Generates the array declaration string.
  49529. *
  49530. * @param {string} type - The type.
  49531. * @param {?number} [count] - The count.
  49532. * @return {string} The generated value as a shader string.
  49533. */
  49534. generateArrayDeclaration( type, count ) {
  49535. return `array< ${ this.getType( type ) }, ${ count } >`;
  49536. }
  49537. /**
  49538. * Generates a WGSL variable that holds the texture dimension of the given texture.
  49539. * It also returns information about the number of layers (elements) of an arrayed
  49540. * texture as well as the cube face count of cube textures.
  49541. *
  49542. * @param {Texture} texture - The texture to generate the function for.
  49543. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  49544. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49545. * @return {string} The name of the dimension variable.
  49546. */
  49547. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  49548. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  49549. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  49550. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  49551. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  49552. let textureDimensionsParams;
  49553. let dimensionType;
  49554. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  49555. const isMultisampled = primarySamples > 1;
  49556. if ( texture.isData3DTexture ) {
  49557. dimensionType = 'vec3<u32>';
  49558. } else {
  49559. // Regular 2D textures, depth textures, etc.
  49560. dimensionType = 'vec2<u32>';
  49561. }
  49562. // Build parameters string based on texture type and multisampling
  49563. if ( isMultisampled || texture.isStorageTexture ) {
  49564. textureDimensionsParams = textureProperty;
  49565. } else {
  49566. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  49567. }
  49568. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  49569. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  49570. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  49571. textureData.arrayLayerCount = new VarNode(
  49572. new ExpressionNode(
  49573. `textureNumLayers(${textureProperty})`,
  49574. 'u32'
  49575. )
  49576. );
  49577. }
  49578. // For cube textures, we know it's always 6 faces
  49579. if ( texture.isTextureCube ) {
  49580. textureData.cubeFaceCount = new VarNode(
  49581. new ExpressionNode( '6u', 'u32' )
  49582. );
  49583. }
  49584. }
  49585. return textureDimensionNode.build( this );
  49586. }
  49587. /**
  49588. * Generates the WGSL snippet for a manual filtered texture.
  49589. *
  49590. * @param {Texture} texture - The texture.
  49591. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49592. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49593. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49594. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49595. * @return {string} The WGSL snippet.
  49596. */
  49597. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  49598. this._include( 'biquadraticTexture' );
  49599. const wrapFunction = this.generateWrapFunction( texture );
  49600. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  49601. if ( offsetSnippet ) {
  49602. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  49603. }
  49604. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  49605. }
  49606. /**
  49607. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  49608. * Since it's a lookup, no sampling or filtering is applied.
  49609. *
  49610. * @param {Texture} texture - The texture.
  49611. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49612. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49613. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49614. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49615. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49616. * @return {string} The WGSL snippet.
  49617. */
  49618. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  49619. const wrapFunction = this.generateWrapFunction( texture );
  49620. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  49621. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  49622. if ( offsetSnippet ) {
  49623. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  49624. }
  49625. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  49626. return this.generateTextureLoad( texture, textureProperty, coordSnippet, levelSnippet, depthSnippet, null );
  49627. }
  49628. /**
  49629. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  49630. *
  49631. * @param {Texture} texture - The texture.
  49632. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49633. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49634. * @param {?string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49635. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49636. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49637. * @return {string} The WGSL snippet.
  49638. */
  49639. generateTextureLoad( texture, textureProperty, uvIndexSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  49640. if ( levelSnippet === null ) levelSnippet = '0u';
  49641. if ( offsetSnippet ) {
  49642. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  49643. }
  49644. let snippet;
  49645. if ( depthSnippet ) {
  49646. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  49647. } else {
  49648. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  49649. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  49650. snippet += '.x';
  49651. }
  49652. }
  49653. return snippet;
  49654. }
  49655. /**
  49656. * Generates the WGSL snippet that writes a single texel to a texture.
  49657. *
  49658. * @param {Texture} texture - The texture.
  49659. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49660. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49661. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49662. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  49663. * @return {string} The WGSL snippet.
  49664. */
  49665. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  49666. let snippet;
  49667. if ( depthSnippet ) {
  49668. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  49669. } else {
  49670. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  49671. }
  49672. return snippet;
  49673. }
  49674. /**
  49675. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  49676. *
  49677. * @param {Texture} texture - The texture.
  49678. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  49679. */
  49680. isSampleCompare( texture ) {
  49681. return texture.isDepthTexture === true && texture.compareFunction !== null;
  49682. }
  49683. /**
  49684. * Returns `true` if the given texture is unfilterable.
  49685. *
  49686. * @param {Texture} texture - The texture.
  49687. * @return {boolean} Whether the given texture is unfilterable or not.
  49688. */
  49689. isUnfilterable( texture ) {
  49690. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  49691. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  49692. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  49693. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  49694. }
  49695. /**
  49696. * Generates the WGSL snippet for sampling/loading the given texture.
  49697. *
  49698. * @param {Texture} texture - The texture.
  49699. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49700. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49701. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49702. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49703. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49704. * @return {string} The WGSL snippet.
  49705. */
  49706. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49707. let snippet = null;
  49708. if ( this.isUnfilterable( texture ) ) {
  49709. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  49710. } else {
  49711. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  49712. }
  49713. return snippet;
  49714. }
  49715. /**
  49716. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  49717. *
  49718. * @param {Texture} texture - The texture.
  49719. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49720. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49721. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  49722. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49723. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49724. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49725. * @return {string} The WGSL snippet.
  49726. */
  49727. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49728. if ( shaderStage === 'fragment' ) {
  49729. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  49730. if ( offsetSnippet ) {
  49731. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  49732. }
  49733. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  49734. } else {
  49735. error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  49736. }
  49737. }
  49738. /**
  49739. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  49740. * against a reference value.
  49741. *
  49742. * @param {Texture} texture - The texture.
  49743. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49744. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49745. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  49746. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49747. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49748. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49749. * @return {string} The WGSL snippet.
  49750. */
  49751. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49752. if ( shaderStage === 'fragment' ) {
  49753. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  49754. if ( offsetSnippet ) {
  49755. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  49756. }
  49757. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  49758. }
  49759. if ( offsetSnippet ) {
  49760. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  49761. }
  49762. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  49763. } else {
  49764. error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  49765. }
  49766. }
  49767. /**
  49768. * Generates the WGSL snippet when sampling textures with explicit mip level.
  49769. *
  49770. * @param {Texture} texture - The texture.
  49771. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49772. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49773. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49774. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49775. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49776. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49777. * @return {string} The WGSL snippet.
  49778. */
  49779. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  49780. if ( this.isUnfilterable( texture ) === false ) {
  49781. if ( offsetSnippet ) {
  49782. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  49783. }
  49784. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  49785. } else if ( this.isFilteredTexture( texture ) ) {
  49786. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  49787. } else {
  49788. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  49789. }
  49790. }
  49791. /**
  49792. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  49793. *
  49794. * @param {Texture} texture - The texture.
  49795. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49796. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49797. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  49798. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49799. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49800. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49801. * @return {string} The WGSL snippet.
  49802. */
  49803. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49804. if ( shaderStage === 'fragment' ) {
  49805. if ( offsetSnippet ) {
  49806. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  49807. }
  49808. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  49809. } else {
  49810. error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  49811. }
  49812. }
  49813. /**
  49814. * Returns a WGSL snippet that represents the property name of the given node.
  49815. *
  49816. * @param {Node} node - The node.
  49817. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49818. * @return {string} The property name.
  49819. */
  49820. getPropertyName( node, shaderStage = this.shaderStage ) {
  49821. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  49822. if ( shaderStage === 'vertex' ) {
  49823. return `varyings.${ node.name }`;
  49824. }
  49825. } else if ( node.isNodeUniform === true ) {
  49826. const name = node.name;
  49827. const type = node.type;
  49828. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  49829. return name;
  49830. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  49831. if ( this.isCustomStruct( node ) ) {
  49832. return name;
  49833. }
  49834. return name + '.value';
  49835. } else {
  49836. return node.groupNode.name + '.' + name;
  49837. }
  49838. }
  49839. return super.getPropertyName( node );
  49840. }
  49841. /**
  49842. * Returns the output struct name.
  49843. *
  49844. * @return {string} The name of the output struct.
  49845. */
  49846. getOutputStructName() {
  49847. return 'output';
  49848. }
  49849. /**
  49850. * Returns the native shader operator name for a given generic name.
  49851. *
  49852. * @param {string} op - The operator name to resolve.
  49853. * @return {?string} The resolved operator name.
  49854. */
  49855. getFunctionOperator( op ) {
  49856. const fnOp = wgslFnOpLib[ op ];
  49857. if ( fnOp !== undefined ) {
  49858. this._include( fnOp );
  49859. return fnOp;
  49860. }
  49861. return null;
  49862. }
  49863. /**
  49864. * Returns the node access for the given node and shader stage.
  49865. *
  49866. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  49867. * @param {string} shaderStage - The shader stage.
  49868. * @return {string} The node access.
  49869. */
  49870. getNodeAccess( node, shaderStage ) {
  49871. if ( shaderStage !== 'compute' ) {
  49872. if ( node.isAtomic === true ) {
  49873. warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  49874. return NodeAccess.READ_WRITE;
  49875. }
  49876. return NodeAccess.READ_ONLY;
  49877. }
  49878. return node.access;
  49879. }
  49880. /**
  49881. * Returns A WGSL snippet representing the storage access.
  49882. *
  49883. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  49884. * @param {string} shaderStage - The shader stage.
  49885. * @return {string} The WGSL snippet representing the storage access.
  49886. */
  49887. getStorageAccess( node, shaderStage ) {
  49888. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  49889. }
  49890. /**
  49891. * This method is one of the more important ones since it's responsible
  49892. * for generating a matching binding instance for the given uniform node.
  49893. *
  49894. * These bindings are later used in the renderer to create bind groups
  49895. * and layouts.
  49896. *
  49897. * @param {UniformNode} node - The uniform node.
  49898. * @param {string} type - The node data type.
  49899. * @param {string} shaderStage - The shader stage.
  49900. * @param {?string} [name=null] - An optional uniform name.
  49901. * @return {NodeUniform} The node uniform object.
  49902. */
  49903. getUniformFromNode( node, type, shaderStage, name = null ) {
  49904. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  49905. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  49906. if ( nodeData.uniformGPU === undefined ) {
  49907. let uniformGPU;
  49908. const group = node.groupNode;
  49909. const groupName = group.name;
  49910. const bindings = this.getBindGroupArray( groupName, shaderStage );
  49911. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  49912. let texture = null;
  49913. const access = this.getNodeAccess( node, shaderStage );
  49914. if ( type === 'texture' || type === 'storageTexture' ) {
  49915. if ( node.value.is3DTexture === true ) {
  49916. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  49917. } else {
  49918. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  49919. }
  49920. } else if ( type === 'cubeTexture' ) {
  49921. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  49922. } else if ( type === 'texture3D' ) {
  49923. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  49924. }
  49925. texture.store = node.isStorageTextureNode === true;
  49926. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49927. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  49928. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  49929. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49930. bindings.push( sampler, texture );
  49931. uniformGPU = [ sampler, texture ];
  49932. } else {
  49933. bindings.push( texture );
  49934. uniformGPU = [ texture ];
  49935. }
  49936. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  49937. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  49938. const buffer = new bufferClass( node, group );
  49939. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49940. bindings.push( buffer );
  49941. uniformGPU = buffer;
  49942. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  49943. } else {
  49944. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  49945. let uniformsGroup = uniformsStage[ groupName ];
  49946. if ( uniformsGroup === undefined ) {
  49947. uniformsGroup = new NodeUniformsGroup( groupName, group );
  49948. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49949. uniformsStage[ groupName ] = uniformsGroup;
  49950. bindings.push( uniformsGroup );
  49951. }
  49952. uniformGPU = this.getNodeUniform( uniformNode, type );
  49953. uniformsGroup.addUniform( uniformGPU );
  49954. }
  49955. nodeData.uniformGPU = uniformGPU;
  49956. }
  49957. return uniformNode;
  49958. }
  49959. /**
  49960. * This method should be used whenever builtins are required in nodes.
  49961. * The internal builtins data structure will make sure builtins are
  49962. * defined in the WGSL source.
  49963. *
  49964. * @param {string} name - The builtin name.
  49965. * @param {string} property - The property name.
  49966. * @param {string} type - The node data type.
  49967. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49968. * @return {string} The property name.
  49969. */
  49970. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  49971. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  49972. if ( map.has( name ) === false ) {
  49973. map.set( name, {
  49974. name,
  49975. property,
  49976. type
  49977. } );
  49978. }
  49979. return property;
  49980. }
  49981. /**
  49982. * Returns `true` if the given builtin is defined in the given shader stage.
  49983. *
  49984. * @param {string} name - The builtin name.
  49985. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49986. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  49987. */
  49988. hasBuiltin( name, shaderStage = this.shaderStage ) {
  49989. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  49990. }
  49991. /**
  49992. * Returns the vertex index builtin.
  49993. *
  49994. * @return {string} The vertex index.
  49995. */
  49996. getVertexIndex() {
  49997. if ( this.shaderStage === 'vertex' ) {
  49998. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  49999. }
  50000. return 'vertexIndex';
  50001. }
  50002. /**
  50003. * Builds the given shader node.
  50004. *
  50005. * @param {ShaderNodeInternal} shaderNode - The shader node.
  50006. * @return {string} The WGSL function code.
  50007. */
  50008. buildFunctionCode( shaderNode ) {
  50009. const layout = shaderNode.layout;
  50010. const flowData = this.flowShaderNode( shaderNode );
  50011. const parameters = [];
  50012. for ( const input of layout.inputs ) {
  50013. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  50014. }
  50015. //
  50016. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  50017. ${ flowData.vars }
  50018. ${ flowData.code }
  50019. `;
  50020. if ( flowData.result ) {
  50021. code += `\treturn ${ flowData.result };\n`;
  50022. }
  50023. code += '\n}\n';
  50024. //
  50025. return code;
  50026. }
  50027. /**
  50028. * Returns the instance index builtin.
  50029. *
  50030. * @return {string} The instance index.
  50031. */
  50032. getInstanceIndex() {
  50033. if ( this.shaderStage === 'vertex' ) {
  50034. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  50035. }
  50036. return 'instanceIndex';
  50037. }
  50038. /**
  50039. * Returns the invocation local index builtin.
  50040. *
  50041. * @return {string} The invocation local index.
  50042. */
  50043. getInvocationLocalIndex() {
  50044. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  50045. }
  50046. /**
  50047. * Returns the subgroup size builtin.
  50048. *
  50049. * @return {string} The subgroup size.
  50050. */
  50051. getSubgroupSize() {
  50052. this.enableSubGroups();
  50053. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  50054. }
  50055. /**
  50056. * Returns the invocation subgroup index builtin.
  50057. *
  50058. * @return {string} The invocation subgroup index.
  50059. */
  50060. getInvocationSubgroupIndex() {
  50061. this.enableSubGroups();
  50062. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  50063. }
  50064. /**
  50065. * Returns the subgroup index builtin.
  50066. *
  50067. * @return {string} The subgroup index.
  50068. */
  50069. getSubgroupIndex() {
  50070. this.enableSubGroups();
  50071. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  50072. }
  50073. /**
  50074. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  50075. *
  50076. * @return {null} Null.
  50077. */
  50078. getDrawIndex() {
  50079. return null;
  50080. }
  50081. /**
  50082. * Returns the front facing builtin.
  50083. *
  50084. * @return {string} The front facing builtin.
  50085. */
  50086. getFrontFacing() {
  50087. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  50088. }
  50089. /**
  50090. * Returns the frag coord builtin.
  50091. *
  50092. * @return {string} The frag coord builtin.
  50093. */
  50094. getFragCoord() {
  50095. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  50096. }
  50097. /**
  50098. * Returns the frag depth builtin.
  50099. *
  50100. * @return {string} The frag depth builtin.
  50101. */
  50102. getFragDepth() {
  50103. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  50104. }
  50105. /**
  50106. * Returns the clip distances builtin.
  50107. *
  50108. * @return {string} The clip distances builtin.
  50109. */
  50110. getClipDistance() {
  50111. return 'varyings.hw_clip_distances';
  50112. }
  50113. /**
  50114. * Whether to flip texture data along its vertical axis or not.
  50115. *
  50116. * @return {boolean} Returns always `false` in context of WGSL.
  50117. */
  50118. isFlipY() {
  50119. return false;
  50120. }
  50121. /**
  50122. * Enables the given directive for the given shader stage.
  50123. *
  50124. * @param {string} name - The directive name.
  50125. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  50126. */
  50127. enableDirective( name, shaderStage = this.shaderStage ) {
  50128. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  50129. stage.add( name );
  50130. }
  50131. /**
  50132. * Returns the directives of the given shader stage as a WGSL string.
  50133. *
  50134. * @param {string} shaderStage - The shader stage.
  50135. * @return {string} A WGSL snippet that enables the directives of the given stage.
  50136. */
  50137. getDirectives( shaderStage ) {
  50138. const snippets = [];
  50139. const directives = this.directives[ shaderStage ];
  50140. if ( directives !== undefined ) {
  50141. for ( const directive of directives ) {
  50142. snippets.push( `enable ${directive};` );
  50143. }
  50144. }
  50145. return snippets.join( '\n' );
  50146. }
  50147. /**
  50148. * Enables the 'subgroups' directive.
  50149. */
  50150. enableSubGroups() {
  50151. this.enableDirective( 'subgroups' );
  50152. }
  50153. /**
  50154. * Enables the 'subgroups-f16' directive.
  50155. */
  50156. enableSubgroupsF16() {
  50157. this.enableDirective( 'subgroups-f16' );
  50158. }
  50159. /**
  50160. * Enables the 'clip_distances' directive.
  50161. */
  50162. enableClipDistances() {
  50163. this.enableDirective( 'clip_distances' );
  50164. }
  50165. /**
  50166. * Enables the 'f16' directive.
  50167. */
  50168. enableShaderF16() {
  50169. this.enableDirective( 'f16' );
  50170. }
  50171. /**
  50172. * Enables the 'dual_source_blending' directive.
  50173. */
  50174. enableDualSourceBlending() {
  50175. this.enableDirective( 'dual_source_blending' );
  50176. }
  50177. /**
  50178. * Enables hardware clipping.
  50179. *
  50180. * @param {string} planeCount - The clipping plane count.
  50181. */
  50182. enableHardwareClipping( planeCount ) {
  50183. this.enableClipDistances();
  50184. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  50185. }
  50186. /**
  50187. * Returns the builtins of the given shader stage as a WGSL string.
  50188. *
  50189. * @param {string} shaderStage - The shader stage.
  50190. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  50191. */
  50192. getBuiltins( shaderStage ) {
  50193. const snippets = [];
  50194. const builtins = this.builtins[ shaderStage ];
  50195. if ( builtins !== undefined ) {
  50196. for ( const { name, property, type } of builtins.values() ) {
  50197. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  50198. }
  50199. }
  50200. return snippets.join( ',\n\t' );
  50201. }
  50202. /**
  50203. * This method should be used when a new scoped buffer is used in context of
  50204. * compute shaders. It adds the array to the internal data structure which is
  50205. * later used to generate the respective WGSL.
  50206. *
  50207. * @param {string} name - The array name.
  50208. * @param {string} scope - The scope.
  50209. * @param {string} bufferType - The buffer type.
  50210. * @param {string} bufferCount - The buffer count.
  50211. * @return {string} The array name.
  50212. */
  50213. getScopedArray( name, scope, bufferType, bufferCount ) {
  50214. if ( this.scopedArrays.has( name ) === false ) {
  50215. this.scopedArrays.set( name, {
  50216. name,
  50217. scope,
  50218. bufferType,
  50219. bufferCount
  50220. } );
  50221. }
  50222. return name;
  50223. }
  50224. /**
  50225. * Returns the scoped arrays of the given shader stage as a WGSL string.
  50226. *
  50227. * @param {string} shaderStage - The shader stage.
  50228. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  50229. * Returns `undefined` when used in the vertex or fragment stage.
  50230. */
  50231. getScopedArrays( shaderStage ) {
  50232. if ( shaderStage !== 'compute' ) {
  50233. return;
  50234. }
  50235. const snippets = [];
  50236. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  50237. const type = this.getType( bufferType );
  50238. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  50239. }
  50240. return snippets.join( '\n' );
  50241. }
  50242. /**
  50243. * Returns the shader attributes of the given shader stage as a WGSL string.
  50244. *
  50245. * @param {string} shaderStage - The shader stage.
  50246. * @return {string} The WGSL snippet that defines the shader attributes.
  50247. */
  50248. getAttributes( shaderStage ) {
  50249. const snippets = [];
  50250. if ( shaderStage === 'compute' ) {
  50251. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  50252. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  50253. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  50254. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  50255. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  50256. this.enableDirective( 'subgroups', shaderStage );
  50257. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  50258. }
  50259. }
  50260. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  50261. const builtins = this.getBuiltins( 'attribute' );
  50262. if ( builtins ) snippets.push( builtins );
  50263. const attributes = this.getAttributesArray();
  50264. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  50265. const attribute = attributes[ index ];
  50266. const name = attribute.name;
  50267. const type = this.getType( attribute.type );
  50268. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  50269. }
  50270. }
  50271. return snippets.join( ',\n\t' );
  50272. }
  50273. /**
  50274. * Returns the members of the given struct type node as a WGSL string.
  50275. *
  50276. * @param {StructTypeNode} struct - The struct type node.
  50277. * @return {string} The WGSL snippet that defines the struct members.
  50278. */
  50279. getStructMembers( struct ) {
  50280. const snippets = [];
  50281. for ( const member of struct.members ) {
  50282. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  50283. let type = this.getType( member.type );
  50284. if ( member.atomic ) {
  50285. type = 'atomic< ' + type + ' >';
  50286. }
  50287. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  50288. }
  50289. if ( struct.output ) {
  50290. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  50291. }
  50292. return snippets.join( ',\n' );
  50293. }
  50294. /**
  50295. * Returns the structs of the given shader stage as a WGSL string.
  50296. *
  50297. * @param {string} shaderStage - The shader stage.
  50298. * @return {string} The WGSL snippet that defines the structs.
  50299. */
  50300. getStructs( shaderStage ) {
  50301. let result = '';
  50302. const structs = this.structs[ shaderStage ];
  50303. if ( structs.length > 0 ) {
  50304. const snippets = [];
  50305. for ( const struct of structs ) {
  50306. let snippet = `struct ${ struct.name } {\n`;
  50307. snippet += this.getStructMembers( struct );
  50308. snippet += '\n};';
  50309. snippets.push( snippet );
  50310. }
  50311. result = '\n' + snippets.join( '\n\n' ) + '\n';
  50312. }
  50313. return result;
  50314. }
  50315. /**
  50316. * Returns a WGSL string representing a variable.
  50317. *
  50318. * @param {string} type - The variable's type.
  50319. * @param {string} name - The variable's name.
  50320. * @param {?number} [count=null] - The array length.
  50321. * @return {string} The WGSL snippet that defines a variable.
  50322. */
  50323. getVar( type, name, count = null ) {
  50324. let snippet = `var ${ name } : `;
  50325. if ( count !== null ) {
  50326. snippet += this.generateArrayDeclaration( type, count );
  50327. } else {
  50328. snippet += this.getType( type );
  50329. }
  50330. return snippet;
  50331. }
  50332. /**
  50333. * Returns the variables of the given shader stage as a WGSL string.
  50334. *
  50335. * @param {string} shaderStage - The shader stage.
  50336. * @return {string} The WGSL snippet that defines the variables.
  50337. */
  50338. getVars( shaderStage ) {
  50339. const snippets = [];
  50340. const vars = this.vars[ shaderStage ];
  50341. if ( vars !== undefined ) {
  50342. for ( const variable of vars ) {
  50343. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  50344. }
  50345. }
  50346. return `\n${ snippets.join( '\n' ) }\n`;
  50347. }
  50348. /**
  50349. * Returns the varyings of the given shader stage as a WGSL string.
  50350. *
  50351. * @param {string} shaderStage - The shader stage.
  50352. * @return {string} The WGSL snippet that defines the varyings.
  50353. */
  50354. getVaryings( shaderStage ) {
  50355. const snippets = [];
  50356. if ( shaderStage === 'vertex' ) {
  50357. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  50358. }
  50359. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  50360. const varyings = this.varyings;
  50361. const vars = this.vars[ shaderStage ];
  50362. for ( let index = 0; index < varyings.length; index ++ ) {
  50363. const varying = varyings[ index ];
  50364. if ( varying.needsInterpolation ) {
  50365. let attributesSnippet = `@location( ${index} )`;
  50366. if ( varying.interpolationType ) {
  50367. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  50368. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  50369. // Otherwise, optimize interpolation when sensible
  50370. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  50371. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  50372. }
  50373. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  50374. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  50375. vars.push( varying );
  50376. }
  50377. }
  50378. }
  50379. const builtins = this.getBuiltins( shaderStage );
  50380. if ( builtins ) snippets.push( builtins );
  50381. const code = snippets.join( ',\n\t' );
  50382. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  50383. }
  50384. isCustomStruct( nodeUniform ) {
  50385. const attribute = nodeUniform.value;
  50386. const bufferNode = nodeUniform.node;
  50387. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  50388. const isStructArray =
  50389. ( bufferNode.value && bufferNode.value.array ) &&
  50390. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  50391. return isAttributeStructType && ! isStructArray;
  50392. }
  50393. /**
  50394. * Returns the uniforms of the given shader stage as a WGSL string.
  50395. *
  50396. * @param {string} shaderStage - The shader stage.
  50397. * @return {string} The WGSL snippet that defines the uniforms.
  50398. */
  50399. getUniforms( shaderStage ) {
  50400. const uniforms = this.uniforms[ shaderStage ];
  50401. const bindingSnippets = [];
  50402. const bufferSnippets = [];
  50403. const structSnippets = [];
  50404. const uniformGroups = {};
  50405. for ( const uniform of uniforms ) {
  50406. const groupName = uniform.groupNode.name;
  50407. const uniformIndexes = this.bindingsIndexes[ groupName ];
  50408. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  50409. const texture = uniform.node.value;
  50410. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  50411. if ( this.isSampleCompare( texture ) ) {
  50412. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  50413. } else {
  50414. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  50415. }
  50416. }
  50417. let textureType;
  50418. let multisampled = '';
  50419. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  50420. if ( primarySamples > 1 ) {
  50421. multisampled = '_multisampled';
  50422. }
  50423. if ( texture.isCubeTexture === true ) {
  50424. textureType = 'texture_cube<f32>';
  50425. } else if ( texture.isDepthTexture === true ) {
  50426. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  50427. textureType = `texture${ multisampled }_2d<f32>`;
  50428. } else {
  50429. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  50430. }
  50431. } else if ( uniform.node.isStorageTextureNode === true ) {
  50432. const format = getFormat( texture );
  50433. const access = this.getStorageAccess( uniform.node, shaderStage );
  50434. const is3D = uniform.node.value.is3DTexture;
  50435. const isArrayTexture = uniform.node.value.isArrayTexture;
  50436. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  50437. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  50438. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  50439. textureType = 'texture_2d_array<f32>';
  50440. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  50441. textureType = 'texture_3d<f32>';
  50442. } else {
  50443. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  50444. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  50445. }
  50446. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  50447. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  50448. const bufferNode = uniform.node;
  50449. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  50450. const bufferCount = bufferNode.bufferCount;
  50451. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  50452. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  50453. if ( this.isCustomStruct( uniform ) ) {
  50454. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  50455. } else {
  50456. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  50457. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  50458. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  50459. }
  50460. } else {
  50461. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  50462. const groupName = uniform.groupNode.name;
  50463. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  50464. index: uniformIndexes.binding ++,
  50465. id: uniformIndexes.group,
  50466. snippets: []
  50467. } );
  50468. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  50469. }
  50470. }
  50471. for ( const name in uniformGroups ) {
  50472. const group = uniformGroups[ name ];
  50473. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  50474. }
  50475. let code = bindingSnippets.join( '\n' );
  50476. code += bufferSnippets.join( '\n' );
  50477. code += structSnippets.join( '\n' );
  50478. return code;
  50479. }
  50480. /**
  50481. * Controls the code build of the shader stages.
  50482. */
  50483. buildCode() {
  50484. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  50485. this.sortBindingGroups();
  50486. for ( const shaderStage in shadersData ) {
  50487. this.shaderStage = shaderStage;
  50488. const stageData = shadersData[ shaderStage ];
  50489. stageData.uniforms = this.getUniforms( shaderStage );
  50490. stageData.attributes = this.getAttributes( shaderStage );
  50491. stageData.varyings = this.getVaryings( shaderStage );
  50492. stageData.structs = this.getStructs( shaderStage );
  50493. stageData.vars = this.getVars( shaderStage );
  50494. stageData.codes = this.getCodes( shaderStage );
  50495. stageData.directives = this.getDirectives( shaderStage );
  50496. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  50497. //
  50498. let flow = '// code\n\n';
  50499. flow += this.flowCode[ shaderStage ];
  50500. const flowNodes = this.flowNodes[ shaderStage ];
  50501. const mainNode = flowNodes[ flowNodes.length - 1 ];
  50502. const outputNode = mainNode.outputNode;
  50503. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  50504. for ( const node of flowNodes ) {
  50505. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  50506. const slotName = node.name;
  50507. if ( slotName ) {
  50508. if ( flow.length > 0 ) flow += '\n';
  50509. flow += `\t// flow -> ${ slotName }\n`;
  50510. }
  50511. flow += `${ flowSlotData.code }\n\t`;
  50512. if ( node === mainNode && shaderStage !== 'compute' ) {
  50513. flow += '// result\n\n\t';
  50514. if ( shaderStage === 'vertex' ) {
  50515. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  50516. } else if ( shaderStage === 'fragment' ) {
  50517. if ( isOutputStruct ) {
  50518. stageData.returnType = outputNode.getNodeType( this );
  50519. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  50520. flow += `return ${ flowSlotData.result };`;
  50521. } else {
  50522. let structSnippet = '\t@location(0) color: vec4<f32>';
  50523. const builtins = this.getBuiltins( 'output' );
  50524. if ( builtins ) structSnippet += ',\n\t' + builtins;
  50525. stageData.returnType = 'OutputStruct';
  50526. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  50527. stageData.structs += '\nvar<private> output : OutputStruct;';
  50528. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  50529. }
  50530. }
  50531. }
  50532. }
  50533. stageData.flow = flow;
  50534. }
  50535. this.shaderStage = null;
  50536. if ( this.material !== null ) {
  50537. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  50538. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  50539. } else {
  50540. // Early strictly validated in computeNode
  50541. const workgroupSize = this.object.workgroupSize;
  50542. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  50543. }
  50544. }
  50545. /**
  50546. * Returns the native shader method name for a given generic name.
  50547. *
  50548. * @param {string} method - The method name to resolve.
  50549. * @param {?string} [output=null] - An optional output.
  50550. * @return {string} The resolved WGSL method name.
  50551. */
  50552. getMethod( method, output = null ) {
  50553. let wgslMethod;
  50554. if ( output !== null ) {
  50555. wgslMethod = this._getWGSLMethod( method + '_' + output );
  50556. }
  50557. if ( wgslMethod === undefined ) {
  50558. wgslMethod = this._getWGSLMethod( method );
  50559. }
  50560. return wgslMethod || method;
  50561. }
  50562. /**
  50563. * Returns the bitcast method name for a given input and outputType.
  50564. *
  50565. * @param {string} type - The output type to bitcast to.
  50566. * @return {string} The resolved WGSL bitcast invocation.
  50567. */
  50568. getBitcastMethod( type ) {
  50569. const dataType = this.getType( type );
  50570. return `bitcast<${ dataType }>`;
  50571. }
  50572. /**
  50573. * Returns the native snippet for a ternary operation.
  50574. *
  50575. * @param {string} condSnippet - The condition determining which expression gets resolved.
  50576. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  50577. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  50578. * @return {string} The resolved method name.
  50579. */
  50580. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  50581. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  50582. }
  50583. /**
  50584. * Returns the WGSL type of the given node data type.
  50585. *
  50586. * @param {string} type - The node data type.
  50587. * @return {string} The WGSL type.
  50588. */
  50589. getType( type ) {
  50590. return wgslTypeLib[ type ] || type;
  50591. }
  50592. /**
  50593. * Whether the requested feature is available or not.
  50594. *
  50595. * @param {string} name - The requested feature.
  50596. * @return {boolean} Whether the requested feature is supported or not.
  50597. */
  50598. isAvailable( name ) {
  50599. let result = supports[ name ];
  50600. if ( result === undefined ) {
  50601. if ( name === 'float32Filterable' ) {
  50602. result = this.renderer.hasFeature( 'float32-filterable' );
  50603. } else if ( name === 'clipDistance' ) {
  50604. result = this.renderer.hasFeature( 'clip-distances' );
  50605. }
  50606. supports[ name ] = result;
  50607. }
  50608. return result;
  50609. }
  50610. /**
  50611. * Returns the native shader method name for a given generic name.
  50612. *
  50613. * @private
  50614. * @param {string} method - The method name to resolve.
  50615. * @return {string} The resolved WGSL method name.
  50616. */
  50617. _getWGSLMethod( method ) {
  50618. if ( wgslPolyfill[ method ] !== undefined ) {
  50619. this._include( method );
  50620. }
  50621. return wgslMethods[ method ];
  50622. }
  50623. /**
  50624. * Includes the given method name into the current
  50625. * function node.
  50626. *
  50627. * @private
  50628. * @param {string} name - The method name to include.
  50629. * @return {CodeNode} The respective code node.
  50630. */
  50631. _include( name ) {
  50632. const codeNode = wgslPolyfill[ name ];
  50633. codeNode.build( this );
  50634. if ( this.currentFunctionNode !== null ) {
  50635. this.currentFunctionNode.includes.push( codeNode );
  50636. }
  50637. return codeNode;
  50638. }
  50639. /**
  50640. * Returns a WGSL vertex shader based on the given shader data.
  50641. *
  50642. * @private
  50643. * @param {Object} shaderData - The shader data.
  50644. * @return {string} The vertex shader.
  50645. */
  50646. _getWGSLVertexCode( shaderData ) {
  50647. return `${ this.getSignature() }
  50648. // directives
  50649. ${shaderData.directives}
  50650. // structs
  50651. ${shaderData.structs}
  50652. // uniforms
  50653. ${shaderData.uniforms}
  50654. // varyings
  50655. ${shaderData.varyings}
  50656. var<private> varyings : VaryingsStruct;
  50657. // codes
  50658. ${shaderData.codes}
  50659. @vertex
  50660. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  50661. // vars
  50662. ${shaderData.vars}
  50663. // flow
  50664. ${shaderData.flow}
  50665. return varyings;
  50666. }
  50667. `;
  50668. }
  50669. /**
  50670. * Returns a WGSL fragment shader based on the given shader data.
  50671. *
  50672. * @private
  50673. * @param {Object} shaderData - The shader data.
  50674. * @return {string} The vertex shader.
  50675. */
  50676. _getWGSLFragmentCode( shaderData ) {
  50677. return `${ this.getSignature() }
  50678. // global
  50679. ${ diagnostics }
  50680. // structs
  50681. ${shaderData.structs}
  50682. // uniforms
  50683. ${shaderData.uniforms}
  50684. // codes
  50685. ${shaderData.codes}
  50686. @fragment
  50687. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  50688. // vars
  50689. ${shaderData.vars}
  50690. // flow
  50691. ${shaderData.flow}
  50692. }
  50693. `;
  50694. }
  50695. /**
  50696. * Returns a WGSL compute shader based on the given shader data.
  50697. *
  50698. * @private
  50699. * @param {Object} shaderData - The shader data.
  50700. * @param {string} workgroupSize - The workgroup size.
  50701. * @return {string} The vertex shader.
  50702. */
  50703. _getWGSLComputeCode( shaderData, workgroupSize ) {
  50704. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  50705. return `${ this.getSignature() }
  50706. // directives
  50707. ${ shaderData.directives }
  50708. // system
  50709. var<private> instanceIndex : u32;
  50710. // locals
  50711. ${ shaderData.scopedArrays }
  50712. // structs
  50713. ${ shaderData.structs }
  50714. // uniforms
  50715. ${ shaderData.uniforms }
  50716. // codes
  50717. ${ shaderData.codes }
  50718. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  50719. fn main( ${ shaderData.attributes } ) {
  50720. // system
  50721. instanceIndex = globalId.x
  50722. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  50723. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  50724. // vars
  50725. ${ shaderData.vars }
  50726. // flow
  50727. ${ shaderData.flow }
  50728. }
  50729. `;
  50730. }
  50731. /**
  50732. * Returns a WGSL struct based on the given name and variables.
  50733. *
  50734. * @private
  50735. * @param {string} name - The struct name.
  50736. * @param {string} vars - The struct variables.
  50737. * @return {string} The WGSL snippet representing a struct.
  50738. */
  50739. _getWGSLStruct( name, vars ) {
  50740. return `
  50741. struct ${name} {
  50742. ${vars}
  50743. };`;
  50744. }
  50745. /**
  50746. * Returns a WGSL struct binding.
  50747. *
  50748. * @private
  50749. * @param {string} name - The struct name.
  50750. * @param {string} vars - The struct variables.
  50751. * @param {string} access - The access.
  50752. * @param {number} [binding=0] - The binding index.
  50753. * @param {number} [group=0] - The group index.
  50754. * @return {string} The WGSL snippet representing a struct binding.
  50755. */
  50756. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  50757. const structName = name + 'Struct';
  50758. const structSnippet = this._getWGSLStruct( structName, vars );
  50759. return `${structSnippet}
  50760. @binding( ${ binding } ) @group( ${ group } )
  50761. var<${access}> ${ name } : ${ structName };`;
  50762. }
  50763. }
  50764. /**
  50765. * A WebGPU backend utility module with common helpers.
  50766. *
  50767. * @private
  50768. */
  50769. class WebGPUUtils {
  50770. /**
  50771. * Constructs a new utility object.
  50772. *
  50773. * @param {WebGPUBackend} backend - The WebGPU backend.
  50774. */
  50775. constructor( backend ) {
  50776. /**
  50777. * A reference to the WebGPU backend.
  50778. *
  50779. * @type {WebGPUBackend}
  50780. */
  50781. this.backend = backend;
  50782. }
  50783. /**
  50784. * Returns the depth/stencil GPU format for the given render context.
  50785. *
  50786. * @param {RenderContext} renderContext - The render context.
  50787. * @return {string} The depth/stencil GPU texture format.
  50788. */
  50789. getCurrentDepthStencilFormat( renderContext ) {
  50790. let format;
  50791. if ( renderContext.depthTexture !== null ) {
  50792. format = this.getTextureFormatGPU( renderContext.depthTexture );
  50793. } else if ( renderContext.depth && renderContext.stencil ) {
  50794. format = GPUTextureFormat.Depth24PlusStencil8;
  50795. } else if ( renderContext.depth ) {
  50796. format = GPUTextureFormat.Depth24Plus;
  50797. }
  50798. return format;
  50799. }
  50800. /**
  50801. * Returns the GPU format for the given texture.
  50802. *
  50803. * @param {Texture} texture - The texture.
  50804. * @return {string} The GPU texture format.
  50805. */
  50806. getTextureFormatGPU( texture ) {
  50807. return this.backend.get( texture ).format;
  50808. }
  50809. /**
  50810. * Returns an object that defines the multi-sampling state of the given texture.
  50811. *
  50812. * @param {Texture} texture - The texture.
  50813. * @return {Object} The multi-sampling state.
  50814. */
  50815. getTextureSampleData( texture ) {
  50816. let samples;
  50817. if ( texture.isFramebufferTexture ) {
  50818. samples = 1;
  50819. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  50820. const renderer = this.backend.renderer;
  50821. const renderTarget = renderer.getRenderTarget();
  50822. samples = renderTarget ? renderTarget.samples : renderer.samples;
  50823. } else if ( texture.renderTarget ) {
  50824. samples = texture.renderTarget.samples;
  50825. }
  50826. samples = samples || 1;
  50827. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  50828. const primarySamples = isMSAA ? 1 : samples;
  50829. return { samples, primarySamples, isMSAA };
  50830. }
  50831. /**
  50832. * Returns the default color attachment's GPU format of the current render context.
  50833. *
  50834. * @param {RenderContext} renderContext - The render context.
  50835. * @return {string} The GPU texture format of the default color attachment.
  50836. */
  50837. getCurrentColorFormat( renderContext ) {
  50838. let format;
  50839. if ( renderContext.textures !== null ) {
  50840. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  50841. } else {
  50842. format = this.getPreferredCanvasFormat(); // default context format
  50843. }
  50844. return format;
  50845. }
  50846. /**
  50847. * Returns the output color space of the current render context.
  50848. *
  50849. * @param {RenderContext} renderContext - The render context.
  50850. * @return {string} The output color space.
  50851. */
  50852. getCurrentColorSpace( renderContext ) {
  50853. if ( renderContext.textures !== null ) {
  50854. return renderContext.textures[ 0 ].colorSpace;
  50855. }
  50856. return this.backend.renderer.outputColorSpace;
  50857. }
  50858. /**
  50859. * Returns GPU primitive topology for the given object and material.
  50860. *
  50861. * @param {Object3D} object - The 3D object.
  50862. * @param {Material} material - The material.
  50863. * @return {string} The GPU primitive topology.
  50864. */
  50865. getPrimitiveTopology( object, material ) {
  50866. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  50867. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  50868. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  50869. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  50870. }
  50871. /**
  50872. * Returns a modified sample count from the given sample count value.
  50873. *
  50874. * That is required since WebGPU only supports either 1 or 4.
  50875. *
  50876. * @param {number} sampleCount - The input sample count.
  50877. * @return {number} The (potentially updated) output sample count.
  50878. */
  50879. getSampleCount( sampleCount ) {
  50880. return sampleCount >= 4 ? 4 : 1;
  50881. }
  50882. /**
  50883. * Returns the sample count of the given render context.
  50884. *
  50885. * @param {RenderContext} renderContext - The render context.
  50886. * @return {number} The sample count.
  50887. */
  50888. getSampleCountRenderContext( renderContext ) {
  50889. if ( renderContext.textures !== null ) {
  50890. return this.getSampleCount( renderContext.sampleCount );
  50891. }
  50892. return this.getSampleCount( this.backend.renderer.samples );
  50893. }
  50894. /**
  50895. * Returns the preferred canvas format.
  50896. *
  50897. * There is a separate method for this so it's possible to
  50898. * honor edge cases for specific devices.
  50899. *
  50900. * @return {string} The GPU texture format of the canvas.
  50901. */
  50902. getPreferredCanvasFormat() {
  50903. const outputType = this.backend.parameters.outputType;
  50904. if ( outputType === undefined ) {
  50905. return navigator.gpu.getPreferredCanvasFormat();
  50906. } else if ( outputType === UnsignedByteType ) {
  50907. return GPUTextureFormat.BGRA8Unorm;
  50908. } else if ( outputType === HalfFloatType ) {
  50909. return GPUTextureFormat.RGBA16Float;
  50910. } else {
  50911. throw new Error( 'Unsupported outputType' );
  50912. }
  50913. }
  50914. }
  50915. const typedArraysToVertexFormatPrefix = new Map( [
  50916. [ Int8Array, [ 'sint8', 'snorm8' ]],
  50917. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  50918. [ Int16Array, [ 'sint16', 'snorm16' ]],
  50919. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  50920. [ Int32Array, [ 'sint32', 'snorm32' ]],
  50921. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  50922. [ Float32Array, [ 'float32', ]],
  50923. ] );
  50924. if ( typeof Float16Array !== 'undefined' ) {
  50925. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  50926. }
  50927. const typedAttributeToVertexFormatPrefix = new Map( [
  50928. [ Float16BufferAttribute, [ 'float16', ]],
  50929. ] );
  50930. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  50931. [ Int32Array, 'sint32' ],
  50932. [ Int16Array, 'sint32' ], // patch for INT16
  50933. [ Uint32Array, 'uint32' ],
  50934. [ Uint16Array, 'uint32' ], // patch for UINT16
  50935. [ Float32Array, 'float32' ]
  50936. ] );
  50937. /**
  50938. * A WebGPU backend utility module for managing shader attributes.
  50939. *
  50940. * @private
  50941. */
  50942. class WebGPUAttributeUtils {
  50943. /**
  50944. * Constructs a new utility object.
  50945. *
  50946. * @param {WebGPUBackend} backend - The WebGPU backend.
  50947. */
  50948. constructor( backend ) {
  50949. /**
  50950. * A reference to the WebGPU backend.
  50951. *
  50952. * @type {WebGPUBackend}
  50953. */
  50954. this.backend = backend;
  50955. }
  50956. /**
  50957. * Creates the GPU buffer for the given buffer attribute.
  50958. *
  50959. * @param {BufferAttribute} attribute - The buffer attribute.
  50960. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  50961. */
  50962. createAttribute( attribute, usage ) {
  50963. const bufferAttribute = this._getBufferAttribute( attribute );
  50964. const backend = this.backend;
  50965. const bufferData = backend.get( bufferAttribute );
  50966. let buffer = bufferData.buffer;
  50967. if ( buffer === undefined ) {
  50968. const device = backend.device;
  50969. let array = bufferAttribute.array;
  50970. // patch for INT16 and UINT16
  50971. if ( attribute.normalized === false ) {
  50972. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  50973. array = new Int32Array( array );
  50974. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  50975. array = new Uint32Array( array );
  50976. if ( usage & GPUBufferUsage.INDEX ) {
  50977. for ( let i = 0; i < array.length; i ++ ) {
  50978. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  50979. }
  50980. }
  50981. }
  50982. }
  50983. bufferAttribute.array = array;
  50984. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  50985. array = new array.constructor( bufferAttribute.count * 4 );
  50986. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  50987. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  50988. }
  50989. // Update BufferAttribute
  50990. bufferAttribute.itemSize = 4;
  50991. bufferAttribute.array = array;
  50992. bufferData._force3to4BytesAlignment = true;
  50993. }
  50994. // ensure 4 byte alignment
  50995. const byteLength = array.byteLength;
  50996. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  50997. buffer = device.createBuffer( {
  50998. label: bufferAttribute.name,
  50999. size: size,
  51000. usage: usage,
  51001. mappedAtCreation: true
  51002. } );
  51003. new array.constructor( buffer.getMappedRange() ).set( array );
  51004. buffer.unmap();
  51005. bufferData.buffer = buffer;
  51006. }
  51007. }
  51008. /**
  51009. * Updates the GPU buffer of the given buffer attribute.
  51010. *
  51011. * @param {BufferAttribute} attribute - The buffer attribute.
  51012. */
  51013. updateAttribute( attribute ) {
  51014. const bufferAttribute = this._getBufferAttribute( attribute );
  51015. const backend = this.backend;
  51016. const device = backend.device;
  51017. const bufferData = backend.get( bufferAttribute );
  51018. const buffer = backend.get( bufferAttribute ).buffer;
  51019. let array = bufferAttribute.array;
  51020. // if storage buffer ensure 4 byte alignment
  51021. if ( bufferData._force3to4BytesAlignment === true ) {
  51022. array = new array.constructor( bufferAttribute.count * 4 );
  51023. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  51024. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  51025. }
  51026. bufferAttribute.array = array;
  51027. }
  51028. const isTypedArray = this._isTypedArray( array );
  51029. const updateRanges = bufferAttribute.updateRanges;
  51030. if ( updateRanges.length === 0 ) {
  51031. // Not using update ranges
  51032. device.queue.writeBuffer(
  51033. buffer,
  51034. 0,
  51035. array,
  51036. 0
  51037. );
  51038. } else {
  51039. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  51040. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  51041. const range = updateRanges[ i ];
  51042. let dataOffset, size;
  51043. if ( bufferData._force3to4BytesAlignment === true ) {
  51044. const vertexStart = Math.floor( range.start / 3 );
  51045. const vertexCount = Math.ceil( range.count / 3 );
  51046. dataOffset = vertexStart * 4 * byteOffsetFactor;
  51047. size = vertexCount * 4 * byteOffsetFactor;
  51048. } else {
  51049. dataOffset = range.start * byteOffsetFactor;
  51050. size = range.count * byteOffsetFactor;
  51051. }
  51052. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  51053. device.queue.writeBuffer(
  51054. buffer,
  51055. bufferOffset,
  51056. array,
  51057. dataOffset,
  51058. size
  51059. );
  51060. }
  51061. bufferAttribute.clearUpdateRanges();
  51062. }
  51063. }
  51064. /**
  51065. * This method creates the vertex buffer layout data which are
  51066. * require when creating a render pipeline for the given render object.
  51067. *
  51068. * @param {RenderObject} renderObject - The render object.
  51069. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  51070. */
  51071. createShaderVertexBuffers( renderObject ) {
  51072. const attributes = renderObject.getAttributes();
  51073. const vertexBuffers = new Map();
  51074. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  51075. const geometryAttribute = attributes[ slot ];
  51076. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  51077. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  51078. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  51079. if ( vertexBufferLayout === undefined ) {
  51080. let arrayStride, stepMode;
  51081. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  51082. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  51083. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  51084. } else {
  51085. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  51086. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  51087. }
  51088. // patch for INT16 and UINT16
  51089. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  51090. arrayStride = 4;
  51091. }
  51092. vertexBufferLayout = {
  51093. arrayStride,
  51094. attributes: [],
  51095. stepMode
  51096. };
  51097. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  51098. }
  51099. const format = this._getVertexFormat( geometryAttribute );
  51100. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  51101. vertexBufferLayout.attributes.push( {
  51102. shaderLocation: slot,
  51103. offset,
  51104. format
  51105. } );
  51106. }
  51107. return Array.from( vertexBuffers.values() );
  51108. }
  51109. /**
  51110. * Destroys the GPU buffer of the given buffer attribute.
  51111. *
  51112. * @param {BufferAttribute} attribute - The buffer attribute.
  51113. */
  51114. destroyAttribute( attribute ) {
  51115. const backend = this.backend;
  51116. const data = backend.get( this._getBufferAttribute( attribute ) );
  51117. data.buffer.destroy();
  51118. backend.delete( attribute );
  51119. }
  51120. /**
  51121. * This method performs a readback operation by moving buffer data from
  51122. * a storage buffer attribute from the GPU to the CPU.
  51123. *
  51124. * @async
  51125. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  51126. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  51127. */
  51128. async getArrayBufferAsync( attribute ) {
  51129. const backend = this.backend;
  51130. const device = backend.device;
  51131. const data = backend.get( this._getBufferAttribute( attribute ) );
  51132. const bufferGPU = data.buffer;
  51133. const size = bufferGPU.size;
  51134. const readBufferGPU = device.createBuffer( {
  51135. label: `${ attribute.name }_readback`,
  51136. size,
  51137. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51138. } );
  51139. const cmdEncoder = device.createCommandEncoder( {
  51140. label: `readback_encoder_${ attribute.name }`
  51141. } );
  51142. cmdEncoder.copyBufferToBuffer(
  51143. bufferGPU,
  51144. 0,
  51145. readBufferGPU,
  51146. 0,
  51147. size
  51148. );
  51149. const gpuCommands = cmdEncoder.finish();
  51150. device.queue.submit( [ gpuCommands ] );
  51151. await readBufferGPU.mapAsync( GPUMapMode.READ );
  51152. const arrayBuffer = readBufferGPU.getMappedRange();
  51153. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  51154. readBufferGPU.unmap();
  51155. return dstBuffer.buffer;
  51156. }
  51157. /**
  51158. * Returns the vertex format of the given buffer attribute.
  51159. *
  51160. * @private
  51161. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  51162. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  51163. */
  51164. _getVertexFormat( geometryAttribute ) {
  51165. const { itemSize, normalized } = geometryAttribute;
  51166. const ArrayType = geometryAttribute.array.constructor;
  51167. const AttributeType = geometryAttribute.constructor;
  51168. let format;
  51169. if ( itemSize === 1 ) {
  51170. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  51171. } else {
  51172. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  51173. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  51174. if ( prefix ) {
  51175. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  51176. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  51177. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  51178. if ( paddedItemSize % 1 ) {
  51179. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  51180. }
  51181. format = `${prefix}x${paddedItemSize}`;
  51182. }
  51183. }
  51184. if ( ! format ) {
  51185. error( 'WebGPUAttributeUtils: Vertex format not supported yet.' );
  51186. }
  51187. return format;
  51188. }
  51189. /**
  51190. * Returns `true` if the given array is a typed array.
  51191. *
  51192. * @private
  51193. * @param {any} array - The array.
  51194. * @return {boolean} Whether the given array is a typed array or not.
  51195. */
  51196. _isTypedArray( array ) {
  51197. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  51198. }
  51199. /**
  51200. * Utility method for handling interleaved buffer attributes correctly.
  51201. * To process them, their `InterleavedBuffer` is returned.
  51202. *
  51203. * @private
  51204. * @param {BufferAttribute} attribute - The attribute.
  51205. * @return {BufferAttribute|InterleavedBuffer}
  51206. */
  51207. _getBufferAttribute( attribute ) {
  51208. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  51209. return attribute;
  51210. }
  51211. }
  51212. /**
  51213. * A WebGPU backend utility module for managing bindings.
  51214. *
  51215. * When reading the documentation it's helpful to keep in mind that
  51216. * all class definitions starting with 'GPU*' are modules from the
  51217. * WebGPU API. So for example `BindGroup` is a class from the engine
  51218. * whereas `GPUBindGroup` is a class from WebGPU.
  51219. *
  51220. * @private
  51221. */
  51222. class WebGPUBindingUtils {
  51223. /**
  51224. * Constructs a new utility object.
  51225. *
  51226. * @param {WebGPUBackend} backend - The WebGPU backend.
  51227. */
  51228. constructor( backend ) {
  51229. /**
  51230. * A reference to the WebGPU backend.
  51231. *
  51232. * @type {WebGPUBackend}
  51233. */
  51234. this.backend = backend;
  51235. /**
  51236. * A cache for managing bind group layouts.
  51237. *
  51238. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  51239. */
  51240. this.bindGroupLayoutCache = new WeakMap();
  51241. }
  51242. /**
  51243. * Creates a GPU bind group layout for the given bind group.
  51244. *
  51245. * @param {BindGroup} bindGroup - The bind group.
  51246. * @return {GPUBindGroupLayout} The GPU bind group layout.
  51247. */
  51248. createBindingsLayout( bindGroup ) {
  51249. const backend = this.backend;
  51250. const device = backend.device;
  51251. const entries = [];
  51252. let index = 0;
  51253. for ( const binding of bindGroup.bindings ) {
  51254. const bindingGPU = {
  51255. binding: index ++,
  51256. visibility: binding.visibility
  51257. };
  51258. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  51259. const buffer = {}; // GPUBufferBindingLayout
  51260. if ( binding.isStorageBuffer ) {
  51261. if ( binding.visibility & 4 ) {
  51262. // compute
  51263. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  51264. buffer.type = GPUBufferBindingType.Storage;
  51265. } else {
  51266. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  51267. }
  51268. } else {
  51269. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  51270. }
  51271. }
  51272. bindingGPU.buffer = buffer;
  51273. } else if ( binding.isSampledTexture && binding.store ) {
  51274. const storageTexture = {}; // GPUStorageTextureBindingLayout
  51275. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  51276. const access = binding.access;
  51277. if ( access === NodeAccess.READ_WRITE ) {
  51278. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  51279. } else if ( access === NodeAccess.WRITE_ONLY ) {
  51280. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  51281. } else {
  51282. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  51283. }
  51284. if ( binding.texture.isArrayTexture ) {
  51285. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  51286. } else if ( binding.texture.is3DTexture ) {
  51287. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  51288. }
  51289. bindingGPU.storageTexture = storageTexture;
  51290. } else if ( binding.isSampledTexture ) {
  51291. const texture = {}; // GPUTextureBindingLayout
  51292. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  51293. if ( primarySamples > 1 ) {
  51294. texture.multisampled = true;
  51295. if ( ! binding.texture.isDepthTexture ) {
  51296. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  51297. }
  51298. }
  51299. if ( binding.texture.isDepthTexture ) {
  51300. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  51301. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  51302. } else {
  51303. texture.sampleType = GPUTextureSampleType.Depth;
  51304. }
  51305. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  51306. const type = binding.texture.type;
  51307. if ( type === IntType ) {
  51308. texture.sampleType = GPUTextureSampleType.SInt;
  51309. } else if ( type === UnsignedIntType ) {
  51310. texture.sampleType = GPUTextureSampleType.UInt;
  51311. } else if ( type === FloatType ) {
  51312. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  51313. texture.sampleType = GPUTextureSampleType.Float;
  51314. } else {
  51315. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  51316. }
  51317. }
  51318. }
  51319. if ( binding.isSampledCubeTexture ) {
  51320. texture.viewDimension = GPUTextureViewDimension.Cube;
  51321. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  51322. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  51323. } else if ( binding.isSampledTexture3D ) {
  51324. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  51325. }
  51326. bindingGPU.texture = texture;
  51327. } else if ( binding.isSampler ) {
  51328. const sampler = {}; // GPUSamplerBindingLayout
  51329. if ( binding.texture.isDepthTexture ) {
  51330. if ( binding.texture.compareFunction !== null ) {
  51331. sampler.type = GPUSamplerBindingType.Comparison;
  51332. } else if ( backend.compatibilityMode ) {
  51333. sampler.type = GPUSamplerBindingType.NonFiltering;
  51334. }
  51335. }
  51336. bindingGPU.sampler = sampler;
  51337. } else {
  51338. error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  51339. }
  51340. entries.push( bindingGPU );
  51341. }
  51342. return device.createBindGroupLayout( { entries } );
  51343. }
  51344. /**
  51345. * Creates bindings from the given bind group definition.
  51346. *
  51347. * @param {BindGroup} bindGroup - The bind group.
  51348. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51349. * @param {number} cacheIndex - The cache index.
  51350. * @param {number} version - The version.
  51351. */
  51352. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  51353. const { backend, bindGroupLayoutCache } = this;
  51354. const bindingsData = backend.get( bindGroup );
  51355. // setup (static) binding layout and (dynamic) binding group
  51356. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  51357. if ( bindLayoutGPU === undefined ) {
  51358. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  51359. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  51360. }
  51361. let bindGroupGPU;
  51362. if ( cacheIndex > 0 ) {
  51363. if ( bindingsData.groups === undefined ) {
  51364. bindingsData.groups = [];
  51365. bindingsData.versions = [];
  51366. }
  51367. if ( bindingsData.versions[ cacheIndex ] === version ) {
  51368. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  51369. }
  51370. }
  51371. if ( bindGroupGPU === undefined ) {
  51372. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  51373. if ( cacheIndex > 0 ) {
  51374. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  51375. bindingsData.versions[ cacheIndex ] = version;
  51376. }
  51377. }
  51378. bindingsData.group = bindGroupGPU;
  51379. bindingsData.layout = bindLayoutGPU;
  51380. }
  51381. /**
  51382. * Updates a buffer binding.
  51383. *
  51384. * @param {Buffer} binding - The buffer binding to update.
  51385. */
  51386. updateBinding( binding ) {
  51387. const backend = this.backend;
  51388. const device = backend.device;
  51389. const buffer = binding.buffer;
  51390. const bufferGPU = backend.get( binding ).buffer;
  51391. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  51392. }
  51393. /**
  51394. * Creates a GPU bind group for the camera index.
  51395. *
  51396. * @param {Uint32Array} data - The index data.
  51397. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  51398. * @return {GPUBindGroup} The GPU bind group.
  51399. */
  51400. createBindGroupIndex( data, layout ) {
  51401. const backend = this.backend;
  51402. const device = backend.device;
  51403. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  51404. const index = data[ 0 ];
  51405. const buffer = device.createBuffer( {
  51406. label: 'bindingCameraIndex_' + index,
  51407. size: 16, // uint(4) * 4
  51408. usage: usage
  51409. } );
  51410. device.queue.writeBuffer( buffer, 0, data, 0 );
  51411. const entries = [ { binding: 0, resource: { buffer } } ];
  51412. return device.createBindGroup( {
  51413. label: 'bindGroupCameraIndex_' + index,
  51414. layout,
  51415. entries
  51416. } );
  51417. }
  51418. /**
  51419. * Creates a GPU bind group for the given bind group and GPU layout.
  51420. *
  51421. * @param {BindGroup} bindGroup - The bind group.
  51422. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  51423. * @return {GPUBindGroup} The GPU bind group.
  51424. */
  51425. createBindGroup( bindGroup, layoutGPU ) {
  51426. const backend = this.backend;
  51427. const device = backend.device;
  51428. let bindingPoint = 0;
  51429. const entriesGPU = [];
  51430. for ( const binding of bindGroup.bindings ) {
  51431. if ( binding.isUniformBuffer ) {
  51432. const bindingData = backend.get( binding );
  51433. if ( bindingData.buffer === undefined ) {
  51434. const byteLength = binding.byteLength;
  51435. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  51436. const bufferGPU = device.createBuffer( {
  51437. label: 'bindingBuffer_' + binding.name,
  51438. size: byteLength,
  51439. usage: usage
  51440. } );
  51441. bindingData.buffer = bufferGPU;
  51442. }
  51443. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  51444. } else if ( binding.isStorageBuffer ) {
  51445. const bindingData = backend.get( binding );
  51446. if ( bindingData.buffer === undefined ) {
  51447. const attribute = binding.attribute;
  51448. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  51449. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  51450. bindingData.buffer = backend.get( attribute ).buffer;
  51451. }
  51452. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  51453. } else if ( binding.isSampledTexture ) {
  51454. const textureData = backend.get( binding.texture );
  51455. let resourceGPU;
  51456. if ( textureData.externalTexture !== undefined ) {
  51457. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  51458. } else {
  51459. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  51460. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  51461. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  51462. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  51463. }
  51464. propertyName += `-${ mipLevelCount }`;
  51465. resourceGPU = textureData[ propertyName ];
  51466. if ( resourceGPU === undefined ) {
  51467. const aspectGPU = GPUTextureAspect.All;
  51468. let dimensionViewGPU;
  51469. if ( binding.isSampledCubeTexture ) {
  51470. dimensionViewGPU = GPUTextureViewDimension.Cube;
  51471. } else if ( binding.isSampledTexture3D ) {
  51472. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  51473. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  51474. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  51475. } else {
  51476. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  51477. }
  51478. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  51479. }
  51480. }
  51481. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  51482. } else if ( binding.isSampler ) {
  51483. const textureGPU = backend.get( binding.texture );
  51484. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  51485. }
  51486. bindingPoint ++;
  51487. }
  51488. return device.createBindGroup( {
  51489. label: 'bindGroup_' + bindGroup.name,
  51490. layout: layoutGPU,
  51491. entries: entriesGPU
  51492. } );
  51493. }
  51494. }
  51495. /**
  51496. * A WebGPU backend utility module for managing pipelines.
  51497. *
  51498. * @private
  51499. */
  51500. class WebGPUPipelineUtils {
  51501. /**
  51502. * Constructs a new utility object.
  51503. *
  51504. * @param {WebGPUBackend} backend - The WebGPU backend.
  51505. */
  51506. constructor( backend ) {
  51507. /**
  51508. * A reference to the WebGPU backend.
  51509. *
  51510. * @type {WebGPUBackend}
  51511. */
  51512. this.backend = backend;
  51513. /**
  51514. * A Weak Map that tracks the active pipeline for render or compute passes.
  51515. *
  51516. * @private
  51517. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  51518. */
  51519. this._activePipelines = new WeakMap();
  51520. }
  51521. /**
  51522. * Sets the given pipeline for the given pass. The method makes sure to only set the
  51523. * pipeline when necessary.
  51524. *
  51525. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  51526. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  51527. */
  51528. setPipeline( pass, pipeline ) {
  51529. const currentPipeline = this._activePipelines.get( pass );
  51530. if ( currentPipeline !== pipeline ) {
  51531. pass.setPipeline( pipeline );
  51532. this._activePipelines.set( pass, pipeline );
  51533. }
  51534. }
  51535. /**
  51536. * Returns the sample count derived from the given render context.
  51537. *
  51538. * @private
  51539. * @param {RenderContext} renderContext - The render context.
  51540. * @return {number} The sample count.
  51541. */
  51542. _getSampleCount( renderContext ) {
  51543. return this.backend.utils.getSampleCountRenderContext( renderContext );
  51544. }
  51545. /**
  51546. * Creates a render pipeline for the given render object.
  51547. *
  51548. * @param {RenderObject} renderObject - The render object.
  51549. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  51550. */
  51551. createRenderPipeline( renderObject, promises ) {
  51552. const { object, material, geometry, pipeline } = renderObject;
  51553. const { vertexProgram, fragmentProgram } = pipeline;
  51554. const backend = this.backend;
  51555. const device = backend.device;
  51556. const utils = backend.utils;
  51557. const pipelineData = backend.get( pipeline );
  51558. // bind group layouts
  51559. const bindGroupLayouts = [];
  51560. for ( const bindGroup of renderObject.getBindings() ) {
  51561. const bindingsData = backend.get( bindGroup );
  51562. bindGroupLayouts.push( bindingsData.layout );
  51563. }
  51564. // vertex buffers
  51565. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  51566. // blending
  51567. let blending;
  51568. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  51569. blending = this._getBlending( material );
  51570. }
  51571. // stencil
  51572. let stencilFront = {};
  51573. if ( material.stencilWrite === true ) {
  51574. stencilFront = {
  51575. compare: this._getStencilCompare( material ),
  51576. failOp: this._getStencilOperation( material.stencilFail ),
  51577. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  51578. passOp: this._getStencilOperation( material.stencilZPass )
  51579. };
  51580. }
  51581. const colorWriteMask = this._getColorWriteMask( material );
  51582. const targets = [];
  51583. if ( renderObject.context.textures !== null ) {
  51584. const textures = renderObject.context.textures;
  51585. for ( let i = 0; i < textures.length; i ++ ) {
  51586. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  51587. targets.push( {
  51588. format: colorFormat,
  51589. blend: blending,
  51590. writeMask: colorWriteMask
  51591. } );
  51592. }
  51593. } else {
  51594. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  51595. targets.push( {
  51596. format: colorFormat,
  51597. blend: blending,
  51598. writeMask: colorWriteMask
  51599. } );
  51600. }
  51601. const vertexModule = backend.get( vertexProgram ).module;
  51602. const fragmentModule = backend.get( fragmentProgram ).module;
  51603. const primitiveState = this._getPrimitiveState( object, geometry, material );
  51604. const depthCompare = this._getDepthCompare( material );
  51605. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  51606. const sampleCount = this._getSampleCount( renderObject.context );
  51607. const pipelineDescriptor = {
  51608. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  51609. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  51610. fragment: Object.assign( {}, fragmentModule, { targets } ),
  51611. primitive: primitiveState,
  51612. multisample: {
  51613. count: sampleCount,
  51614. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  51615. },
  51616. layout: device.createPipelineLayout( {
  51617. bindGroupLayouts
  51618. } )
  51619. };
  51620. const depthStencil = {};
  51621. const renderDepth = renderObject.context.depth;
  51622. const renderStencil = renderObject.context.stencil;
  51623. if ( renderDepth === true || renderStencil === true ) {
  51624. if ( renderDepth === true ) {
  51625. depthStencil.format = depthStencilFormat;
  51626. depthStencil.depthWriteEnabled = material.depthWrite;
  51627. depthStencil.depthCompare = depthCompare;
  51628. }
  51629. if ( renderStencil === true ) {
  51630. depthStencil.stencilFront = stencilFront;
  51631. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  51632. depthStencil.stencilReadMask = material.stencilFuncMask;
  51633. depthStencil.stencilWriteMask = material.stencilWriteMask;
  51634. }
  51635. if ( material.polygonOffset === true ) {
  51636. depthStencil.depthBias = material.polygonOffsetUnits;
  51637. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  51638. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  51639. }
  51640. pipelineDescriptor.depthStencil = depthStencil;
  51641. }
  51642. if ( promises === null ) {
  51643. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  51644. } else {
  51645. const p = new Promise( ( resolve /*, reject*/ ) => {
  51646. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  51647. pipelineData.pipeline = pipeline;
  51648. resolve();
  51649. } );
  51650. } );
  51651. promises.push( p );
  51652. }
  51653. }
  51654. /**
  51655. * Creates GPU render bundle encoder for the given render context.
  51656. *
  51657. * @param {RenderContext} renderContext - The render context.
  51658. * @param {?string} [label='renderBundleEncoder'] - The label.
  51659. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  51660. */
  51661. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  51662. const backend = this.backend;
  51663. const { utils, device } = backend;
  51664. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  51665. const colorFormat = utils.getCurrentColorFormat( renderContext );
  51666. const sampleCount = this._getSampleCount( renderContext );
  51667. const descriptor = {
  51668. label: label,
  51669. colorFormats: [ colorFormat ],
  51670. depthStencilFormat,
  51671. sampleCount
  51672. };
  51673. return device.createRenderBundleEncoder( descriptor );
  51674. }
  51675. /**
  51676. * Creates a compute pipeline for the given compute node.
  51677. *
  51678. * @param {ComputePipeline} pipeline - The compute pipeline.
  51679. * @param {Array<BindGroup>} bindings - The bindings.
  51680. */
  51681. createComputePipeline( pipeline, bindings ) {
  51682. const backend = this.backend;
  51683. const device = backend.device;
  51684. const computeProgram = backend.get( pipeline.computeProgram ).module;
  51685. const pipelineGPU = backend.get( pipeline );
  51686. // bind group layouts
  51687. const bindGroupLayouts = [];
  51688. for ( const bindingsGroup of bindings ) {
  51689. const bindingsData = backend.get( bindingsGroup );
  51690. bindGroupLayouts.push( bindingsData.layout );
  51691. }
  51692. pipelineGPU.pipeline = device.createComputePipeline( {
  51693. compute: computeProgram,
  51694. layout: device.createPipelineLayout( {
  51695. bindGroupLayouts
  51696. } )
  51697. } );
  51698. }
  51699. /**
  51700. * Returns the blending state as a descriptor object required
  51701. * for the pipeline creation.
  51702. *
  51703. * @private
  51704. * @param {Material} material - The material.
  51705. * @return {Object} The blending state.
  51706. */
  51707. _getBlending( material ) {
  51708. let color, alpha;
  51709. const blending = material.blending;
  51710. const blendSrc = material.blendSrc;
  51711. const blendDst = material.blendDst;
  51712. const blendEquation = material.blendEquation;
  51713. if ( blending === CustomBlending ) {
  51714. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  51715. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  51716. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  51717. color = {
  51718. srcFactor: this._getBlendFactor( blendSrc ),
  51719. dstFactor: this._getBlendFactor( blendDst ),
  51720. operation: this._getBlendOperation( blendEquation )
  51721. };
  51722. alpha = {
  51723. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  51724. dstFactor: this._getBlendFactor( blendDstAlpha ),
  51725. operation: this._getBlendOperation( blendEquationAlpha )
  51726. };
  51727. } else {
  51728. const premultipliedAlpha = material.premultipliedAlpha;
  51729. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  51730. color = {
  51731. srcFactor: srcRGB,
  51732. dstFactor: dstRGB,
  51733. operation: GPUBlendOperation.Add
  51734. };
  51735. alpha = {
  51736. srcFactor: srcAlpha,
  51737. dstFactor: dstAlpha,
  51738. operation: GPUBlendOperation.Add
  51739. };
  51740. };
  51741. if ( premultipliedAlpha ) {
  51742. switch ( blending ) {
  51743. case NormalBlending:
  51744. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  51745. break;
  51746. case AdditiveBlending:
  51747. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  51748. break;
  51749. case SubtractiveBlending:
  51750. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  51751. break;
  51752. case MultiplyBlending:
  51753. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  51754. break;
  51755. }
  51756. } else {
  51757. switch ( blending ) {
  51758. case NormalBlending:
  51759. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  51760. break;
  51761. case AdditiveBlending:
  51762. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  51763. break;
  51764. case SubtractiveBlending:
  51765. error( 'WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  51766. break;
  51767. case MultiplyBlending:
  51768. error( 'WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  51769. break;
  51770. }
  51771. }
  51772. }
  51773. if ( color !== undefined && alpha !== undefined ) {
  51774. return { color, alpha };
  51775. } else {
  51776. error( 'WebGPURenderer: Invalid blending: ', blending );
  51777. }
  51778. }
  51779. /**
  51780. * Returns the GPU blend factor which is required for the pipeline creation.
  51781. *
  51782. * @private
  51783. * @param {number} blend - The blend factor as a three.js constant.
  51784. * @return {string} The GPU blend factor.
  51785. */
  51786. _getBlendFactor( blend ) {
  51787. let blendFactor;
  51788. switch ( blend ) {
  51789. case ZeroFactor:
  51790. blendFactor = GPUBlendFactor.Zero;
  51791. break;
  51792. case OneFactor:
  51793. blendFactor = GPUBlendFactor.One;
  51794. break;
  51795. case SrcColorFactor:
  51796. blendFactor = GPUBlendFactor.Src;
  51797. break;
  51798. case OneMinusSrcColorFactor:
  51799. blendFactor = GPUBlendFactor.OneMinusSrc;
  51800. break;
  51801. case SrcAlphaFactor:
  51802. blendFactor = GPUBlendFactor.SrcAlpha;
  51803. break;
  51804. case OneMinusSrcAlphaFactor:
  51805. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  51806. break;
  51807. case DstColorFactor:
  51808. blendFactor = GPUBlendFactor.Dst;
  51809. break;
  51810. case OneMinusDstColorFactor:
  51811. blendFactor = GPUBlendFactor.OneMinusDst;
  51812. break;
  51813. case DstAlphaFactor:
  51814. blendFactor = GPUBlendFactor.DstAlpha;
  51815. break;
  51816. case OneMinusDstAlphaFactor:
  51817. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  51818. break;
  51819. case SrcAlphaSaturateFactor:
  51820. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  51821. break;
  51822. case BlendColorFactor:
  51823. blendFactor = GPUBlendFactor.Constant;
  51824. break;
  51825. case OneMinusBlendColorFactor:
  51826. blendFactor = GPUBlendFactor.OneMinusConstant;
  51827. break;
  51828. default:
  51829. error( 'WebGPURenderer: Blend factor not supported.', blend );
  51830. }
  51831. return blendFactor;
  51832. }
  51833. /**
  51834. * Returns the GPU stencil compare function which is required for the pipeline creation.
  51835. *
  51836. * @private
  51837. * @param {Material} material - The material.
  51838. * @return {string} The GPU stencil compare function.
  51839. */
  51840. _getStencilCompare( material ) {
  51841. let stencilCompare;
  51842. const stencilFunc = material.stencilFunc;
  51843. switch ( stencilFunc ) {
  51844. case NeverStencilFunc:
  51845. stencilCompare = GPUCompareFunction.Never;
  51846. break;
  51847. case AlwaysStencilFunc:
  51848. stencilCompare = GPUCompareFunction.Always;
  51849. break;
  51850. case LessStencilFunc:
  51851. stencilCompare = GPUCompareFunction.Less;
  51852. break;
  51853. case LessEqualStencilFunc:
  51854. stencilCompare = GPUCompareFunction.LessEqual;
  51855. break;
  51856. case EqualStencilFunc:
  51857. stencilCompare = GPUCompareFunction.Equal;
  51858. break;
  51859. case GreaterEqualStencilFunc:
  51860. stencilCompare = GPUCompareFunction.GreaterEqual;
  51861. break;
  51862. case GreaterStencilFunc:
  51863. stencilCompare = GPUCompareFunction.Greater;
  51864. break;
  51865. case NotEqualStencilFunc:
  51866. stencilCompare = GPUCompareFunction.NotEqual;
  51867. break;
  51868. default:
  51869. error( 'WebGPURenderer: Invalid stencil function.', stencilFunc );
  51870. }
  51871. return stencilCompare;
  51872. }
  51873. /**
  51874. * Returns the GPU stencil operation which is required for the pipeline creation.
  51875. *
  51876. * @private
  51877. * @param {number} op - A three.js constant defining the stencil operation.
  51878. * @return {string} The GPU stencil operation.
  51879. */
  51880. _getStencilOperation( op ) {
  51881. let stencilOperation;
  51882. switch ( op ) {
  51883. case KeepStencilOp:
  51884. stencilOperation = GPUStencilOperation.Keep;
  51885. break;
  51886. case ZeroStencilOp:
  51887. stencilOperation = GPUStencilOperation.Zero;
  51888. break;
  51889. case ReplaceStencilOp:
  51890. stencilOperation = GPUStencilOperation.Replace;
  51891. break;
  51892. case InvertStencilOp:
  51893. stencilOperation = GPUStencilOperation.Invert;
  51894. break;
  51895. case IncrementStencilOp:
  51896. stencilOperation = GPUStencilOperation.IncrementClamp;
  51897. break;
  51898. case DecrementStencilOp:
  51899. stencilOperation = GPUStencilOperation.DecrementClamp;
  51900. break;
  51901. case IncrementWrapStencilOp:
  51902. stencilOperation = GPUStencilOperation.IncrementWrap;
  51903. break;
  51904. case DecrementWrapStencilOp:
  51905. stencilOperation = GPUStencilOperation.DecrementWrap;
  51906. break;
  51907. default:
  51908. error( 'WebGPURenderer: Invalid stencil operation.', stencilOperation );
  51909. }
  51910. return stencilOperation;
  51911. }
  51912. /**
  51913. * Returns the GPU blend operation which is required for the pipeline creation.
  51914. *
  51915. * @private
  51916. * @param {number} blendEquation - A three.js constant defining the blend equation.
  51917. * @return {string} The GPU blend operation.
  51918. */
  51919. _getBlendOperation( blendEquation ) {
  51920. let blendOperation;
  51921. switch ( blendEquation ) {
  51922. case AddEquation:
  51923. blendOperation = GPUBlendOperation.Add;
  51924. break;
  51925. case SubtractEquation:
  51926. blendOperation = GPUBlendOperation.Subtract;
  51927. break;
  51928. case ReverseSubtractEquation:
  51929. blendOperation = GPUBlendOperation.ReverseSubtract;
  51930. break;
  51931. case MinEquation:
  51932. blendOperation = GPUBlendOperation.Min;
  51933. break;
  51934. case MaxEquation:
  51935. blendOperation = GPUBlendOperation.Max;
  51936. break;
  51937. default:
  51938. error( 'WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  51939. }
  51940. return blendOperation;
  51941. }
  51942. /**
  51943. * Returns the primitive state as a descriptor object required
  51944. * for the pipeline creation.
  51945. *
  51946. * @private
  51947. * @param {Object3D} object - The 3D object.
  51948. * @param {BufferGeometry} geometry - The geometry.
  51949. * @param {Material} material - The material.
  51950. * @return {Object} The primitive state.
  51951. */
  51952. _getPrimitiveState( object, geometry, material ) {
  51953. const descriptor = {};
  51954. const utils = this.backend.utils;
  51955. //
  51956. descriptor.topology = utils.getPrimitiveTopology( object, material );
  51957. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  51958. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  51959. }
  51960. //
  51961. let flipSided = ( material.side === BackSide );
  51962. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  51963. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  51964. //
  51965. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  51966. return descriptor;
  51967. }
  51968. /**
  51969. * Returns the GPU color write mask which is required for the pipeline creation.
  51970. *
  51971. * @private
  51972. * @param {Material} material - The material.
  51973. * @return {number} The GPU color write mask.
  51974. */
  51975. _getColorWriteMask( material ) {
  51976. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  51977. }
  51978. /**
  51979. * Returns the GPU depth compare function which is required for the pipeline creation.
  51980. *
  51981. * @private
  51982. * @param {Material} material - The material.
  51983. * @return {string} The GPU depth compare function.
  51984. */
  51985. _getDepthCompare( material ) {
  51986. let depthCompare;
  51987. if ( material.depthTest === false ) {
  51988. depthCompare = GPUCompareFunction.Always;
  51989. } else {
  51990. const depthFunc = material.depthFunc;
  51991. switch ( depthFunc ) {
  51992. case NeverDepth:
  51993. depthCompare = GPUCompareFunction.Never;
  51994. break;
  51995. case AlwaysDepth:
  51996. depthCompare = GPUCompareFunction.Always;
  51997. break;
  51998. case LessDepth:
  51999. depthCompare = GPUCompareFunction.Less;
  52000. break;
  52001. case LessEqualDepth:
  52002. depthCompare = GPUCompareFunction.LessEqual;
  52003. break;
  52004. case EqualDepth:
  52005. depthCompare = GPUCompareFunction.Equal;
  52006. break;
  52007. case GreaterEqualDepth:
  52008. depthCompare = GPUCompareFunction.GreaterEqual;
  52009. break;
  52010. case GreaterDepth:
  52011. depthCompare = GPUCompareFunction.Greater;
  52012. break;
  52013. case NotEqualDepth:
  52014. depthCompare = GPUCompareFunction.NotEqual;
  52015. break;
  52016. default:
  52017. error( 'WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  52018. }
  52019. }
  52020. return depthCompare;
  52021. }
  52022. }
  52023. /**
  52024. * Manages a pool of WebGPU timestamp queries for performance measurement.
  52025. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  52026. *
  52027. * @augments TimestampQueryPool
  52028. */
  52029. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  52030. /**
  52031. * Creates a new WebGPU timestamp query pool.
  52032. *
  52033. * @param {GPUDevice} device - The WebGPU device to create queries on.
  52034. * @param {string} type - The type identifier for this query pool.
  52035. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  52036. */
  52037. constructor( device, type, maxQueries = 2048 ) {
  52038. super( maxQueries );
  52039. this.device = device;
  52040. this.type = type;
  52041. this.querySet = this.device.createQuerySet( {
  52042. type: 'timestamp',
  52043. count: this.maxQueries,
  52044. label: `queryset_global_timestamp_${type}`
  52045. } );
  52046. const bufferSize = this.maxQueries * 8;
  52047. this.resolveBuffer = this.device.createBuffer( {
  52048. label: `buffer_timestamp_resolve_${type}`,
  52049. size: bufferSize,
  52050. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  52051. } );
  52052. this.resultBuffer = this.device.createBuffer( {
  52053. label: `buffer_timestamp_result_${type}`,
  52054. size: bufferSize,
  52055. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52056. } );
  52057. }
  52058. /**
  52059. * Allocates a pair of queries for a given render context.
  52060. *
  52061. * @param {string} uid - A unique identifier for the render context.
  52062. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  52063. */
  52064. allocateQueriesForContext( uid ) {
  52065. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  52066. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  52067. 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() } ).` );
  52068. return null;
  52069. }
  52070. const baseOffset = this.currentQueryIndex;
  52071. this.currentQueryIndex += 2;
  52072. this.queryOffsets.set( uid, baseOffset );
  52073. return baseOffset;
  52074. }
  52075. /**
  52076. * Asynchronously resolves all pending queries and returns the total duration.
  52077. * If there's already a pending resolve operation, returns that promise instead.
  52078. *
  52079. * @async
  52080. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  52081. */
  52082. async resolveQueriesAsync() {
  52083. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  52084. return this.lastValue;
  52085. }
  52086. if ( this.pendingResolve ) {
  52087. return this.pendingResolve;
  52088. }
  52089. this.pendingResolve = this._resolveQueries();
  52090. try {
  52091. const result = await this.pendingResolve;
  52092. return result;
  52093. } finally {
  52094. this.pendingResolve = null;
  52095. }
  52096. }
  52097. /**
  52098. * Internal method to resolve queries and calculate total duration.
  52099. *
  52100. * @async
  52101. * @private
  52102. * @returns {Promise<number>} The total duration in milliseconds.
  52103. */
  52104. async _resolveQueries() {
  52105. if ( this.isDisposed ) {
  52106. return this.lastValue;
  52107. }
  52108. try {
  52109. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  52110. return this.lastValue;
  52111. }
  52112. const currentOffsets = new Map( this.queryOffsets );
  52113. const queryCount = this.currentQueryIndex;
  52114. const bytesUsed = queryCount * 8;
  52115. // Reset state before GPU work
  52116. this.currentQueryIndex = 0;
  52117. this.queryOffsets.clear();
  52118. const commandEncoder = this.device.createCommandEncoder();
  52119. commandEncoder.resolveQuerySet(
  52120. this.querySet,
  52121. 0,
  52122. queryCount,
  52123. this.resolveBuffer,
  52124. 0
  52125. );
  52126. commandEncoder.copyBufferToBuffer(
  52127. this.resolveBuffer,
  52128. 0,
  52129. this.resultBuffer,
  52130. 0,
  52131. bytesUsed
  52132. );
  52133. const commandBuffer = commandEncoder.finish();
  52134. this.device.queue.submit( [ commandBuffer ] );
  52135. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  52136. return this.lastValue;
  52137. }
  52138. // Create and track the mapping operation
  52139. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  52140. if ( this.isDisposed ) {
  52141. if ( this.resultBuffer.mapState === 'mapped' ) {
  52142. this.resultBuffer.unmap();
  52143. }
  52144. return this.lastValue;
  52145. }
  52146. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  52147. let totalDuration = 0;
  52148. for ( const [ , baseOffset ] of currentOffsets ) {
  52149. const startTime = times[ baseOffset ];
  52150. const endTime = times[ baseOffset + 1 ];
  52151. const duration = Number( endTime - startTime ) / 1e6;
  52152. totalDuration += duration;
  52153. }
  52154. this.resultBuffer.unmap();
  52155. this.lastValue = totalDuration;
  52156. return totalDuration;
  52157. } catch ( error ) {
  52158. error( 'Error resolving queries:', error );
  52159. if ( this.resultBuffer.mapState === 'mapped' ) {
  52160. this.resultBuffer.unmap();
  52161. }
  52162. return this.lastValue;
  52163. }
  52164. }
  52165. /**
  52166. * Dispose of the query pool.
  52167. *
  52168. * @async
  52169. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  52170. */
  52171. async dispose() {
  52172. if ( this.isDisposed ) {
  52173. return;
  52174. }
  52175. this.isDisposed = true;
  52176. // Wait for pending resolve operation
  52177. if ( this.pendingResolve ) {
  52178. try {
  52179. await this.pendingResolve;
  52180. } catch ( error ) {
  52181. error( 'Error waiting for pending resolve:', error );
  52182. }
  52183. }
  52184. // Ensure buffer is unmapped before destroying
  52185. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  52186. try {
  52187. this.resultBuffer.unmap();
  52188. } catch ( error ) {
  52189. error( 'Error unmapping buffer:', error );
  52190. }
  52191. }
  52192. // Destroy resources
  52193. if ( this.querySet ) {
  52194. this.querySet.destroy();
  52195. this.querySet = null;
  52196. }
  52197. if ( this.resolveBuffer ) {
  52198. this.resolveBuffer.destroy();
  52199. this.resolveBuffer = null;
  52200. }
  52201. if ( this.resultBuffer ) {
  52202. this.resultBuffer.destroy();
  52203. this.resultBuffer = null;
  52204. }
  52205. this.queryOffsets.clear();
  52206. this.pendingResolve = null;
  52207. }
  52208. }
  52209. /*// debugger tools
  52210. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  52211. //*/
  52212. /**
  52213. * A backend implementation targeting WebGPU.
  52214. *
  52215. * @private
  52216. * @augments Backend
  52217. */
  52218. class WebGPUBackend extends Backend {
  52219. /**
  52220. * WebGPUBackend options.
  52221. *
  52222. * @typedef {Object} WebGPUBackend~Options
  52223. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  52224. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  52225. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  52226. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  52227. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  52228. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  52229. * @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.
  52230. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  52231. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  52232. * @property {string} [powerPreference=undefined] - The power preference.
  52233. * @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.
  52234. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  52235. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  52236. */
  52237. /**
  52238. * Constructs a new WebGPU backend.
  52239. *
  52240. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  52241. */
  52242. constructor( parameters = {} ) {
  52243. super( parameters );
  52244. /**
  52245. * This flag can be used for type testing.
  52246. *
  52247. * @type {boolean}
  52248. * @readonly
  52249. * @default true
  52250. */
  52251. this.isWebGPUBackend = true;
  52252. // some parameters require default values other than "undefined"
  52253. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  52254. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  52255. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  52256. /**
  52257. * Indicates whether the backend is in compatibility mode or not.
  52258. * @type {boolean}
  52259. * @default false
  52260. */
  52261. this.compatibilityMode = this.parameters.compatibilityMode;
  52262. /**
  52263. * A reference to the device.
  52264. *
  52265. * @type {?GPUDevice}
  52266. * @default null
  52267. */
  52268. this.device = null;
  52269. /**
  52270. * A reference to the context.
  52271. *
  52272. * @type {?GPUCanvasContext}
  52273. * @default null
  52274. */
  52275. this.context = null;
  52276. /**
  52277. * A reference to the color attachment of the default framebuffer.
  52278. *
  52279. * @type {?GPUTexture}
  52280. * @default null
  52281. */
  52282. this.colorBuffer = null;
  52283. /**
  52284. * A reference to the default render pass descriptor.
  52285. *
  52286. * @type {?Object}
  52287. * @default null
  52288. */
  52289. this.defaultRenderPassdescriptor = null;
  52290. /**
  52291. * A reference to a backend module holding common utility functions.
  52292. *
  52293. * @type {WebGPUUtils}
  52294. */
  52295. this.utils = new WebGPUUtils( this );
  52296. /**
  52297. * A reference to a backend module holding shader attribute-related
  52298. * utility functions.
  52299. *
  52300. * @type {WebGPUAttributeUtils}
  52301. */
  52302. this.attributeUtils = new WebGPUAttributeUtils( this );
  52303. /**
  52304. * A reference to a backend module holding shader binding-related
  52305. * utility functions.
  52306. *
  52307. * @type {WebGPUBindingUtils}
  52308. */
  52309. this.bindingUtils = new WebGPUBindingUtils( this );
  52310. /**
  52311. * A reference to a backend module holding shader pipeline-related
  52312. * utility functions.
  52313. *
  52314. * @type {WebGPUPipelineUtils}
  52315. */
  52316. this.pipelineUtils = new WebGPUPipelineUtils( this );
  52317. /**
  52318. * A reference to a backend module holding shader texture-related
  52319. * utility functions.
  52320. *
  52321. * @type {WebGPUTextureUtils}
  52322. */
  52323. this.textureUtils = new WebGPUTextureUtils( this );
  52324. /**
  52325. * A map that manages the resolve buffers for occlusion queries.
  52326. *
  52327. * @type {Map<number,GPUBuffer>}
  52328. */
  52329. this.occludedResolveCache = new Map();
  52330. }
  52331. /**
  52332. * Initializes the backend so it is ready for usage.
  52333. *
  52334. * @async
  52335. * @param {Renderer} renderer - The renderer.
  52336. * @return {Promise} A Promise that resolves when the backend has been initialized.
  52337. */
  52338. async init( renderer ) {
  52339. await super.init( renderer );
  52340. //
  52341. const parameters = this.parameters;
  52342. // create the device if it is not passed with parameters
  52343. let device;
  52344. if ( parameters.device === undefined ) {
  52345. const adapterOptions = {
  52346. powerPreference: parameters.powerPreference,
  52347. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  52348. };
  52349. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  52350. if ( adapter === null ) {
  52351. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  52352. }
  52353. // feature support
  52354. const features = Object.values( GPUFeatureName );
  52355. const supportedFeatures = [];
  52356. for ( const name of features ) {
  52357. if ( adapter.features.has( name ) ) {
  52358. supportedFeatures.push( name );
  52359. }
  52360. }
  52361. const deviceDescriptor = {
  52362. requiredFeatures: supportedFeatures,
  52363. requiredLimits: parameters.requiredLimits
  52364. };
  52365. device = await adapter.requestDevice( deviceDescriptor );
  52366. } else {
  52367. device = parameters.device;
  52368. }
  52369. device.lost.then( ( info ) => {
  52370. const deviceLossInfo = {
  52371. api: 'WebGPU',
  52372. message: info.message || 'Unknown reason',
  52373. reason: info.reason || null,
  52374. originalEvent: info
  52375. };
  52376. renderer.onDeviceLost( deviceLossInfo );
  52377. } );
  52378. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  52379. this.device = device;
  52380. this.context = context;
  52381. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  52382. const toneMappingMode = ColorManagement.getToneMappingMode( this.renderer.outputColorSpace );
  52383. this.context.configure( {
  52384. device: this.device,
  52385. format: this.utils.getPreferredCanvasFormat(),
  52386. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  52387. alphaMode: alphaMode,
  52388. toneMapping: {
  52389. mode: toneMappingMode
  52390. }
  52391. } );
  52392. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  52393. this.updateSize();
  52394. }
  52395. /**
  52396. * The coordinate system of the backend.
  52397. *
  52398. * @type {number}
  52399. * @readonly
  52400. */
  52401. get coordinateSystem() {
  52402. return WebGPUCoordinateSystem;
  52403. }
  52404. /**
  52405. * This method performs a readback operation by moving buffer data from
  52406. * a storage buffer attribute from the GPU to the CPU.
  52407. *
  52408. * @async
  52409. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  52410. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  52411. */
  52412. async getArrayBufferAsync( attribute ) {
  52413. return await this.attributeUtils.getArrayBufferAsync( attribute );
  52414. }
  52415. /**
  52416. * Returns the backend's rendering context.
  52417. *
  52418. * @return {GPUCanvasContext} The rendering context.
  52419. */
  52420. getContext() {
  52421. return this.context;
  52422. }
  52423. /**
  52424. * Returns the default render pass descriptor.
  52425. *
  52426. * In WebGPU, the default framebuffer must be configured
  52427. * like custom framebuffers so the backend needs a render
  52428. * pass descriptor even when rendering directly to screen.
  52429. *
  52430. * @private
  52431. * @return {Object} The render pass descriptor.
  52432. */
  52433. _getDefaultRenderPassDescriptor() {
  52434. let descriptor = this.defaultRenderPassdescriptor;
  52435. if ( descriptor === null ) {
  52436. const renderer = this.renderer;
  52437. descriptor = {
  52438. colorAttachments: [ {
  52439. view: null
  52440. } ],
  52441. };
  52442. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  52443. descriptor.depthStencilAttachment = {
  52444. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  52445. };
  52446. }
  52447. const colorAttachment = descriptor.colorAttachments[ 0 ];
  52448. if ( this.renderer.samples > 0 ) {
  52449. colorAttachment.view = this.colorBuffer.createView();
  52450. } else {
  52451. colorAttachment.resolveTarget = undefined;
  52452. }
  52453. this.defaultRenderPassdescriptor = descriptor;
  52454. }
  52455. const colorAttachment = descriptor.colorAttachments[ 0 ];
  52456. if ( this.renderer.samples > 0 ) {
  52457. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  52458. } else {
  52459. colorAttachment.view = this.context.getCurrentTexture().createView();
  52460. }
  52461. return descriptor;
  52462. }
  52463. /**
  52464. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  52465. *
  52466. * @param {RenderContext} renderContext - The render context.
  52467. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  52468. *
  52469. * @private
  52470. */
  52471. _isRenderCameraDepthArray( renderContext ) {
  52472. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  52473. }
  52474. /**
  52475. * Returns the render pass descriptor for the given render context.
  52476. *
  52477. * @private
  52478. * @param {RenderContext} renderContext - The render context.
  52479. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  52480. * @return {Object} The render pass descriptor.
  52481. */
  52482. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  52483. const renderTarget = renderContext.renderTarget;
  52484. const renderTargetData = this.get( renderTarget );
  52485. let descriptors = renderTargetData.descriptors;
  52486. if ( descriptors === undefined ||
  52487. renderTargetData.width !== renderTarget.width ||
  52488. renderTargetData.height !== renderTarget.height ||
  52489. renderTargetData.samples !== renderTarget.samples
  52490. ) {
  52491. descriptors = {};
  52492. renderTargetData.descriptors = descriptors;
  52493. }
  52494. const cacheKey = renderContext.getCacheKey();
  52495. let descriptorBase = descriptors[ cacheKey ];
  52496. if ( descriptorBase === undefined ) {
  52497. const textures = renderContext.textures;
  52498. const textureViews = [];
  52499. let sliceIndex;
  52500. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  52501. for ( let i = 0; i < textures.length; i ++ ) {
  52502. const textureData = this.get( textures[ i ] );
  52503. const viewDescriptor = {
  52504. label: `colorAttachment_${ i }`,
  52505. baseMipLevel: renderContext.activeMipmapLevel,
  52506. mipLevelCount: 1,
  52507. baseArrayLayer: renderContext.activeCubeFace,
  52508. arrayLayerCount: 1,
  52509. dimension: GPUTextureViewDimension.TwoD
  52510. };
  52511. if ( renderTarget.isRenderTarget3D ) {
  52512. sliceIndex = renderContext.activeCubeFace;
  52513. viewDescriptor.baseArrayLayer = 0;
  52514. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  52515. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  52516. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  52517. if ( isRenderCameraDepthArray === true ) {
  52518. const cameras = renderContext.camera.cameras;
  52519. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  52520. const layerViewDescriptor = {
  52521. ...viewDescriptor,
  52522. baseArrayLayer: layer,
  52523. arrayLayerCount: 1,
  52524. dimension: GPUTextureViewDimension.TwoD
  52525. };
  52526. const textureView = textureData.texture.createView( layerViewDescriptor );
  52527. textureViews.push( {
  52528. view: textureView,
  52529. resolveTarget: undefined,
  52530. depthSlice: undefined
  52531. } );
  52532. }
  52533. } else {
  52534. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  52535. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  52536. }
  52537. }
  52538. if ( isRenderCameraDepthArray !== true ) {
  52539. const textureView = textureData.texture.createView( viewDescriptor );
  52540. let view, resolveTarget;
  52541. if ( textureData.msaaTexture !== undefined ) {
  52542. view = textureData.msaaTexture.createView();
  52543. resolveTarget = textureView;
  52544. } else {
  52545. view = textureView;
  52546. resolveTarget = undefined;
  52547. }
  52548. textureViews.push( {
  52549. view,
  52550. resolveTarget,
  52551. depthSlice: sliceIndex
  52552. } );
  52553. }
  52554. }
  52555. descriptorBase = { textureViews };
  52556. if ( renderContext.depth ) {
  52557. const depthTextureData = this.get( renderContext.depthTexture );
  52558. const options = {};
  52559. if ( renderContext.depthTexture.isArrayTexture ) {
  52560. options.dimension = GPUTextureViewDimension.TwoD;
  52561. options.arrayLayerCount = 1;
  52562. options.baseArrayLayer = renderContext.activeCubeFace;
  52563. }
  52564. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  52565. }
  52566. descriptors[ cacheKey ] = descriptorBase;
  52567. renderTargetData.width = renderTarget.width;
  52568. renderTargetData.height = renderTarget.height;
  52569. renderTargetData.samples = renderTarget.samples;
  52570. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  52571. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  52572. }
  52573. const descriptor = {
  52574. colorAttachments: []
  52575. };
  52576. // Apply dynamic properties to cached views
  52577. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  52578. const viewInfo = descriptorBase.textureViews[ i ];
  52579. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  52580. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  52581. clearValue = colorAttachmentsConfig.clearValue;
  52582. }
  52583. descriptor.colorAttachments.push( {
  52584. view: viewInfo.view,
  52585. depthSlice: viewInfo.depthSlice,
  52586. resolveTarget: viewInfo.resolveTarget,
  52587. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  52588. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  52589. clearValue: clearValue
  52590. } );
  52591. }
  52592. if ( descriptorBase.depthStencilView ) {
  52593. descriptor.depthStencilAttachment = {
  52594. view: descriptorBase.depthStencilView
  52595. };
  52596. }
  52597. return descriptor;
  52598. }
  52599. /**
  52600. * This method is executed at the beginning of a render call and prepares
  52601. * the WebGPU state for upcoming render calls
  52602. *
  52603. * @param {RenderContext} renderContext - The render context.
  52604. */
  52605. beginRender( renderContext ) {
  52606. const renderContextData = this.get( renderContext );
  52607. //
  52608. renderContextData.frameCalls = this.renderer.info.render.frameCalls;
  52609. //
  52610. const device = this.device;
  52611. const occlusionQueryCount = renderContext.occlusionQueryCount;
  52612. let occlusionQuerySet;
  52613. if ( occlusionQueryCount > 0 ) {
  52614. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  52615. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  52616. // Get a reference to the array of objects with queries. The renderContextData property
  52617. // can be changed by another render pass before the buffer.mapAsyc() completes.
  52618. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  52619. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  52620. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  52621. //
  52622. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  52623. renderContextData.occlusionQuerySet = occlusionQuerySet;
  52624. renderContextData.occlusionQueryIndex = 0;
  52625. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  52626. renderContextData.lastOcclusionObject = null;
  52627. }
  52628. let descriptor;
  52629. if ( renderContext.textures === null ) {
  52630. descriptor = this._getDefaultRenderPassDescriptor();
  52631. } else {
  52632. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  52633. }
  52634. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  52635. descriptor.occlusionQuerySet = occlusionQuerySet;
  52636. const depthStencilAttachment = descriptor.depthStencilAttachment;
  52637. if ( renderContext.textures !== null ) {
  52638. const colorAttachments = descriptor.colorAttachments;
  52639. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  52640. const colorAttachment = colorAttachments[ i ];
  52641. if ( renderContext.clearColor ) {
  52642. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  52643. colorAttachment.loadOp = GPULoadOp.Clear;
  52644. } else {
  52645. colorAttachment.loadOp = GPULoadOp.Load;
  52646. }
  52647. colorAttachment.storeOp = GPUStoreOp.Store;
  52648. }
  52649. } else {
  52650. const colorAttachment = descriptor.colorAttachments[ 0 ];
  52651. if ( renderContext.clearColor ) {
  52652. colorAttachment.clearValue = renderContext.clearColorValue;
  52653. colorAttachment.loadOp = GPULoadOp.Clear;
  52654. } else {
  52655. colorAttachment.loadOp = GPULoadOp.Load;
  52656. }
  52657. colorAttachment.storeOp = GPUStoreOp.Store;
  52658. }
  52659. //
  52660. if ( renderContext.depth ) {
  52661. if ( renderContext.clearDepth ) {
  52662. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  52663. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  52664. } else {
  52665. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  52666. }
  52667. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52668. }
  52669. if ( renderContext.stencil ) {
  52670. if ( renderContext.clearStencil ) {
  52671. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  52672. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  52673. } else {
  52674. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  52675. }
  52676. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52677. }
  52678. //
  52679. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  52680. // shadow arrays - prepare bundle encoders for each camera in an array camera
  52681. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  52682. const cameras = renderContext.camera.cameras;
  52683. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  52684. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  52685. } else {
  52686. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  52687. }
  52688. // Create bundle encoders for each layer
  52689. renderContextData.bundleEncoders = [];
  52690. renderContextData.bundleSets = [];
  52691. // Create separate bundle encoders for each camera in the array
  52692. for ( let i = 0; i < cameras.length; i ++ ) {
  52693. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  52694. renderContext,
  52695. 'renderBundleArrayCamera_' + i
  52696. );
  52697. // Initialize state tracking for this bundle
  52698. const bundleSets = {
  52699. attributes: {},
  52700. bindingGroups: [],
  52701. pipeline: null,
  52702. index: null
  52703. };
  52704. renderContextData.bundleEncoders.push( bundleEncoder );
  52705. renderContextData.bundleSets.push( bundleSets );
  52706. }
  52707. // We'll complete the bundles in finishRender
  52708. renderContextData.currentPass = null;
  52709. } else {
  52710. const currentPass = encoder.beginRenderPass( descriptor );
  52711. renderContextData.currentPass = currentPass;
  52712. if ( renderContext.viewport ) {
  52713. this.updateViewport( renderContext );
  52714. }
  52715. if ( renderContext.scissor ) {
  52716. const { x, y, width, height } = renderContext.scissorValue;
  52717. currentPass.setScissorRect( x, y, width, height );
  52718. }
  52719. }
  52720. //
  52721. renderContextData.descriptor = descriptor;
  52722. renderContextData.encoder = encoder;
  52723. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52724. renderContextData.renderBundles = [];
  52725. }
  52726. /**
  52727. * This method creates layer descriptors for each camera in an array camera
  52728. * to prepare for rendering to a depth array texture.
  52729. *
  52730. * @param {RenderContext} renderContext - The render context.
  52731. * @param {Object} renderContextData - The render context data.
  52732. * @param {Object} descriptor - The render pass descriptor.
  52733. * @param {ArrayCamera} cameras - The array camera.
  52734. *
  52735. * @private
  52736. */
  52737. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  52738. const depthStencilAttachment = descriptor.depthStencilAttachment;
  52739. renderContextData.layerDescriptors = [];
  52740. const depthTextureData = this.get( renderContext.depthTexture );
  52741. if ( ! depthTextureData.viewCache ) {
  52742. depthTextureData.viewCache = [];
  52743. }
  52744. for ( let i = 0; i < cameras.length; i ++ ) {
  52745. const layerDescriptor = {
  52746. ...descriptor,
  52747. colorAttachments: [ {
  52748. ...descriptor.colorAttachments[ 0 ],
  52749. view: descriptor.colorAttachments[ i ].view
  52750. } ]
  52751. };
  52752. if ( descriptor.depthStencilAttachment ) {
  52753. const layerIndex = i;
  52754. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  52755. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  52756. dimension: GPUTextureViewDimension.TwoD,
  52757. baseArrayLayer: i,
  52758. arrayLayerCount: 1
  52759. } );
  52760. }
  52761. layerDescriptor.depthStencilAttachment = {
  52762. view: depthTextureData.viewCache[ layerIndex ],
  52763. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  52764. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  52765. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  52766. };
  52767. if ( renderContext.stencil ) {
  52768. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  52769. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  52770. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  52771. }
  52772. } else {
  52773. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  52774. }
  52775. renderContextData.layerDescriptors.push( layerDescriptor );
  52776. }
  52777. }
  52778. /**
  52779. * This method updates the layer descriptors for each camera in an array camera
  52780. * to prepare for rendering to a depth array texture.
  52781. *
  52782. * @param {RenderContext} renderContext - The render context.
  52783. * @param {Object} renderContextData - The render context data.
  52784. * @param {ArrayCamera} cameras - The array camera.
  52785. *
  52786. */
  52787. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  52788. for ( let i = 0; i < cameras.length; i ++ ) {
  52789. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  52790. if ( layerDescriptor.depthStencilAttachment ) {
  52791. const depthAttachment = layerDescriptor.depthStencilAttachment;
  52792. if ( renderContext.depth ) {
  52793. if ( renderContext.clearDepth ) {
  52794. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  52795. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  52796. } else {
  52797. depthAttachment.depthLoadOp = GPULoadOp.Load;
  52798. }
  52799. }
  52800. if ( renderContext.stencil ) {
  52801. if ( renderContext.clearStencil ) {
  52802. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  52803. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  52804. } else {
  52805. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  52806. }
  52807. }
  52808. }
  52809. }
  52810. }
  52811. /**
  52812. * This method is executed at the end of a render call and finalizes work
  52813. * after draw calls.
  52814. *
  52815. * @param {RenderContext} renderContext - The render context.
  52816. */
  52817. finishRender( renderContext ) {
  52818. const renderContextData = this.get( renderContext );
  52819. const occlusionQueryCount = renderContext.occlusionQueryCount;
  52820. if ( renderContextData.renderBundles.length > 0 ) {
  52821. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  52822. }
  52823. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  52824. renderContextData.currentPass.endOcclusionQuery();
  52825. }
  52826. // shadow arrays - Execute bundles for each layer
  52827. const encoder = renderContextData.encoder;
  52828. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  52829. const bundles = [];
  52830. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  52831. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  52832. bundles.push( bundleEncoder.finish() );
  52833. }
  52834. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  52835. if ( i < bundles.length ) {
  52836. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  52837. const renderPass = encoder.beginRenderPass( layerDescriptor );
  52838. if ( renderContext.viewport ) {
  52839. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  52840. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  52841. }
  52842. if ( renderContext.scissor ) {
  52843. const { x, y, width, height } = renderContext.scissorValue;
  52844. renderPass.setScissorRect( x, y, width, height );
  52845. }
  52846. renderPass.executeBundles( [ bundles[ i ] ] );
  52847. renderPass.end();
  52848. }
  52849. }
  52850. } else if ( renderContextData.currentPass ) {
  52851. renderContextData.currentPass.end();
  52852. }
  52853. if ( occlusionQueryCount > 0 ) {
  52854. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  52855. //
  52856. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  52857. if ( queryResolveBuffer === undefined ) {
  52858. queryResolveBuffer = this.device.createBuffer(
  52859. {
  52860. size: bufferSize,
  52861. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  52862. }
  52863. );
  52864. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  52865. }
  52866. //
  52867. const readBuffer = this.device.createBuffer(
  52868. {
  52869. size: bufferSize,
  52870. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52871. }
  52872. );
  52873. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  52874. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  52875. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  52876. renderContextData.occlusionQueryBuffer = readBuffer;
  52877. //
  52878. this.resolveOccludedAsync( renderContext );
  52879. }
  52880. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  52881. //
  52882. if ( renderContext.textures !== null ) {
  52883. const textures = renderContext.textures;
  52884. for ( let i = 0; i < textures.length; i ++ ) {
  52885. const texture = textures[ i ];
  52886. if ( texture.generateMipmaps === true ) {
  52887. this.textureUtils.generateMipmaps( texture );
  52888. }
  52889. }
  52890. }
  52891. }
  52892. /**
  52893. * Returns `true` if the given 3D object is fully occluded by other
  52894. * 3D objects in the scene.
  52895. *
  52896. * @param {RenderContext} renderContext - The render context.
  52897. * @param {Object3D} object - The 3D object to test.
  52898. * @return {boolean} Whether the 3D object is fully occluded or not.
  52899. */
  52900. isOccluded( renderContext, object ) {
  52901. const renderContextData = this.get( renderContext );
  52902. return renderContextData.occluded && renderContextData.occluded.has( object );
  52903. }
  52904. /**
  52905. * This method processes the result of occlusion queries and writes it
  52906. * into render context data.
  52907. *
  52908. * @async
  52909. * @param {RenderContext} renderContext - The render context.
  52910. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  52911. */
  52912. async resolveOccludedAsync( renderContext ) {
  52913. const renderContextData = this.get( renderContext );
  52914. // handle occlusion query results
  52915. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  52916. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  52917. const occluded = new WeakSet();
  52918. renderContextData.currentOcclusionQueryObjects = null;
  52919. renderContextData.currentOcclusionQueryBuffer = null;
  52920. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  52921. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  52922. const results = new BigUint64Array( buffer );
  52923. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  52924. if ( results[ i ] === BigInt( 0 ) ) {
  52925. occluded.add( currentOcclusionQueryObjects[ i ] );
  52926. }
  52927. }
  52928. currentOcclusionQueryBuffer.destroy();
  52929. renderContextData.occluded = occluded;
  52930. }
  52931. }
  52932. /**
  52933. * Updates the viewport with the values from the given render context.
  52934. *
  52935. * @param {RenderContext} renderContext - The render context.
  52936. */
  52937. updateViewport( renderContext ) {
  52938. const { currentPass } = this.get( renderContext );
  52939. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  52940. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  52941. }
  52942. /**
  52943. * Returns the clear color and alpha into a single
  52944. * color object.
  52945. *
  52946. * @return {Color4} The clear color.
  52947. */
  52948. getClearColor() {
  52949. const clearColor = super.getClearColor();
  52950. // only premultiply alpha when alphaMode is "premultiplied"
  52951. if ( this.renderer.alpha === true ) {
  52952. clearColor.r *= clearColor.a;
  52953. clearColor.g *= clearColor.a;
  52954. clearColor.b *= clearColor.a;
  52955. }
  52956. return clearColor;
  52957. }
  52958. /**
  52959. * Performs a clear operation.
  52960. *
  52961. * @param {boolean} color - Whether the color buffer should be cleared or not.
  52962. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  52963. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  52964. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  52965. */
  52966. clear( color, depth, stencil, renderTargetContext = null ) {
  52967. const device = this.device;
  52968. const renderer = this.renderer;
  52969. let colorAttachments = [];
  52970. let depthStencilAttachment;
  52971. let clearValue;
  52972. let supportsDepth;
  52973. let supportsStencil;
  52974. if ( color ) {
  52975. const clearColor = this.getClearColor();
  52976. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  52977. }
  52978. if ( renderTargetContext === null ) {
  52979. supportsDepth = renderer.depth;
  52980. supportsStencil = renderer.stencil;
  52981. const descriptor = this._getDefaultRenderPassDescriptor();
  52982. if ( color ) {
  52983. colorAttachments = descriptor.colorAttachments;
  52984. const colorAttachment = colorAttachments[ 0 ];
  52985. colorAttachment.clearValue = clearValue;
  52986. colorAttachment.loadOp = GPULoadOp.Clear;
  52987. colorAttachment.storeOp = GPUStoreOp.Store;
  52988. }
  52989. if ( supportsDepth || supportsStencil ) {
  52990. depthStencilAttachment = descriptor.depthStencilAttachment;
  52991. }
  52992. } else {
  52993. supportsDepth = renderTargetContext.depth;
  52994. supportsStencil = renderTargetContext.stencil;
  52995. const clearConfig = {
  52996. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  52997. clearValue: color ? clearValue : undefined
  52998. };
  52999. if ( supportsDepth ) {
  53000. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  53001. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  53002. clearConfig.depthStoreOp = GPUStoreOp.Store;
  53003. }
  53004. if ( supportsStencil ) {
  53005. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  53006. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  53007. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  53008. }
  53009. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  53010. colorAttachments = descriptor.colorAttachments;
  53011. depthStencilAttachment = descriptor.depthStencilAttachment;
  53012. }
  53013. if ( supportsDepth && depthStencilAttachment ) {
  53014. if ( depth ) {
  53015. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  53016. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  53017. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  53018. } else {
  53019. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53020. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  53021. }
  53022. }
  53023. //
  53024. if ( supportsStencil && depthStencilAttachment ) {
  53025. if ( stencil ) {
  53026. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  53027. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  53028. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  53029. } else {
  53030. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53031. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  53032. }
  53033. }
  53034. //
  53035. const encoder = device.createCommandEncoder( { label: 'clear' } );
  53036. const currentPass = encoder.beginRenderPass( {
  53037. colorAttachments,
  53038. depthStencilAttachment
  53039. } );
  53040. currentPass.end();
  53041. device.queue.submit( [ encoder.finish() ] );
  53042. }
  53043. // compute
  53044. /**
  53045. * This method is executed at the beginning of a compute call and
  53046. * prepares the state for upcoming compute tasks.
  53047. *
  53048. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  53049. */
  53050. beginCompute( computeGroup ) {
  53051. const groupGPU = this.get( computeGroup );
  53052. //
  53053. groupGPU.frameCalls = this.renderer.info.compute.frameCalls;
  53054. //
  53055. const descriptor = {
  53056. label: 'computeGroup_' + computeGroup.id
  53057. };
  53058. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  53059. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  53060. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  53061. }
  53062. /**
  53063. * Executes a compute command for the given compute node.
  53064. *
  53065. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  53066. * @param {Node} computeNode - The compute node.
  53067. * @param {Array<BindGroup>} bindings - The bindings.
  53068. * @param {ComputePipeline} pipeline - The compute pipeline.
  53069. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  53070. */
  53071. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  53072. const computeNodeData = this.get( computeNode );
  53073. const { passEncoderGPU } = this.get( computeGroup );
  53074. // pipeline
  53075. const pipelineGPU = this.get( pipeline ).pipeline;
  53076. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  53077. // bind groups
  53078. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  53079. const bindGroup = bindings[ i ];
  53080. const bindingsData = this.get( bindGroup );
  53081. passEncoderGPU.setBindGroup( i, bindingsData.group );
  53082. }
  53083. let dispatchSize;
  53084. if ( dispatchSizeOrCount === null ) {
  53085. dispatchSizeOrCount = computeNode.count;
  53086. }
  53087. if ( typeof dispatchSizeOrCount === 'number' ) {
  53088. // If a single number is given, we calculate the dispatch size based on the workgroup size
  53089. const count = dispatchSizeOrCount;
  53090. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  53091. // cache dispatch size to avoid recalculating it every time
  53092. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  53093. computeNodeData.count = count;
  53094. const workgroupSize = computeNode.workgroupSize;
  53095. let size = workgroupSize[ 0 ];
  53096. for ( let i = 1; i < workgroupSize.length; i ++ )
  53097. size *= workgroupSize[ i ];
  53098. const dispatchCount = Math.ceil( count / size );
  53099. //
  53100. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  53101. dispatchSize = [ dispatchCount, 1, 1 ];
  53102. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  53103. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  53104. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  53105. }
  53106. computeNodeData.dispatchSize = dispatchSize;
  53107. }
  53108. dispatchSize = computeNodeData.dispatchSize;
  53109. } else {
  53110. dispatchSize = dispatchSizeOrCount;
  53111. }
  53112. //
  53113. passEncoderGPU.dispatchWorkgroups(
  53114. dispatchSize[ 0 ],
  53115. dispatchSize[ 1 ] || 1,
  53116. dispatchSize[ 2 ] || 1
  53117. );
  53118. }
  53119. /**
  53120. * This method is executed at the end of a compute call and
  53121. * finalizes work after compute tasks.
  53122. *
  53123. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  53124. */
  53125. finishCompute( computeGroup ) {
  53126. const groupData = this.get( computeGroup );
  53127. groupData.passEncoderGPU.end();
  53128. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  53129. }
  53130. /**
  53131. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  53132. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  53133. *
  53134. * @async
  53135. * @return {Promise} A Promise that resolves when synchronization has been finished.
  53136. */
  53137. async waitForGPU() {
  53138. await this.device.queue.onSubmittedWorkDone();
  53139. }
  53140. // render object
  53141. /**
  53142. * Executes a draw command for the given render object.
  53143. *
  53144. * @param {RenderObject} renderObject - The render object to draw.
  53145. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  53146. */
  53147. draw( renderObject, info ) {
  53148. const { object, material, context, pipeline } = renderObject;
  53149. const bindings = renderObject.getBindings();
  53150. const renderContextData = this.get( context );
  53151. const pipelineGPU = this.get( pipeline ).pipeline;
  53152. const index = renderObject.getIndex();
  53153. const hasIndex = ( index !== null );
  53154. const drawParams = renderObject.getDrawParameters();
  53155. if ( drawParams === null ) return;
  53156. // pipeline
  53157. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  53158. // pipeline
  53159. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  53160. currentSets.pipeline = pipelineGPU;
  53161. // bind groups
  53162. const currentBindingGroups = currentSets.bindingGroups;
  53163. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  53164. const bindGroup = bindings[ i ];
  53165. const bindingsData = this.get( bindGroup );
  53166. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  53167. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  53168. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  53169. }
  53170. }
  53171. // attributes
  53172. // index
  53173. if ( hasIndex === true ) {
  53174. if ( currentSets.index !== index ) {
  53175. const buffer = this.get( index ).buffer;
  53176. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  53177. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  53178. currentSets.index = index;
  53179. }
  53180. }
  53181. // vertex buffers
  53182. const vertexBuffers = renderObject.getVertexBuffers();
  53183. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  53184. const vertexBuffer = vertexBuffers[ i ];
  53185. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  53186. const buffer = this.get( vertexBuffer ).buffer;
  53187. passEncoderGPU.setVertexBuffer( i, buffer );
  53188. currentSets.attributes[ i ] = vertexBuffer;
  53189. }
  53190. }
  53191. // stencil
  53192. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  53193. passEncoderGPU.setStencilReference( material.stencilRef );
  53194. renderContextData.currentStencilRef = material.stencilRef;
  53195. }
  53196. };
  53197. // Define draw function
  53198. const draw = ( passEncoderGPU, currentSets ) => {
  53199. setPipelineAndBindings( passEncoderGPU, currentSets );
  53200. if ( object.isBatchedMesh === true ) {
  53201. const starts = object._multiDrawStarts;
  53202. const counts = object._multiDrawCounts;
  53203. const drawCount = object._multiDrawCount;
  53204. const drawInstances = object._multiDrawInstances;
  53205. if ( drawInstances !== null ) {
  53206. // @deprecated, r174
  53207. warnOnce( 'WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  53208. }
  53209. for ( let i = 0; i < drawCount; i ++ ) {
  53210. const count = drawInstances ? drawInstances[ i ] : 1;
  53211. const firstInstance = count > 1 ? 0 : i;
  53212. if ( hasIndex === true ) {
  53213. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  53214. } else {
  53215. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  53216. }
  53217. info.update( object, counts[ i ], count );
  53218. }
  53219. } else if ( hasIndex === true ) {
  53220. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  53221. const indirect = renderObject.getIndirect();
  53222. if ( indirect !== null ) {
  53223. const buffer = this.get( indirect ).buffer;
  53224. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  53225. } else {
  53226. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  53227. }
  53228. info.update( object, indexCount, instanceCount );
  53229. } else {
  53230. const { vertexCount, instanceCount, firstVertex } = drawParams;
  53231. const indirect = renderObject.getIndirect();
  53232. if ( indirect !== null ) {
  53233. const buffer = this.get( indirect ).buffer;
  53234. passEncoderGPU.drawIndirect( buffer, 0 );
  53235. } else {
  53236. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  53237. }
  53238. info.update( object, vertexCount, instanceCount );
  53239. }
  53240. };
  53241. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  53242. const cameraData = this.get( renderObject.camera );
  53243. const cameras = renderObject.camera.cameras;
  53244. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  53245. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  53246. const bindingsData = this.get( cameraIndex );
  53247. const indexesGPU = [];
  53248. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  53249. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  53250. data[ 0 ] = i;
  53251. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  53252. indexesGPU.push( bindGroupIndex );
  53253. }
  53254. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  53255. }
  53256. const pixelRatio = this.renderer.getPixelRatio();
  53257. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  53258. const subCamera = cameras[ i ];
  53259. if ( object.layers.test( subCamera.layers ) ) {
  53260. const vp = subCamera.viewport;
  53261. let pass = renderContextData.currentPass;
  53262. let sets = renderContextData.currentSets;
  53263. if ( renderContextData.bundleEncoders ) {
  53264. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  53265. const bundleSets = renderContextData.bundleSets[ i ];
  53266. pass = bundleEncoder;
  53267. sets = bundleSets;
  53268. }
  53269. if ( vp ) {
  53270. pass.setViewport(
  53271. Math.floor( vp.x * pixelRatio ),
  53272. Math.floor( vp.y * pixelRatio ),
  53273. Math.floor( vp.width * pixelRatio ),
  53274. Math.floor( vp.height * pixelRatio ),
  53275. context.viewportValue.minDepth,
  53276. context.viewportValue.maxDepth
  53277. );
  53278. }
  53279. // Set camera index binding for this layer
  53280. if ( cameraIndex && cameraData.indexesGPU ) {
  53281. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  53282. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  53283. }
  53284. draw( pass, sets );
  53285. }
  53286. }
  53287. } else {
  53288. // Regular single camera rendering
  53289. if ( renderContextData.currentPass ) {
  53290. // Handle occlusion queries
  53291. if ( renderContextData.occlusionQuerySet !== undefined ) {
  53292. const lastObject = renderContextData.lastOcclusionObject;
  53293. if ( lastObject !== object ) {
  53294. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  53295. renderContextData.currentPass.endOcclusionQuery();
  53296. renderContextData.occlusionQueryIndex ++;
  53297. }
  53298. if ( object.occlusionTest === true ) {
  53299. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  53300. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  53301. }
  53302. renderContextData.lastOcclusionObject = object;
  53303. }
  53304. }
  53305. draw( renderContextData.currentPass, renderContextData.currentSets );
  53306. }
  53307. }
  53308. }
  53309. // cache key
  53310. /**
  53311. * Returns `true` if the render pipeline requires an update.
  53312. *
  53313. * @param {RenderObject} renderObject - The render object.
  53314. * @return {boolean} Whether the render pipeline requires an update or not.
  53315. */
  53316. needsRenderUpdate( renderObject ) {
  53317. const data = this.get( renderObject );
  53318. const { object, material } = renderObject;
  53319. const utils = this.utils;
  53320. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  53321. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  53322. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  53323. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  53324. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  53325. let needsUpdate = false;
  53326. if ( data.material !== material || data.materialVersion !== material.version ||
  53327. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  53328. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  53329. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  53330. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  53331. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  53332. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  53333. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  53334. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  53335. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  53336. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  53337. data.primitiveTopology !== primitiveTopology ||
  53338. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  53339. ) {
  53340. data.material = material; data.materialVersion = material.version;
  53341. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  53342. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  53343. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  53344. data.colorWrite = material.colorWrite;
  53345. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  53346. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  53347. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  53348. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  53349. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  53350. data.sampleCount = sampleCount;
  53351. data.colorSpace = colorSpace;
  53352. data.colorFormat = colorFormat;
  53353. data.depthStencilFormat = depthStencilFormat;
  53354. data.primitiveTopology = primitiveTopology;
  53355. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  53356. needsUpdate = true;
  53357. }
  53358. return needsUpdate;
  53359. }
  53360. /**
  53361. * Returns a cache key that is used to identify render pipelines.
  53362. *
  53363. * @param {RenderObject} renderObject - The render object.
  53364. * @return {string} The cache key.
  53365. */
  53366. getRenderCacheKey( renderObject ) {
  53367. const { object, material } = renderObject;
  53368. const utils = this.utils;
  53369. const renderContext = renderObject.context;
  53370. // meshes with negative scale have a different frontFace render pipeline
  53371. // descriptor value so the following must be honored in the cache key
  53372. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  53373. return [
  53374. material.transparent, material.blending, material.premultipliedAlpha,
  53375. material.blendSrc, material.blendDst, material.blendEquation,
  53376. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  53377. material.colorWrite,
  53378. material.depthWrite, material.depthTest, material.depthFunc,
  53379. material.stencilWrite, material.stencilFunc,
  53380. material.stencilFail, material.stencilZFail, material.stencilZPass,
  53381. material.stencilFuncMask, material.stencilWriteMask,
  53382. material.side,
  53383. frontFaceCW,
  53384. utils.getSampleCountRenderContext( renderContext ),
  53385. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  53386. utils.getPrimitiveTopology( object, material ),
  53387. renderObject.getGeometryCacheKey(),
  53388. renderObject.clippingContextCacheKey
  53389. ].join();
  53390. }
  53391. // textures
  53392. /**
  53393. * Creates a GPU sampler for the given texture.
  53394. *
  53395. * @param {Texture} texture - The texture to create the sampler for.
  53396. */
  53397. createSampler( texture ) {
  53398. this.textureUtils.createSampler( texture );
  53399. }
  53400. /**
  53401. * Destroys the GPU sampler for the given texture.
  53402. *
  53403. * @param {Texture} texture - The texture to destroy the sampler for.
  53404. */
  53405. destroySampler( texture ) {
  53406. this.textureUtils.destroySampler( texture );
  53407. }
  53408. /**
  53409. * Creates a default texture for the given texture that can be used
  53410. * as a placeholder until the actual texture is ready for usage.
  53411. *
  53412. * @param {Texture} texture - The texture to create a default texture for.
  53413. */
  53414. createDefaultTexture( texture ) {
  53415. this.textureUtils.createDefaultTexture( texture );
  53416. }
  53417. /**
  53418. * Defines a texture on the GPU for the given texture object.
  53419. *
  53420. * @param {Texture} texture - The texture.
  53421. * @param {Object} [options={}] - Optional configuration parameter.
  53422. */
  53423. createTexture( texture, options ) {
  53424. this.textureUtils.createTexture( texture, options );
  53425. }
  53426. /**
  53427. * Uploads the updated texture data to the GPU.
  53428. *
  53429. * @param {Texture} texture - The texture.
  53430. * @param {Object} [options={}] - Optional configuration parameter.
  53431. */
  53432. updateTexture( texture, options ) {
  53433. this.textureUtils.updateTexture( texture, options );
  53434. }
  53435. /**
  53436. * Generates mipmaps for the given texture.
  53437. *
  53438. * @param {Texture} texture - The texture.
  53439. */
  53440. generateMipmaps( texture ) {
  53441. this.textureUtils.generateMipmaps( texture );
  53442. }
  53443. /**
  53444. * Destroys the GPU data for the given texture object.
  53445. *
  53446. * @param {Texture} texture - The texture.
  53447. * @param {boolean} [isDefaultTexture=false] - Whether the texture uses a default GPU texture or not.
  53448. */
  53449. destroyTexture( texture, isDefaultTexture = false ) {
  53450. this.textureUtils.destroyTexture( texture, isDefaultTexture );
  53451. }
  53452. /**
  53453. * Returns texture data as a typed array.
  53454. *
  53455. * @async
  53456. * @param {Texture} texture - The texture to copy.
  53457. * @param {number} x - The x coordinate of the copy origin.
  53458. * @param {number} y - The y coordinate of the copy origin.
  53459. * @param {number} width - The width of the copy.
  53460. * @param {number} height - The height of the copy.
  53461. * @param {number} faceIndex - The face index.
  53462. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  53463. */
  53464. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  53465. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  53466. }
  53467. /**
  53468. * Inits a time stamp query for the given render context.
  53469. *
  53470. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  53471. * @param {number} uid - Unique id for the context (e.g. render context id).
  53472. * @param {Object} descriptor - The query descriptor.
  53473. */
  53474. initTimestampQuery( type, uid, descriptor ) {
  53475. if ( ! this.trackTimestamp ) return;
  53476. if ( ! this.timestampQueryPool[ type ] ) {
  53477. // TODO: Variable maxQueries?
  53478. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  53479. }
  53480. const timestampQueryPool = this.timestampQueryPool[ type ];
  53481. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  53482. descriptor.timestampWrites = {
  53483. querySet: timestampQueryPool.querySet,
  53484. beginningOfPassWriteIndex: baseOffset,
  53485. endOfPassWriteIndex: baseOffset + 1,
  53486. };
  53487. }
  53488. // node builder
  53489. /**
  53490. * Returns a node builder for the given render object.
  53491. *
  53492. * @param {RenderObject} object - The render object.
  53493. * @param {Renderer} renderer - The renderer.
  53494. * @return {WGSLNodeBuilder} The node builder.
  53495. */
  53496. createNodeBuilder( object, renderer ) {
  53497. return new WGSLNodeBuilder( object, renderer );
  53498. }
  53499. // program
  53500. /**
  53501. * Creates a shader program from the given programmable stage.
  53502. *
  53503. * @param {ProgrammableStage} program - The programmable stage.
  53504. */
  53505. createProgram( program ) {
  53506. const programGPU = this.get( program );
  53507. programGPU.module = {
  53508. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  53509. entryPoint: 'main'
  53510. };
  53511. }
  53512. /**
  53513. * Destroys the shader program of the given programmable stage.
  53514. *
  53515. * @param {ProgrammableStage} program - The programmable stage.
  53516. */
  53517. destroyProgram( program ) {
  53518. this.delete( program );
  53519. }
  53520. // pipelines
  53521. /**
  53522. * Creates a render pipeline for the given render object.
  53523. *
  53524. * @param {RenderObject} renderObject - The render object.
  53525. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  53526. */
  53527. createRenderPipeline( renderObject, promises ) {
  53528. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  53529. }
  53530. /**
  53531. * Creates a compute pipeline for the given compute node.
  53532. *
  53533. * @param {ComputePipeline} computePipeline - The compute pipeline.
  53534. * @param {Array<BindGroup>} bindings - The bindings.
  53535. */
  53536. createComputePipeline( computePipeline, bindings ) {
  53537. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  53538. }
  53539. /**
  53540. * Prepares the state for encoding render bundles.
  53541. *
  53542. * @param {RenderContext} renderContext - The render context.
  53543. */
  53544. beginBundle( renderContext ) {
  53545. const renderContextData = this.get( renderContext );
  53546. renderContextData._currentPass = renderContextData.currentPass;
  53547. renderContextData._currentSets = renderContextData.currentSets;
  53548. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53549. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  53550. }
  53551. /**
  53552. * After processing render bundles this method finalizes related work.
  53553. *
  53554. * @param {RenderContext} renderContext - The render context.
  53555. * @param {RenderBundle} bundle - The render bundle.
  53556. */
  53557. finishBundle( renderContext, bundle ) {
  53558. const renderContextData = this.get( renderContext );
  53559. const bundleEncoder = renderContextData.currentPass;
  53560. const bundleGPU = bundleEncoder.finish();
  53561. this.get( bundle ).bundleGPU = bundleGPU;
  53562. // restore render pass state
  53563. renderContextData.currentSets = renderContextData._currentSets;
  53564. renderContextData.currentPass = renderContextData._currentPass;
  53565. }
  53566. /**
  53567. * Adds a render bundle to the render context data.
  53568. *
  53569. * @param {RenderContext} renderContext - The render context.
  53570. * @param {RenderBundle} bundle - The render bundle to add.
  53571. */
  53572. addBundle( renderContext, bundle ) {
  53573. const renderContextData = this.get( renderContext );
  53574. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  53575. }
  53576. // bindings
  53577. /**
  53578. * Creates bindings from the given bind group definition.
  53579. *
  53580. * @param {BindGroup} bindGroup - The bind group.
  53581. * @param {Array<BindGroup>} bindings - Array of bind groups.
  53582. * @param {number} cacheIndex - The cache index.
  53583. * @param {number} version - The version.
  53584. */
  53585. createBindings( bindGroup, bindings, cacheIndex, version ) {
  53586. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  53587. }
  53588. /**
  53589. * Updates the given bind group definition.
  53590. *
  53591. * @param {BindGroup} bindGroup - The bind group.
  53592. * @param {Array<BindGroup>} bindings - Array of bind groups.
  53593. * @param {number} cacheIndex - The cache index.
  53594. * @param {number} version - The version.
  53595. */
  53596. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  53597. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  53598. }
  53599. /**
  53600. * Updates a buffer binding.
  53601. *
  53602. * @param {Buffer} binding - The buffer binding to update.
  53603. */
  53604. updateBinding( binding ) {
  53605. this.bindingUtils.updateBinding( binding );
  53606. }
  53607. // attributes
  53608. /**
  53609. * Creates the buffer of an indexed shader attribute.
  53610. *
  53611. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  53612. */
  53613. createIndexAttribute( attribute ) {
  53614. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  53615. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  53616. usage |= GPUBufferUsage.STORAGE;
  53617. }
  53618. this.attributeUtils.createAttribute( attribute, usage );
  53619. }
  53620. /**
  53621. * Creates the GPU buffer of a shader attribute.
  53622. *
  53623. * @param {BufferAttribute} attribute - The buffer attribute.
  53624. */
  53625. createAttribute( attribute ) {
  53626. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  53627. }
  53628. /**
  53629. * Creates the GPU buffer of a storage attribute.
  53630. *
  53631. * @param {BufferAttribute} attribute - The buffer attribute.
  53632. */
  53633. createStorageAttribute( attribute ) {
  53634. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  53635. }
  53636. /**
  53637. * Creates the GPU buffer of an indirect storage attribute.
  53638. *
  53639. * @param {BufferAttribute} attribute - The buffer attribute.
  53640. */
  53641. createIndirectStorageAttribute( attribute ) {
  53642. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  53643. }
  53644. /**
  53645. * Updates the GPU buffer of a shader attribute.
  53646. *
  53647. * @param {BufferAttribute} attribute - The buffer attribute to update.
  53648. */
  53649. updateAttribute( attribute ) {
  53650. this.attributeUtils.updateAttribute( attribute );
  53651. }
  53652. /**
  53653. * Destroys the GPU buffer of a shader attribute.
  53654. *
  53655. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  53656. */
  53657. destroyAttribute( attribute ) {
  53658. this.attributeUtils.destroyAttribute( attribute );
  53659. }
  53660. // canvas
  53661. /**
  53662. * Triggers an update of the default render pass descriptor.
  53663. */
  53664. updateSize() {
  53665. this.colorBuffer = this.textureUtils.getColorBuffer();
  53666. this.defaultRenderPassdescriptor = null;
  53667. }
  53668. // utils public
  53669. /**
  53670. * Returns the maximum anisotropy texture filtering value.
  53671. *
  53672. * @return {number} The maximum anisotropy texture filtering value.
  53673. */
  53674. getMaxAnisotropy() {
  53675. return 16;
  53676. }
  53677. /**
  53678. * Checks if the given feature is supported by the backend.
  53679. *
  53680. * @param {string} name - The feature's name.
  53681. * @return {boolean} Whether the feature is supported or not.
  53682. */
  53683. hasFeature( name ) {
  53684. return this.device.features.has( name );
  53685. }
  53686. /**
  53687. * Copies data of the given source texture to the given destination texture.
  53688. *
  53689. * @param {Texture} srcTexture - The source texture.
  53690. * @param {Texture} dstTexture - The destination texture.
  53691. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  53692. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  53693. * @param {number} [srcLevel=0] - The mipmap level to copy.
  53694. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  53695. */
  53696. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  53697. let dstX = 0;
  53698. let dstY = 0;
  53699. let dstZ = 0;
  53700. let srcX = 0;
  53701. let srcY = 0;
  53702. let srcZ = 0;
  53703. let srcWidth = srcTexture.image.width;
  53704. let srcHeight = srcTexture.image.height;
  53705. let srcDepth = 1;
  53706. if ( srcRegion !== null ) {
  53707. if ( srcRegion.isBox3 === true ) {
  53708. srcX = srcRegion.min.x;
  53709. srcY = srcRegion.min.y;
  53710. srcZ = srcRegion.min.z;
  53711. srcWidth = srcRegion.max.x - srcRegion.min.x;
  53712. srcHeight = srcRegion.max.y - srcRegion.min.y;
  53713. srcDepth = srcRegion.max.z - srcRegion.min.z;
  53714. } else {
  53715. // Assume it's a Box2
  53716. srcX = srcRegion.min.x;
  53717. srcY = srcRegion.min.y;
  53718. srcWidth = srcRegion.max.x - srcRegion.min.x;
  53719. srcHeight = srcRegion.max.y - srcRegion.min.y;
  53720. srcDepth = 1;
  53721. }
  53722. }
  53723. if ( dstPosition !== null ) {
  53724. dstX = dstPosition.x;
  53725. dstY = dstPosition.y;
  53726. dstZ = dstPosition.z || 0;
  53727. }
  53728. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  53729. const sourceGPU = this.get( srcTexture ).texture;
  53730. const destinationGPU = this.get( dstTexture ).texture;
  53731. encoder.copyTextureToTexture(
  53732. {
  53733. texture: sourceGPU,
  53734. mipLevel: srcLevel,
  53735. origin: { x: srcX, y: srcY, z: srcZ }
  53736. },
  53737. {
  53738. texture: destinationGPU,
  53739. mipLevel: dstLevel,
  53740. origin: { x: dstX, y: dstY, z: dstZ }
  53741. },
  53742. [
  53743. srcWidth,
  53744. srcHeight,
  53745. srcDepth
  53746. ]
  53747. );
  53748. this.device.queue.submit( [ encoder.finish() ] );
  53749. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  53750. this.textureUtils.generateMipmaps( dstTexture );
  53751. }
  53752. }
  53753. /**
  53754. * Copies the current bound framebuffer to the given texture.
  53755. *
  53756. * @param {Texture} texture - The destination texture.
  53757. * @param {RenderContext} renderContext - The render context.
  53758. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  53759. */
  53760. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  53761. const renderContextData = this.get( renderContext );
  53762. let sourceGPU = null;
  53763. if ( renderContext.renderTarget ) {
  53764. if ( texture.isDepthTexture ) {
  53765. sourceGPU = this.get( renderContext.depthTexture ).texture;
  53766. } else {
  53767. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  53768. }
  53769. } else {
  53770. if ( texture.isDepthTexture ) {
  53771. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  53772. } else {
  53773. sourceGPU = this.context.getCurrentTexture();
  53774. }
  53775. }
  53776. const destinationGPU = this.get( texture ).texture;
  53777. if ( sourceGPU.format !== destinationGPU.format ) {
  53778. error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  53779. return;
  53780. }
  53781. let encoder;
  53782. if ( renderContextData.currentPass ) {
  53783. renderContextData.currentPass.end();
  53784. encoder = renderContextData.encoder;
  53785. } else {
  53786. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  53787. }
  53788. encoder.copyTextureToTexture(
  53789. {
  53790. texture: sourceGPU,
  53791. origin: [ rectangle.x, rectangle.y, 0 ],
  53792. },
  53793. {
  53794. texture: destinationGPU
  53795. },
  53796. [
  53797. rectangle.z,
  53798. rectangle.w
  53799. ]
  53800. );
  53801. if ( renderContextData.currentPass ) {
  53802. const { descriptor } = renderContextData;
  53803. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  53804. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  53805. }
  53806. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53807. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53808. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  53809. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53810. if ( renderContext.viewport ) {
  53811. this.updateViewport( renderContext );
  53812. }
  53813. if ( renderContext.scissor ) {
  53814. const { x, y, width, height } = renderContext.scissorValue;
  53815. renderContextData.currentPass.setScissorRect( x, y, width, height );
  53816. }
  53817. } else {
  53818. this.device.queue.submit( [ encoder.finish() ] );
  53819. }
  53820. if ( texture.generateMipmaps ) {
  53821. this.textureUtils.generateMipmaps( texture );
  53822. }
  53823. }
  53824. }
  53825. /**
  53826. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  53827. *
  53828. * @augments SpotLight
  53829. */
  53830. class IESSpotLight extends SpotLight {
  53831. /**
  53832. * Constructs a new IES spot light.
  53833. *
  53834. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  53835. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  53836. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  53837. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  53838. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  53839. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  53840. */
  53841. constructor( color, intensity, distance, angle, penumbra, decay ) {
  53842. super( color, intensity, distance, angle, penumbra, decay );
  53843. /**
  53844. * TODO
  53845. *
  53846. * @type {?Texture}
  53847. * @default null
  53848. */
  53849. this.iesMap = null;
  53850. }
  53851. copy( source, recursive ) {
  53852. super.copy( source, recursive );
  53853. this.iesMap = source.iesMap;
  53854. return this;
  53855. }
  53856. }
  53857. /**
  53858. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  53859. *
  53860. * @augments SpotLight
  53861. */
  53862. class ProjectorLight extends SpotLight {
  53863. /**
  53864. * Constructs a new projector light.
  53865. *
  53866. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  53867. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  53868. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  53869. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  53870. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  53871. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  53872. */
  53873. constructor( color, intensity, distance, angle, penumbra, decay ) {
  53874. super( color, intensity, distance, angle, penumbra, decay );
  53875. /**
  53876. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  53877. *
  53878. * @type {?number}
  53879. * @default null
  53880. */
  53881. this.aspect = null;
  53882. }
  53883. copy( source, recursive ) {
  53884. super.copy( source, recursive );
  53885. this.aspect = source.aspect;
  53886. return this;
  53887. }
  53888. }
  53889. /**
  53890. * This version of a node library represents a basic version
  53891. * just focusing on lights and tone mapping techniques.
  53892. *
  53893. * @private
  53894. * @augments NodeLibrary
  53895. */
  53896. class BasicNodeLibrary extends NodeLibrary {
  53897. /**
  53898. * Constructs a new basic node library.
  53899. */
  53900. constructor() {
  53901. super();
  53902. this.addLight( PointLightNode, PointLight );
  53903. this.addLight( DirectionalLightNode, DirectionalLight );
  53904. this.addLight( RectAreaLightNode, RectAreaLight );
  53905. this.addLight( SpotLightNode, SpotLight );
  53906. this.addLight( AmbientLightNode, AmbientLight );
  53907. this.addLight( HemisphereLightNode, HemisphereLight );
  53908. this.addLight( LightProbeNode, LightProbe );
  53909. this.addLight( IESSpotLightNode, IESSpotLight );
  53910. this.addLight( ProjectorLightNode, ProjectorLight );
  53911. this.addToneMapping( linearToneMapping, LinearToneMapping );
  53912. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  53913. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  53914. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  53915. this.addToneMapping( agxToneMapping, AgXToneMapping );
  53916. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  53917. }
  53918. }
  53919. /**
  53920. * This alternative version of {@link WebGPURenderer} only supports node materials.
  53921. * So classes like `MeshBasicMaterial` are not compatible.
  53922. *
  53923. * @private
  53924. * @augments Renderer
  53925. */
  53926. class WebGPURenderer extends Renderer {
  53927. /**
  53928. * Constructs a new WebGPU renderer.
  53929. *
  53930. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  53931. */
  53932. constructor( parameters = {} ) {
  53933. let BackendClass;
  53934. if ( parameters.forceWebGL ) {
  53935. BackendClass = WebGLBackend;
  53936. } else {
  53937. BackendClass = WebGPUBackend;
  53938. parameters.getFallback = () => {
  53939. warn( 'WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  53940. return new WebGLBackend( parameters );
  53941. };
  53942. }
  53943. const backend = new BackendClass( parameters );
  53944. super( backend, parameters );
  53945. /**
  53946. * The generic default value is overwritten with the
  53947. * standard node library for type mapping. Material
  53948. * mapping is not supported with this version.
  53949. *
  53950. * @type {BasicNodeLibrary}
  53951. */
  53952. this.library = new BasicNodeLibrary();
  53953. /**
  53954. * This flag can be used for type testing.
  53955. *
  53956. * @type {boolean}
  53957. * @readonly
  53958. * @default true
  53959. */
  53960. this.isWebGPURenderer = true;
  53961. }
  53962. }
  53963. /**
  53964. * A specialized group which enables applications access to the
  53965. * Render Bundle API of WebGPU. The group with all its descendant nodes
  53966. * are considered as one render bundle and processed as such by
  53967. * the renderer.
  53968. *
  53969. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  53970. * With a WebGL backend, the group can technically be rendered but without
  53971. * any performance improvements.
  53972. *
  53973. * @augments Group
  53974. */
  53975. class BundleGroup extends Group {
  53976. /**
  53977. * Constructs a new bundle group.
  53978. */
  53979. constructor() {
  53980. super();
  53981. /**
  53982. * This flag can be used for type testing.
  53983. *
  53984. * @type {boolean}
  53985. * @readonly
  53986. * @default true
  53987. */
  53988. this.isBundleGroup = true;
  53989. /**
  53990. * This property is only relevant for detecting types
  53991. * during serialization/deserialization. It should always
  53992. * match the class name.
  53993. *
  53994. * @type {string}
  53995. * @readonly
  53996. * @default 'BundleGroup'
  53997. */
  53998. this.type = 'BundleGroup';
  53999. /**
  54000. * Whether the bundle is static or not. When set to `true`, the structure
  54001. * is assumed to be static and does not change. E.g. no new objects are
  54002. * added to the group
  54003. *
  54004. * If a change is required, an update can still be forced by setting the
  54005. * `needsUpdate` flag to `true`.
  54006. *
  54007. * @type {boolean}
  54008. * @default true
  54009. */
  54010. this.static = true;
  54011. /**
  54012. * The bundle group's version.
  54013. *
  54014. * @type {number}
  54015. * @readonly
  54016. * @default 0
  54017. */
  54018. this.version = 0;
  54019. }
  54020. /**
  54021. * Set this property to `true` when the bundle group has changed.
  54022. *
  54023. * @type {boolean}
  54024. * @default false
  54025. * @param {boolean} value
  54026. */
  54027. set needsUpdate( value ) {
  54028. if ( value === true ) this.version ++;
  54029. }
  54030. }
  54031. /**
  54032. * This module is responsible to manage the post processing setups in apps.
  54033. * You usually create a single instance of this class and use it to define
  54034. * the output of your post processing effect chain.
  54035. * ```js
  54036. * const postProcessing = new PostProcessing( renderer );
  54037. *
  54038. * const scenePass = pass( scene, camera );
  54039. *
  54040. * postProcessing.outputNode = scenePass;
  54041. * ```
  54042. *
  54043. * Note: This module can only be used with `WebGPURenderer`.
  54044. */
  54045. class PostProcessing {
  54046. /**
  54047. * Constructs a new post processing management module.
  54048. *
  54049. * @param {Renderer} renderer - A reference to the renderer.
  54050. * @param {Node<vec4>} outputNode - An optional output node.
  54051. */
  54052. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  54053. /**
  54054. * A reference to the renderer.
  54055. *
  54056. * @type {Renderer}
  54057. */
  54058. this.renderer = renderer;
  54059. /**
  54060. * A node which defines the final output of the post
  54061. * processing. This is usually the last node in a chain
  54062. * of effect nodes.
  54063. *
  54064. * @type {Node<vec4>}
  54065. */
  54066. this.outputNode = outputNode;
  54067. /**
  54068. * Whether the default output tone mapping and color
  54069. * space transformation should be enabled or not.
  54070. *
  54071. * It is enabled by default by it must be disabled when
  54072. * effects must be executed after tone mapping and color
  54073. * space conversion. A typical example is FXAA which
  54074. * requires sRGB input.
  54075. *
  54076. * When set to `false`, the app must control the output
  54077. * transformation with `RenderOutputNode`.
  54078. *
  54079. * ```js
  54080. * const outputPass = renderOutput( scenePass );
  54081. * ```
  54082. *
  54083. * @type {boolean}
  54084. */
  54085. this.outputColorTransform = true;
  54086. /**
  54087. * Must be set to `true` when the output node changes.
  54088. *
  54089. * @type {Node<vec4>}
  54090. */
  54091. this.needsUpdate = true;
  54092. const material = new NodeMaterial();
  54093. material.name = 'PostProcessing';
  54094. /**
  54095. * The full screen quad that is used to render
  54096. * the effects.
  54097. *
  54098. * @private
  54099. * @type {QuadMesh}
  54100. */
  54101. this._quadMesh = new QuadMesh( material );
  54102. /**
  54103. * The context of the post processing stack.
  54104. *
  54105. * @private
  54106. * @type {?Object}
  54107. * @default null
  54108. */
  54109. this._context = null;
  54110. }
  54111. /**
  54112. * When `PostProcessing` is used to apply post processing effects,
  54113. * the application must use this version of `render()` inside
  54114. * its animation loop (not the one from the renderer).
  54115. */
  54116. render() {
  54117. const renderer = this.renderer;
  54118. this._update();
  54119. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  54120. const toneMapping = renderer.toneMapping;
  54121. const outputColorSpace = renderer.outputColorSpace;
  54122. renderer.toneMapping = NoToneMapping;
  54123. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  54124. //
  54125. const currentXR = renderer.xr.enabled;
  54126. renderer.xr.enabled = false;
  54127. this._quadMesh.render( renderer );
  54128. renderer.xr.enabled = currentXR;
  54129. //
  54130. renderer.toneMapping = toneMapping;
  54131. renderer.outputColorSpace = outputColorSpace;
  54132. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  54133. }
  54134. /**
  54135. * Returns the current context of the post processing stack.
  54136. *
  54137. * @readonly
  54138. * @type {?Object}
  54139. */
  54140. get context() {
  54141. return this._context;
  54142. }
  54143. /**
  54144. * Frees internal resources.
  54145. */
  54146. dispose() {
  54147. this._quadMesh.material.dispose();
  54148. }
  54149. /**
  54150. * Updates the state of the module.
  54151. *
  54152. * @private
  54153. */
  54154. _update() {
  54155. if ( this.needsUpdate === true ) {
  54156. const renderer = this.renderer;
  54157. const toneMapping = renderer.toneMapping;
  54158. const outputColorSpace = renderer.outputColorSpace;
  54159. const context = {
  54160. postProcessing: this,
  54161. onBeforePostProcessing: null,
  54162. onAfterPostProcessing: null
  54163. };
  54164. let outputNode = this.outputNode;
  54165. if ( this.outputColorTransform === true ) {
  54166. outputNode = outputNode.context( context );
  54167. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  54168. } else {
  54169. context.toneMapping = toneMapping;
  54170. context.outputColorSpace = outputColorSpace;
  54171. outputNode = outputNode.context( context );
  54172. }
  54173. this._context = context;
  54174. this._quadMesh.material.fragmentNode = outputNode;
  54175. this._quadMesh.material.needsUpdate = true;
  54176. this.needsUpdate = false;
  54177. }
  54178. }
  54179. /**
  54180. * When `PostProcessing` is used to apply post processing effects,
  54181. * the application must use this version of `renderAsync()` inside
  54182. * its animation loop (not the one from the renderer).
  54183. *
  54184. * @async
  54185. * @return {Promise} A Promise that resolves when the render has been finished.
  54186. */
  54187. async renderAsync() {
  54188. this._update();
  54189. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  54190. const renderer = this.renderer;
  54191. const toneMapping = renderer.toneMapping;
  54192. const outputColorSpace = renderer.outputColorSpace;
  54193. renderer.toneMapping = NoToneMapping;
  54194. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  54195. //
  54196. const currentXR = renderer.xr.enabled;
  54197. renderer.xr.enabled = false;
  54198. await this._quadMesh.renderAsync( renderer );
  54199. renderer.xr.enabled = currentXR;
  54200. //
  54201. renderer.toneMapping = toneMapping;
  54202. renderer.outputColorSpace = outputColorSpace;
  54203. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  54204. }
  54205. }
  54206. /**
  54207. * This special type of texture is intended for compute shaders.
  54208. * It can be used to compute the data of a texture with a compute shader.
  54209. *
  54210. * Note: This type of texture can only be used with `WebGPURenderer`
  54211. * and a WebGPU backend.
  54212. *
  54213. * @augments Texture
  54214. */
  54215. class StorageTexture extends Texture {
  54216. /**
  54217. * Constructs a new storage texture.
  54218. *
  54219. * @param {number} [width=1] - The storage texture's width.
  54220. * @param {number} [height=1] - The storage texture's height.
  54221. */
  54222. constructor( width = 1, height = 1 ) {
  54223. super();
  54224. /**
  54225. * The image object which just represents the texture's dimension.
  54226. *
  54227. * @type {{width: number, height: number}}
  54228. */
  54229. this.image = { width, height };
  54230. /**
  54231. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  54232. *
  54233. * @type {number}
  54234. */
  54235. this.magFilter = LinearFilter;
  54236. /**
  54237. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  54238. *
  54239. * @type {number}
  54240. */
  54241. this.minFilter = LinearFilter;
  54242. /**
  54243. * This flag can be used for type testing.
  54244. *
  54245. * @type {boolean}
  54246. * @readonly
  54247. * @default true
  54248. */
  54249. this.isStorageTexture = true;
  54250. }
  54251. /**
  54252. * Sets the size of the storage texture.
  54253. *
  54254. * @param {number} width - The new width of the storage texture.
  54255. * @param {number} height - The new height of the storage texture.
  54256. */
  54257. setSize( width, height ) {
  54258. if ( this.image.width !== width || this.image.height !== height ) {
  54259. this.image.width = width;
  54260. this.image.height = height;
  54261. this.dispose();
  54262. }
  54263. }
  54264. }
  54265. /**
  54266. * This special type of buffer attribute is intended for compute shaders.
  54267. * It can be used to encode draw parameters for indirect draw calls.
  54268. *
  54269. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  54270. * and a WebGPU backend.
  54271. *
  54272. * @augments StorageBufferAttribute
  54273. */
  54274. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  54275. /**
  54276. * Constructs a new storage buffer attribute.
  54277. *
  54278. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  54279. * The subsequent parameter is then obsolete.
  54280. * @param {number} itemSize - The item size.
  54281. */
  54282. constructor( count, itemSize ) {
  54283. super( count, itemSize, Uint32Array );
  54284. /**
  54285. * This flag can be used for type testing.
  54286. *
  54287. * @type {boolean}
  54288. * @readonly
  54289. * @default true
  54290. */
  54291. this.isIndirectStorageBufferAttribute = true;
  54292. }
  54293. }
  54294. /**
  54295. * A loader for loading node objects in the three.js JSON Object/Scene format.
  54296. *
  54297. * @augments Loader
  54298. */
  54299. class NodeLoader extends Loader {
  54300. /**
  54301. * Constructs a new node loader.
  54302. *
  54303. * @param {LoadingManager} [manager] - A reference to a loading manager.
  54304. */
  54305. constructor( manager ) {
  54306. super( manager );
  54307. /**
  54308. * Represents a dictionary of textures.
  54309. *
  54310. * @type {Object<string,Texture>}
  54311. */
  54312. this.textures = {};
  54313. /**
  54314. * Represents a dictionary of node types.
  54315. *
  54316. * @type {Object<string,Node.constructor>}
  54317. */
  54318. this.nodes = {};
  54319. }
  54320. /**
  54321. * Loads the node definitions from the given URL.
  54322. *
  54323. * @param {string} url - The path/URL of the file to be loaded.
  54324. * @param {Function} onLoad - Will be called when load completes.
  54325. * @param {Function} onProgress - Will be called while load progresses.
  54326. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  54327. */
  54328. load( url, onLoad, onProgress, onError ) {
  54329. const loader = new FileLoader( this.manager );
  54330. loader.setPath( this.path );
  54331. loader.setRequestHeader( this.requestHeader );
  54332. loader.setWithCredentials( this.withCredentials );
  54333. loader.load( url, ( text ) => {
  54334. try {
  54335. onLoad( this.parse( JSON.parse( text ) ) );
  54336. } catch ( e ) {
  54337. if ( onError ) {
  54338. onError( e );
  54339. } else {
  54340. error( e );
  54341. }
  54342. this.manager.itemError( url );
  54343. }
  54344. }, onProgress, onError );
  54345. }
  54346. /**
  54347. * Parse the node dependencies for the loaded node.
  54348. *
  54349. * @param {Array<Object>} [json] - The JSON definition
  54350. * @return {Object<string,Node>} A dictionary with node dependencies.
  54351. */
  54352. parseNodes( json ) {
  54353. const nodes = {};
  54354. if ( json !== undefined ) {
  54355. for ( const nodeJSON of json ) {
  54356. const { uuid, type } = nodeJSON;
  54357. nodes[ uuid ] = this.createNodeFromType( type );
  54358. nodes[ uuid ].uuid = uuid;
  54359. }
  54360. const meta = { nodes, textures: this.textures };
  54361. for ( const nodeJSON of json ) {
  54362. nodeJSON.meta = meta;
  54363. const node = nodes[ nodeJSON.uuid ];
  54364. node.deserialize( nodeJSON );
  54365. delete nodeJSON.meta;
  54366. }
  54367. }
  54368. return nodes;
  54369. }
  54370. /**
  54371. * Parses the node from the given JSON.
  54372. *
  54373. * @param {Object} json - The JSON definition
  54374. * @param {string} json.type - The node type.
  54375. * @param {string} json.uuid - The node UUID.
  54376. * @param {Array<Object>} [json.nodes] - The node dependencies.
  54377. * @param {Object} [json.meta] - The meta data.
  54378. * @return {Node} The parsed node.
  54379. */
  54380. parse( json ) {
  54381. const node = this.createNodeFromType( json.type );
  54382. node.uuid = json.uuid;
  54383. const nodes = this.parseNodes( json.nodes );
  54384. const meta = { nodes, textures: this.textures };
  54385. json.meta = meta;
  54386. node.deserialize( json );
  54387. delete json.meta;
  54388. return node;
  54389. }
  54390. /**
  54391. * Defines the dictionary of textures.
  54392. *
  54393. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  54394. * @return {NodeLoader} A reference to this loader.
  54395. */
  54396. setTextures( value ) {
  54397. this.textures = value;
  54398. return this;
  54399. }
  54400. /**
  54401. * Defines the dictionary of node types.
  54402. *
  54403. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54404. * @return {NodeLoader} A reference to this loader.
  54405. */
  54406. setNodes( value ) {
  54407. this.nodes = value;
  54408. return this;
  54409. }
  54410. /**
  54411. * Creates a node object from the given type.
  54412. *
  54413. * @param {string} type - The node type.
  54414. * @return {Node} The created node instance.
  54415. */
  54416. createNodeFromType( type ) {
  54417. if ( this.nodes[ type ] === undefined ) {
  54418. error( 'NodeLoader: Node type not found:', type );
  54419. return float();
  54420. }
  54421. return nodeObject( new this.nodes[ type ]() );
  54422. }
  54423. }
  54424. /**
  54425. * A special type of material loader for loading node materials.
  54426. *
  54427. * @augments MaterialLoader
  54428. */
  54429. class NodeMaterialLoader extends MaterialLoader {
  54430. /**
  54431. * Constructs a new node material loader.
  54432. *
  54433. * @param {LoadingManager} [manager] - A reference to a loading manager.
  54434. */
  54435. constructor( manager ) {
  54436. super( manager );
  54437. /**
  54438. * Represents a dictionary of node types.
  54439. *
  54440. * @type {Object<string,Node.constructor>}
  54441. */
  54442. this.nodes = {};
  54443. /**
  54444. * Represents a dictionary of node material types.
  54445. *
  54446. * @type {Object<string,NodeMaterial.constructor>}
  54447. */
  54448. this.nodeMaterials = {};
  54449. }
  54450. /**
  54451. * Parses the node material from the given JSON.
  54452. *
  54453. * @param {Object} json - The JSON definition
  54454. * @return {NodeMaterial}. The parsed material.
  54455. */
  54456. parse( json ) {
  54457. const material = super.parse( json );
  54458. const nodes = this.nodes;
  54459. const inputNodes = json.inputNodes;
  54460. for ( const property in inputNodes ) {
  54461. const uuid = inputNodes[ property ];
  54462. material[ property ] = nodes[ uuid ];
  54463. }
  54464. return material;
  54465. }
  54466. /**
  54467. * Defines the dictionary of node types.
  54468. *
  54469. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54470. * @return {NodeLoader} A reference to this loader.
  54471. */
  54472. setNodes( value ) {
  54473. this.nodes = value;
  54474. return this;
  54475. }
  54476. /**
  54477. * Defines the dictionary of node material types.
  54478. *
  54479. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  54480. * @return {NodeLoader} A reference to this loader.
  54481. */
  54482. setNodeMaterials( value ) {
  54483. this.nodeMaterials = value;
  54484. return this;
  54485. }
  54486. /**
  54487. * Creates a node material from the given type.
  54488. *
  54489. * @param {string} type - The node material type.
  54490. * @return {Node} The created node material instance.
  54491. */
  54492. createMaterialFromType( type ) {
  54493. const materialClass = this.nodeMaterials[ type ];
  54494. if ( materialClass !== undefined ) {
  54495. return new materialClass();
  54496. }
  54497. return super.createMaterialFromType( type );
  54498. }
  54499. }
  54500. /**
  54501. * A special type of object loader for loading 3D objects using
  54502. * node materials.
  54503. *
  54504. * @augments ObjectLoader
  54505. */
  54506. class NodeObjectLoader extends ObjectLoader {
  54507. /**
  54508. * Constructs a new node object loader.
  54509. *
  54510. * @param {LoadingManager} [manager] - A reference to a loading manager.
  54511. */
  54512. constructor( manager ) {
  54513. super( manager );
  54514. /**
  54515. * Represents a dictionary of node types.
  54516. *
  54517. * @type {Object<string,Node.constructor>}
  54518. */
  54519. this.nodes = {};
  54520. /**
  54521. * Represents a dictionary of node material types.
  54522. *
  54523. * @type {Object<string,NodeMaterial.constructor>}
  54524. */
  54525. this.nodeMaterials = {};
  54526. /**
  54527. * A reference to hold the `nodes` JSON property.
  54528. *
  54529. * @private
  54530. * @type {?Object[]}
  54531. */
  54532. this._nodesJSON = null;
  54533. }
  54534. /**
  54535. * Defines the dictionary of node types.
  54536. *
  54537. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54538. * @return {NodeObjectLoader} A reference to this loader.
  54539. */
  54540. setNodes( value ) {
  54541. this.nodes = value;
  54542. return this;
  54543. }
  54544. /**
  54545. * Defines the dictionary of node material types.
  54546. *
  54547. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  54548. * @return {NodeObjectLoader} A reference to this loader.
  54549. */
  54550. setNodeMaterials( value ) {
  54551. this.nodeMaterials = value;
  54552. return this;
  54553. }
  54554. /**
  54555. * Parses the node objects from the given JSON.
  54556. *
  54557. * @param {Object} json - The JSON definition
  54558. * @param {Function} onLoad - The onLoad callback function.
  54559. * @return {Object3D}. The parsed 3D object.
  54560. */
  54561. parse( json, onLoad ) {
  54562. this._nodesJSON = json.nodes;
  54563. const data = super.parse( json, onLoad );
  54564. this._nodesJSON = null; // dispose
  54565. return data;
  54566. }
  54567. /**
  54568. * Parses the node objects from the given JSON and textures.
  54569. *
  54570. * @param {Object[]} json - The JSON definition
  54571. * @param {Object<string,Texture>} textures - The texture library.
  54572. * @return {Object<string,Node>}. The parsed nodes.
  54573. */
  54574. parseNodes( json, textures ) {
  54575. if ( json !== undefined ) {
  54576. const loader = new NodeLoader();
  54577. loader.setNodes( this.nodes );
  54578. loader.setTextures( textures );
  54579. return loader.parseNodes( json );
  54580. }
  54581. return {};
  54582. }
  54583. /**
  54584. * Parses the node objects from the given JSON and textures.
  54585. *
  54586. * @param {Object} json - The JSON definition
  54587. * @param {Object<string,Texture>} textures - The texture library.
  54588. * @return {Object<string,NodeMaterial>}. The parsed materials.
  54589. */
  54590. parseMaterials( json, textures ) {
  54591. const materials = {};
  54592. if ( json !== undefined ) {
  54593. const nodes = this.parseNodes( this._nodesJSON, textures );
  54594. const loader = new NodeMaterialLoader();
  54595. loader.setTextures( textures );
  54596. loader.setNodes( nodes );
  54597. loader.setNodeMaterials( this.nodeMaterials );
  54598. for ( let i = 0, l = json.length; i < l; i ++ ) {
  54599. const data = json[ i ];
  54600. materials[ data.uuid ] = loader.parse( data );
  54601. }
  54602. }
  54603. return materials;
  54604. }
  54605. }
  54606. /**
  54607. * In earlier three.js versions, clipping was defined globally
  54608. * on the renderer or on material level. This special version of
  54609. * `THREE.Group` allows to encode the clipping state into the scene
  54610. * graph. Meaning if you create an instance of this group, all
  54611. * descendant 3D objects will be affected by the respective clipping
  54612. * planes.
  54613. *
  54614. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  54615. *
  54616. * @augments Group
  54617. */
  54618. class ClippingGroup extends Group {
  54619. /**
  54620. * Constructs a new clipping group.
  54621. */
  54622. constructor() {
  54623. super();
  54624. /**
  54625. * This flag can be used for type testing.
  54626. *
  54627. * @type {boolean}
  54628. * @readonly
  54629. * @default true
  54630. */
  54631. this.isClippingGroup = true;
  54632. /**
  54633. * An array with clipping planes.
  54634. *
  54635. * @type {Array<Plane>}
  54636. */
  54637. this.clippingPlanes = [];
  54638. /**
  54639. * Whether clipping should be enabled or not.
  54640. *
  54641. * @type {boolean}
  54642. * @default true
  54643. */
  54644. this.enabled = true;
  54645. /**
  54646. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  54647. *
  54648. * @type {boolean}
  54649. * @default false
  54650. */
  54651. this.clipIntersection = false;
  54652. /**
  54653. * Whether shadows should be clipped or not.
  54654. *
  54655. * @type {boolean}
  54656. * @default false
  54657. */
  54658. this.clipShadows = false;
  54659. }
  54660. }
  54661. 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, CacheNode, Camera, 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, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, 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, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, error, log$1 as log, shaderStages, vectorComponents, warn, warnOnce };
粤ICP备19079148号